times portada

packs2
DEV 3 years ago
parent 7669987b25
commit 207e58c9fe

@ -24,7 +24,7 @@
package main
import (
"activething.com/go/gogo/core/errs"
"activething.com/go/gogo/core/bins/bfields"
"activething.com/go/gogo/core/results"
"activething.com/go/gogo/packs/pjson"
"crypto/aes"
@ -54,7 +54,7 @@ func (e encrypter) Encrypt (data []byte) results.Bytes {
ct := make([]byte,aes.BlockSize+len(data))
iv := ct[:aes.BlockSize]
if _, er = io.ReadFull(rand.Reader, iv); er != nil {
return results.MakeBytesError(fmt.Errorf("could not encrypt: %v", er))
return results.DoBytesError(fmt.Errorf("could not encrypt: %v", er))
}
st := cipher.NewCFBEncrypter(b,iv)
st.XORKeyStream(ct[aes.BlockSize:],data)
@ -91,6 +91,7 @@ func main() {
en := encrypter{key: []byte{0,1,2,3,45,6,6,7,8,9,0,1,1,1,1,1}}
pk := pjson.NewPacker(pjson.PackerWithEncrypter(en))
//pk := pjson.NewPacker()
t := A {
CampoInt: 23,
@ -118,7 +119,7 @@ func main() {
},flags)
},0)
errs.Test(pk.Error(),true)
errs.Test(pk.ErrorResult(),true)
fmt.Printf("Paquete %s\n",pk.Packet())
*/
@ -128,14 +129,14 @@ func main() {
pk.PackAny(t,0)
errs.Test(pk.Error(),true)
//errs.Test(pk.Cause(),true)
fmt.Printf("Paquete %s\n",pk.Packet())
/*
res := en.Encrypt([]byte("Esto debe de ir encruptdao"))
if res.IsError() {
panic(res.Error())
panic(res.ErrorResult())
}
dt := string(res.Success())
fmt.Printf("seguro %s\n",dt)
@ -146,6 +147,11 @@ func main() {
}
fmt.Printf("decrupt %s\n",st)
*/
f,_ := bfields.NewBField([]byte("MiNombre"),[]byte("221100"))
fmt.Printf("field :%s\n",f.String())
}

@ -57,8 +57,8 @@ func BenchmarkHtmlPacker(b *testing.B) {
for i := 0; i < b.N; i++ {
packer.Pack(s)
if packer.Error() != nil {
panic(packer.Error())
if packer.Cause() != nil {
panic(packer.Cause())
}
packer.Reset()
}
@ -87,8 +87,8 @@ func BenchmarkJsonMarshal(b *testing.B) {
func BenchmarkMapPacker(b *testing.B) {
for i := 0; i < b.N; i++ {
packer.Pack(mp)
if packer.Error() != nil {
panic(packer.Error())
if packer.Cause() != nil {
panic(packer.Cause())
}
packer.Reset()
}

@ -24,6 +24,7 @@
package bins
type (
Appender interface {
Append(data []byte) []byte
}
@ -31,6 +32,6 @@ type (
AppendFnc func(data []byte) []byte
)
func (f AppendFnc) Append(data []byte) []byte {
return f(data)
}
return f(data) }

@ -0,0 +1,68 @@
// ------------------------------------------------------------------------
// Project atila
// Active Thing (activething.com) git.activething.com/go
//
// File name bfield.go
// Created by DEV
// Modified 19/02/2024
//
// Copyright 2024 activething.com
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------
package bfields
type (
BField struct {
name []byte
value []byte
}
)
func NewBField (name, value []byte) (*BField,error) {
if len(name) == 0 {
return nil,G.ErrInvalidName
}
return &BField {
name: append(make([]byte,0,len(name)),name...),
value: append(make([]byte,0,len(value)),value...),
},nil
}
func (f BField) Name () []byte {
return f.name }
func (f BField) Value() []byte {
return f.value }
func (f BField) String () string {
r := make([]byte,len(f.name)+len(f.value)+1)
copy(r,f.name)
r[len(f.name)]=':'
copy(r[:len(f.name)+1],f.value)
return string(r)
}

@ -0,0 +1,48 @@
// ------------------------------------------------------------------------
// Project atila
// Active Thing (activething.com) git.activething.com/go
//
// File name gogo.go
// Created by DEV
// Modified 19/02/2024
//
// Copyright 2024 activething.com
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------
package bfields
import "activething.com/go/gogo/core/errs"
var (
G = struct {
ErrInvalidName errs.ErrCode
ErrBFieldDuplicated errs.ErrCode
ErrFixed errs.ErrCode
ErrReadOnly errs.ErrCode
}{
ErrInvalidName : errs.ErrCode("core:bins.bfields.invalid-name"),
ErrBFieldDuplicated : errs.ErrCode("core:bins.bfields.duplicated-field"),
ErrFixed : errs.ErrCode("core:bins.bfields.fixed"),
ErrReadOnly : errs.ErrCode("core:bins.bfields.read-only"),
}
)

@ -36,34 +36,38 @@ const (
MinRead = 512
)
type (
Buffer struct {
data []byte
off int
ini [64]byte
lastOp bufferOp
}
)
func NewBuffer() *Buffer {
return &Buffer{}
}
return &Buffer{} }
func (b *Buffer) Len() int {
return len(b.data) - b.off
}
return len(b.data) - b.off }
func (b *Buffer) Cap() int {
return cap(b.data)
}
return cap(b.data) }
func (b *Buffer) isEmpty() bool {
return len(b.data) <= b.off
}
return len(b.data) <= b.off }
func (b *Buffer) Bytes() []byte {
return b.data[b.off:]
}
return b.data[b.off:] }
func (b *Buffer) String() string {
if b == nil {
@ -72,12 +76,14 @@ func (b *Buffer) String() string {
return string(b.data[b.off:])
}
func (b *Buffer) Reset() {
b.data = b.data[:0]
b.off = 0
b.lastOp = opInvalid
}
func (b *Buffer) Truncate(size int) {
if size == 0 {
b.Reset()
@ -90,6 +96,7 @@ func (b *Buffer) Truncate(size int) {
b.data = b.data[:b.off+size]
}
func (b *Buffer) Read(data []byte) (count int, err error) {
b.lastOp = opInvalid
if b.isEmpty() {
@ -107,6 +114,7 @@ func (b *Buffer) Read(data []byte) (count int, err error) {
return count, nil
}
func (b *Buffer) ReadFrom(reader io.Reader) (count int64, err error) {
b.lastOp = opInvalid
for {
@ -127,6 +135,7 @@ func (b *Buffer) ReadFrom(reader io.Reader) (count int64, err error) {
}
}
func (b *Buffer) ReadByte() (byte, error) {
if b.isEmpty() {
b.Reset()
@ -138,17 +147,20 @@ func (b *Buffer) ReadByte() (byte, error) {
return c, nil
}
func (b *Buffer) ReadBytes(delimiter byte) (result []byte, er error) {
slice, er := b.readSlice(delimiter)
result = append(result, slice...)
return result, er
}
func (b *Buffer) ReadString(delimiter byte) (result string, err error) {
slice, err := b.readSlice(delimiter)
return string(slice), err
}
func (b *Buffer) ReadRune() (run rune, size int, err error) {
if b.isEmpty() {
b.Reset()
@ -166,6 +178,7 @@ func (b *Buffer) ReadRune() (run rune, size int, err error) {
return r, n, nil
}
func (b *Buffer) readSlice(delimiter byte) (ln []byte, er error) {
i := bytes.IndexByte(b.data[b.off:], delimiter)
end := b.off + i + 1
@ -179,6 +192,7 @@ func (b *Buffer) readSlice(delimiter byte) (ln []byte, er error) {
return ln, er
}
func (b *Buffer) UnreadRune() error {
if b.lastOp <= opInvalid {
return G.ErrUnreadInvalid
@ -190,6 +204,7 @@ func (b *Buffer) UnreadRune() error {
return nil
}
func (b *Buffer) UnreadByte() error {
if b.lastOp == opInvalid {
return G.ErrUnreadInvalid
@ -201,6 +216,7 @@ func (b *Buffer) UnreadByte() error {
return nil
}
func (b *Buffer) AppendWith(appender Appender) {
b.lastOp = opInvalid
if appender != nil {
@ -208,6 +224,7 @@ func (b *Buffer) AppendWith(appender Appender) {
}
}
func (b *Buffer) Write(value []byte) (int, error) {
b.lastOp = opInvalid
return copy(b.data[b.tryGrow(len(value)):], value), nil
@ -219,6 +236,7 @@ func (b *Buffer) W (value []byte) {
copy(b.data[b.tryGrow(len(value)):], value)
}
// WOQ With Optional Quoted
func (b *Buffer) WOQ (add bool, quote byte, value []byte) {
b.lastOp = opInvalid
@ -233,7 +251,7 @@ func (b *Buffer) WOQ (add bool, quote byte, value []byte) {
}
func (b *Buffer) WriteHTMLScape (source []byte) {
func (b *Buffer) WriteHTML(source []byte) {
st := 0
for i,c := range source {
if c == '<' || c == '>' || c == '&' {
@ -265,6 +283,7 @@ func (b *Buffer) WriteByte(value byte) {
b.data[b.tryGrow(1)] = value
}
func (b *Buffer) Write2Byte(valueA, valueB byte) {
b.lastOp = opInvalid
p := b.tryGrow(2)
@ -272,17 +291,17 @@ func (b *Buffer) Write2Byte(valueA, valueB byte) {
b.data[p+1] = valueB
}
func (b *Buffer) WriteString(value string) {
b.W([]byte(value))
}
b.W([]byte(value)) }
func (b *Buffer) WriteTo(writer io.Writer) (int64, error) {
return b.writeTo(writer, false)
}
return b.writeTo(writer, false) }
func (b *Buffer) FlushTo(writer io.Writer) (int64, error) {
return b.writeTo(writer, true)
}
return b.writeTo(writer, true) }
@ -314,6 +333,7 @@ func (b *Buffer) writeTo(writer io.Writer, reset bool) (count int64, err error)
return count, nil
}
func (b *Buffer) tryGrow(size int) int {
m := len(b.data)
if size <= cap(b.data)-m {
@ -346,6 +366,7 @@ func (b *Buffer) tryGrow(size int) int {
return m
}
func (b *Buffer) tryGrowByResize(size int) (int, bool) {
if l := len(b.data); size <= cap(b.data)-l {
b.data = b.data[:l+size]
@ -354,6 +375,7 @@ func (b *Buffer) tryGrowByResize(size int) (int, bool) {
return 0, false
}
func (b *Buffer) tryGrowByStrategy(size int) int {
m := len(b.data)
if m == 0 && b.off != 0 {
@ -384,6 +406,7 @@ func (b *Buffer) tryGrowByStrategy(size int) int {
return m
}
func makeSlice(size int) (result []byte) {
dn := false
defer func(d *bool) {

@ -23,11 +23,5 @@
package bins
const (
opRead bufferOp = -1 // Any other read operation.
opInvalid bufferOp = 0 // Non-read operation.
opRune bufferOp = 1 // Decode rune of size 1.
)
type bufferOp int8

@ -31,16 +31,7 @@ import (
"sync/atomic"
)
const (
minBitSize = 6
minSize = 1 << minBitSize
maxSize = 1 << (minBitSize + poolSteps - 1)
poolSteps = 20
poolThreshold = 42000
poolPercentile = 0.95
)
type (
@ -62,24 +53,24 @@ type (
)
func NewBufferPool(options ...opts.OptionFnc[BufferPool]) *BufferPool {
return opts.Apply(&BufferPool{percentile: poolPercentile}, options...)
}
return opts.Apply(&BufferPool{percentile: poolPercentile}, options...) }
func (p *BufferPool) MaxSize() uint64 {
return atomic.LoadUint64(&p.maxSize)
}
return atomic.LoadUint64(&p.maxSize) }
func (p *BufferPool) DefSize() uint64 {
return atomic.LoadUint64(&p.defSize)
}
return atomic.LoadUint64(&p.defSize) }
func (p *BufferPool) MaxPercentile() float32 {
return p.percentile
}
return p.percentile }
func (p *BufferPool) CallsThreshold() uint64 {
return atomic.LoadUint64(&p.threshold)
}
return atomic.LoadUint64(&p.threshold) }
func (p *BufferPool) Get() *Buffer {
b := p.inner.Get()
@ -91,6 +82,7 @@ func (p *BufferPool) Get() *Buffer {
return b.(*Buffer)
}
func (p *BufferPool) Put(buffer *Buffer) {
if buffer == nil {
return
@ -106,6 +98,7 @@ func (p *BufferPool) Put(buffer *Buffer) {
p.AddReleased()
}
func (p *BufferPool) calibrate() {
if atomic.CompareAndSwapUint64(&p.calibra, 0, 1) {
return
@ -143,6 +136,7 @@ func (p *BufferPool) calibrate() {
atomic.StoreUint64(&p.calibra, 0)
}
func index(n int) int {
n--
n >>= minBitSize

@ -34,6 +34,7 @@ func BufferPoolWithMaxPercentile(percentile float32) opts.OptionFnc[BufferPool]
}
}
func BufferPoolWithCallsThreshold(threshold uint64) opts.OptionFnc[BufferPool] {
return func(b *BufferPool) {
atomic.StoreUint64(&b.threshold, threshold)

@ -29,6 +29,8 @@ import (
"time"
)
func (b *Buffer) WriteBool(value bool) {
if value {
b.WriteByte(1)
@ -37,10 +39,12 @@ func (b *Buffer) WriteBool(value bool) {
}
}
func (b *Buffer) WriteRune(value rune, byteOrder binary.ByteOrder) {
b.WriteUint32(uint32(value), byteOrder)
}
func (b *Buffer) WriteUint16(value uint16, byteOrder binary.ByteOrder) {
b.lastOp = opInvalid
if byteOrder == nil {
@ -49,6 +53,7 @@ func (b *Buffer) WriteUint16(value uint16, byteOrder binary.ByteOrder) {
byteOrder.PutUint16(b.data[b.tryGrow(2):], value)
}
func (b *Buffer) WriteUint32(value uint32, byteOrder binary.ByteOrder) {
b.lastOp = opInvalid
if byteOrder == nil {
@ -57,6 +62,7 @@ func (b *Buffer) WriteUint32(value uint32, byteOrder binary.ByteOrder) {
byteOrder.PutUint32(b.data[b.tryGrow(4):], value)
}
func (b *Buffer) WriteUint64(value uint64, byteOrder binary.ByteOrder) {
if byteOrder == nil {
byteOrder = binary.LittleEndian
@ -64,25 +70,26 @@ func (b *Buffer) WriteUint64(value uint64, byteOrder binary.ByteOrder) {
byteOrder.PutUint64(b.data[b.tryGrow(8):], value)
}
func (b *Buffer) WriteInt16(value int16, byteOrder binary.ByteOrder) {
b.WriteUint16(uint16(value), byteOrder)
}
b.WriteUint16(uint16(value), byteOrder) }
func (b *Buffer) WriteInt32(value int32, byteOrder binary.ByteOrder) {
b.WriteUint32(uint32(value), byteOrder)
}
b.WriteUint32(uint32(value), byteOrder) }
func (b *Buffer) WriteInt64(value int64, byteOrder binary.ByteOrder) {
b.WriteUint64(uint64(value), byteOrder)
}
b.WriteUint64(uint64(value), byteOrder) }
func (b *Buffer) WriteFloat32(value float32, byteOrder binary.ByteOrder) {
b.WriteUint32(math.Float32bits(value), byteOrder)
}
b.WriteUint32(math.Float32bits(value), byteOrder) }
func (b *Buffer) WriteFloat64(value float64, byteOrder binary.ByteOrder) {
b.WriteUint64(math.Float64bits(value), byteOrder)
}
b.WriteUint64(math.Float64bits(value), byteOrder) }
func (b *Buffer) WriteComplex64(value complex64, byteOrder binary.ByteOrder) {
b.lastOp = opInvalid
@ -94,6 +101,7 @@ func (b *Buffer) WriteComplex64(value complex64, byteOrder binary.ByteOrder) {
byteOrder.PutUint32(b.data[l+4:], math.Float32bits(imag(value)))
}
func (b *Buffer) WriteComplex128(value complex128, byteOrder binary.ByteOrder) {
b.lastOp = opInvalid
if byteOrder == nil {
@ -104,6 +112,7 @@ func (b *Buffer) WriteComplex128(value complex128, byteOrder binary.ByteOrder) {
byteOrder.PutUint64(b.data[l+4:], math.Float64bits(imag(value)))
}
func (b *Buffer) WriteTime(value time.Time) error {
b.lastOp = opInvalid
d, e := value.MarshalBinary()
@ -114,6 +123,6 @@ func (b *Buffer) WriteTime(value time.Time) error {
return nil
}
func (b *Buffer) WriteDuration(val time.Duration) {
b.WriteInt64(int64(val), binary.LittleEndian)
}
b.WriteInt64(int64(val), binary.LittleEndian) }

@ -28,11 +28,13 @@ import (
"unicode/utf8"
)
func (b *Buffer) WriteBoolStr(value bool) {
b.lastOp = opInvalid
b.data = strconv.AppendBool(b.data, value)
}
func (b *Buffer) WriteRuneStr(value rune) int {
if value < utf8.RuneSelf {
b.WriteByte(byte(value))
@ -45,6 +47,7 @@ func (b *Buffer) WriteRuneStr(value rune) int {
return cn
}
func (b *Buffer) WriteUIntStr(value uint64, base int) {
b.lastOp = opInvalid
if base == 0 {
@ -53,6 +56,7 @@ func (b *Buffer) WriteUIntStr(value uint64, base int) {
b.data = strconv.AppendUint(b.data, value, base)
}
func (b *Buffer) WriteIntStr(value int64, base int) {
b.lastOp = opInvalid
if base == 0 {
@ -61,6 +65,7 @@ func (b *Buffer) WriteIntStr(value int64, base int) {
b.data = strconv.AppendInt(b.data, value, base)
}
func (b *Buffer) WriteFloatStr(value float64, formatter byte, precision int) {
b.lastOp = opInvalid
if formatter == 0 {
@ -69,6 +74,7 @@ func (b *Buffer) WriteFloatStr(value float64, formatter byte, precision int) {
b.data = strconv.AppendFloat(b.data, value, formatter, precision, 64)
}
func (b *Buffer) WriteComplexStr(value complex128, formatter byte, precision int) {
b.lastOp = opInvalid
if formatter == 0 {

@ -25,6 +25,28 @@ package bins
import "activething.com/go/gogo/core/errs"
const (
opRead bufferOp = -1 // Any other read operation.
opInvalid bufferOp = 0 // Non-read operation.
opRune bufferOp = 1 // Decode rune of size 1.
)
const (
minBitSize = 6
minSize = 1 << minBitSize
maxSize = 1 << (minBitSize + poolSteps - 1)
poolSteps = 20
poolThreshold = 42000
poolPercentile = 0.95
)
var (
G = struct {
ErrOutOfRange errs.ErrCode

@ -35,18 +35,23 @@ import (
func Has [T types.UnsignedAll](source T, flag T) bool {
return source&flag != 0 }
func Add [T types.UnsignedAll](source T, flag T) T {
return source|flag }
func AddWithMask [T types.UnsignedAll](source T, flag T, mask T) T {
return (source&mask) | flag }
func Del [T types.UnsignedAll](source T, flag T) T {
return source&^flag }
func Invert [T types.UnsignedAll](source T) T {
return ^source }
func Count[T types.UnsignedAll](source T) int {
switch binary.Size(source) {
case 1 : return bits.OnesCount8 (uint8(source))

@ -35,18 +35,23 @@ type BFlags16 uint16
func (f BFlags16) Has ( flag BFlags16) bool {
return f&flag != 0 }
func (f BFlags16) Add ( flag BFlags16) BFlags16 {
return f|flag }
func (f BFlags16) AddWithMask ( flag BFlags16, mask BFlags16) BFlags16 {
return (f&mask) | flag }
func (f BFlags16) Del ( flag BFlags16) BFlags16 {
return f&^flag }
func (f BFlags16) Invert () BFlags16 {
return ^f }
func (f BFlags16) Count() int {
return bits.OnesCount16(uint16(f)) }

@ -25,18 +25,7 @@
package chars
const (
ASCIIAttControl CharAtt = 1 << iota
ASCIIAttPrintable
ASCIIAttAlpha
ASCIIAttAlphaLower
ASCIIAttAlphaUpper
ASCIIAttDigit
ASCIIAttHex
ASCIIAttDigitHex = ASCIIAttHex | ASCIIAttDigit
)
type (

@ -25,17 +25,18 @@
package chars
const CharAttNone CharAtt = 0
type CharAtt uint8
func (a CharAtt) Is(att CharAtt) bool {
return a&att == att
}
return a&att == att }
func (a CharAtt) Has(att CharAtt) bool {
return a&att != 0
}
return a&att != 0 }
/*
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

@ -25,10 +25,12 @@
package chars
const maxTableSize = 1<<8 - 1
type CharAtts [maxTableSize]CharAtt
func (t *CharAtts) SetRange(att CharAtt, begin, end int) {
if end >= maxTableSize {
end = maxTableSize - 1
@ -38,6 +40,7 @@ func (t *CharAtts) SetRange(att CharAtt, begin, end int) {
}
}
func (t *CharAtts) AddRange(att CharAtt, begin, end int) {
if end >= maxTableSize {
end = maxTableSize - 1
@ -47,6 +50,7 @@ func (t *CharAtts) AddRange(att CharAtt, begin, end int) {
}
}
func (t *CharAtts) DelRange(att CharAtt, begin, end int) {
if end >= maxTableSize {
end = maxTableSize - 1
@ -56,24 +60,28 @@ func (t *CharAtts) DelRange(att CharAtt, begin, end int) {
}
}
func (t *CharAtts) SetSlice(list []byte, att CharAtt, opr int) {
for _, bt := range list {
t[bt] = att
}
}
func (t *CharAtts) AddSlice(list []byte, att CharAtt) {
for _, bt := range list {
t[bt] |= att
}
}
func (t *CharAtts) DelSlice(list []byte, att CharAtt, opr int) {
for _, bt := range list {
t[bt] &^= att
}
}
func (t CharAtts) Has(source []byte, att CharAtt) bool {
for _, ch := range source {
if t[ch]&att == att {
@ -83,6 +91,7 @@ func (t CharAtts) Has(source []byte, att CharAtt) bool {
return false
}
func (t CharAtts) HasAny(source []byte, att CharAtt) bool {
for _, ch := range source {
if t[ch]&att != 0 {
@ -92,6 +101,7 @@ func (t CharAtts) HasAny(source []byte, att CharAtt) bool {
return false
}
func (t CharAtts) IsOf(source []byte, att CharAtt) bool {
if len(source) == 0 {
return false
@ -104,6 +114,7 @@ func (t CharAtts) IsOf(source []byte, att CharAtt) bool {
return true
}
func (t CharAtts) IsOfAny(source []byte, att CharAtt) bool {
if len(source) == 0 {
return false

@ -25,6 +25,30 @@
package chars
const (
ASCIIAttControl CharAtt = 1 << iota
ASCIIAttPrintable
ASCIIAttAlpha
ASCIIAttAlphaLower
ASCIIAttAlphaUpper
ASCIIAttDigit
ASCIIAttHex
ASCIIAttDigitHex = ASCIIAttHex | ASCIIAttDigit
)
const (
CharAttNone CharAtt = 0
maxTableSize = 1<<8 - 1
)
var (
G = struct {

@ -43,6 +43,7 @@ func NewCancel() *Cancel {
}
}
func (c *Cancel) Cancel() {
if atomic.CompareAndSwapUint32(&c.active,1,0) {
close(c.doneCh)

@ -31,6 +31,7 @@ type (
Decrypt (data []byte) results.Bytes
}
DecrypterNop struct {}
)
@ -38,5 +39,5 @@ type (
func (_ DecrypterNop) Decrypt (_ []byte) results.Bytes {
return results.MakeBytesError(G.ErrNotImplemented) }
return results.DoBytesError(G.ErrNotImplemented) }

@ -37,5 +37,6 @@ type (
EncrypterNop struct {}
)
func (_ EncrypterNop) Encrypt (_ []byte) results.Bytes {
return results.MakeBytesError(G.ErrNotImplemented) }
return results.DoBytesError(G.ErrNotImplemented) }

@ -39,7 +39,9 @@ type (
CauserFnc func() error
)
func (f CauserFnc) Cause() error { return f() }
func (f CauserFnc) Cause() error {
return f() }
/*
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

@ -39,6 +39,7 @@ type (
}
)
func NewErrCause(err, cause error) *ErrCause {
if err == nil {
if cause == nil {
@ -49,17 +50,22 @@ func NewErrCause(err, cause error) *ErrCause {
return &ErrCause{error: err, cause: cause}
}
func (e ErrCause) WithInfo(options ...opts.OptionFnc[ErrInfo]) *ErrInfo {
return NewErrInfo(e, options...)
}
return NewErrInfo(e, options...) }
func (e ErrCause) Stack() StackTrace {
return getStackTrace(e.cause)
}
return getStackTrace(e.cause) }
func (e ErrCause) Cause() error {
return e.cause }
func (e ErrCause) Unwrap() error {
return e.cause }
func (e ErrCause) Cause() error { return e.cause }
func (e ErrCause) Unwrap() error { return e.cause }
/*
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

@ -43,19 +43,25 @@ type (
ErrCode string
)
func (e ErrCode) Error() string { return string(e) }
func (e ErrCode) Error() string {
return string(e) }
func (e ErrCode) Stack() StackTrace {
return nil
}
return nil }
func (e ErrCode) WithCause(cause error) *ErrCause {
return NewErrCause(e, cause)
}
return NewErrCause(e, cause) }
func (e ErrCode) WithInfo(options ...opts.OptionFnc[ErrInfo]) *ErrInfo {
return NewErrInfo(e, options...)
}
return NewErrInfo(e, options...) }
/*
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

@ -27,19 +27,24 @@ package errs
import "activething.com/go/gogo/core/opts"
type ErrGroup ErrList
func (_ ErrGroup) Error() string {
return "core:errs.group-error"
}
return "core:errs.group-error" }
func (g ErrGroup) Count() int {
return len(g)
}
return len(g) }
func (g ErrGroup) Errors() []error {
return g
}
return g }
func (g ErrGroup) Cause() error {
switch len(g) {
@ -52,17 +57,19 @@ func (g ErrGroup) Cause() error {
}
}
func (g ErrGroup) Unwrap() error {
return g.Cause()
}
return g.Cause() }
func (g ErrGroup) Stack() StackTrace {
return g.Stack()
}
return g.Stack() }
func (g ErrGroup) WithInfo(options ...opts.OptionFnc[ErrInfo]) *ErrInfo {
return NewErrInfo(g, options...)
}
return NewErrInfo(g, options...) }
/*
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

@ -48,6 +48,7 @@ type (
}
)
func NewErrInfo(err error, options ...opts.OptionFnc[ErrInfo]) *ErrInfo {
if err == nil {
return nil
@ -55,21 +56,22 @@ func NewErrInfo(err error, options ...opts.OptionFnc[ErrInfo]) *ErrInfo {
return opts.Apply(&ErrInfo{error: err}, options...)
}
func (i ErrInfo) Message() string {
return i.message
}
return i.message }
func (i ErrInfo) Source() string {
return i.source
}
return i.source }
func (i ErrInfo) Help() string {
return i.help
}
return i.help }
func (i ErrInfo) Link() string {
return i.link
}
return i.link }
func (i ErrInfo) Stack() StackTrace {
if i.stack != nil {
@ -78,9 +80,10 @@ func (i ErrInfo) Stack() StackTrace {
return getStackTrace(i.Cause())
}
func (i ErrInfo) Details() map[string]any {
return i.Details()
}
return i.Details() }
func (i ErrInfo) Cause() error {
if cs, is := i.error.(Causer); is {
@ -89,13 +92,15 @@ func (i ErrInfo) Cause() error {
return Unwrap(i.error)
}
func (i ErrInfo) Unwrap() error {
return i.Cause()
}
return i.Cause() }
func (i ErrInfo) Date() time.Time {
return i.date
}
return i.date }
/*
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

@ -38,34 +38,42 @@ func ErrInfoWithCause(cause error) opts.OptionFnc[ErrInfo] {
}
}
func ErrInfoWithMessage(message string) opts.OptionFnc[ErrInfo] {
return func(i *ErrInfo) {
i.message = message
}
}
func ErrInfoWithMessagef(format string, args ...any) opts.OptionFnc[ErrInfo] {
return func(i *ErrInfo) {
i.message = fmt.Sprintf(format, args...)
}
}
func ErrInfoWithLink(link string) opts.OptionFnc[ErrInfo] {
return func(i *ErrInfo) {
i.link = link
}
}
func ErrInfoWithHelp(help string) opts.OptionFnc[ErrInfo] {
return func(i *ErrInfo) {
i.help = help
}
}
func ErrInfoWithDate() opts.OptionFnc[ErrInfo] {
return func(i *ErrInfo) { i.date = time.Now() }
return func(i *ErrInfo) {
i.date = time.Now()
}
}
func ErrInfoWithStack(offset ...int) opts.OptionFnc[ErrInfo] {
return func(i *ErrInfo) {
if len(i.stack) > 0 {
@ -79,6 +87,7 @@ func ErrInfoWithStack(offset ...int) opts.OptionFnc[ErrInfo] {
}
}
func ErrInfoWithDetail(name string, value any) opts.OptionFnc[ErrInfo] {
return func(i *ErrInfo) {
if i.details == nil {

@ -27,6 +27,8 @@ package errs
type ErrList []error
func (l ErrList) Clean() ErrList {
for _, e := range l {
if e == nil {
@ -36,6 +38,7 @@ func (l ErrList) Clean() ErrList {
return l
}
func (l ErrList) clean() ErrList {
rs := make([]error, 0, len(l))
for _, e := range l {
@ -46,6 +49,7 @@ func (l ErrList) clean() ErrList {
return rs
}
func (l ErrList) GetFirst() error {
for _, er := range l {
if er != nil {
@ -55,6 +59,7 @@ func (l ErrList) GetFirst() error {
return nil
}
func (l ErrList) GetLast() error {
for i := len(l) - 1; i >= 0; i-- {
if l[i] != nil {
@ -64,13 +69,14 @@ func (l ErrList) GetLast() error {
return nil
}
func (l ErrList) Any() bool {
return l.count(true) > 0
}
return l.count(true) > 0 }
func (l ErrList) Count() int {
return _errorsCount(false, l)
}
return _errorsCount(false, l) }
func (l ErrList) count(ext bool) int {
rs := 0
@ -85,6 +91,7 @@ func (l ErrList) count(ext bool) int {
return rs
}
func (l ErrList) Stack() StackTrace {
for _, er := range l {
if er != nil {
@ -97,6 +104,7 @@ func (l ErrList) Stack() StackTrace {
return nil
}
func (l ErrList) ToError() error {
switch _errorsCount(false, l) {
case 0:
@ -108,6 +116,7 @@ func (l ErrList) ToError() error {
}
}
func _errorsCount(exitOnAny bool, els []error) int {
rs := 0
for _, er := range els {

@ -26,6 +26,7 @@
package errs
type (
ErrorHandler interface {
HandleError(err error)
}
@ -35,6 +36,7 @@ type (
ErrorHandlerFnc func(err error)
)
func (f ErrorHandlerFnc) HandleError(err error) {
f(err)
}

@ -28,14 +28,16 @@ import (
"fmt"
)
type (
//
_W interface{ Unwrap() error }
// Posibles tipos que proveen una posible stack trace
_T interface{ StackTrace() []uintptr }
_C interface{ Callers() []uintptr }
_F interface{ StackFrames() []uintptr }
const (
stackMaxFrames = 32
stackSkipFrames = 2
)
const (
traceUnknown string = "??"
)
var (
@ -52,13 +54,15 @@ var (
}
)
func Is(err, target error) bool {
return errors.Is(err, target)
}
return errors.Is(err, target) }
func As(err error, target any) bool {
return errors.As(err, target)
}
return errors.As(err, target) }
func ToError(err any) error {
if err == nil {
@ -74,6 +78,7 @@ func ToError(err any) error {
}
}
func ToPanic(err any) error {
if err == nil {
return nil
@ -81,6 +86,7 @@ func ToPanic(err any) error {
return G.ErrPanic.WithCause(ToError(err))
}
func Wrap(err, cause error) error {
if err == nil {
return cause
@ -91,6 +97,7 @@ func Wrap(err, cause error) error {
return *NewErrCause(err, cause)
}
func Unwrap(err error) error {
cs, is := err.(_W)
if !is {
@ -99,6 +106,7 @@ func Unwrap(err error) error {
return cs.Unwrap()
}
func getStackTrace(err error) StackTrace {
for err != nil {
switch e := err.(type) {
@ -116,6 +124,7 @@ func getStackTrace(err error) StackTrace {
return nil
}
func Test(err error, halt bool) {
if err != nil {
panic(err)

@ -27,13 +27,12 @@ package errs
import "runtime"
const (
stackMaxFrames = 32
stackSkipFrames = 2
)
type StackTrace []uintptr
func NewStackTrace(offset int) *StackTrace {
var fm [stackMaxFrames]uintptr
if offset < 0 {
@ -44,6 +43,7 @@ func NewStackTrace(offset int) *StackTrace {
return &st
}
func (s StackTrace) Frames() []StackTraceFrame {
ln := len(s)
if ln == 0 {

@ -31,43 +31,49 @@ import (
"strings"
)
const (
unknown string = "??"
)
type StackTraceFrame uintptr
func (f StackTraceFrame) PC() uintptr { return uintptr(f) - 1 }
func (f StackTraceFrame) PC() uintptr {
return uintptr(f) - 1 }
func (f StackTraceFrame) FileName() (fl string) {
fl, _ = f.FileLine()
return
}
func (f StackTraceFrame) FileFull() string {
return path.Base(f.FileName())
}
return path.Base(f.FileName()) }
func (f StackTraceFrame) Line() (ln int) {
_, ln = f.FileLine()
return
}
func (f StackTraceFrame) FileLine() (string, int) {
pc := f.PC()
if fn := runtime.FuncForPC(pc); fn != nil {
return fn.FileLine(pc)
}
return unknown, 0
return traceUnknown, 0
}
func (f StackTraceFrame) FuncName() string {
return f.getFunc(true)
}
return f.getFunc(true) }
func (f StackTraceFrame) FuncFull() string {
return f.getFunc(false)
}
return f.getFunc(false) }
func (f StackTraceFrame) getFunc(cls bool) string {
if fn := runtime.FuncForPC(f.PC()); fn != nil {
@ -80,7 +86,7 @@ func (f StackTraceFrame) getFunc(cls bool) string {
}
return nm
}
return unknown
return traceUnknown
}

@ -26,9 +26,12 @@
package errs
type (
StackTracer interface {
Stack() StackTrace
}
)
/*

@ -2,9 +2,9 @@
// Project atila
// Active Thing (activething.com) git.activething.com/go
//
// File name gogo.go
// File name types.go
// Created by DEV
// Modified 17/02/2024
// Modified 19/02/2024
//
// Copyright 2024 activething.com
// ------------------------------------------------------------------------
@ -21,33 +21,16 @@
// limitations under the License.
// ------------------------------------------------------------------------
package matches
package errs
import (
"activething.com/go/gogo/core/errs"
)
const (
type (
//
_W interface{ Unwrap() error }
namedMatcher byte = '='
notMatcher byte = '!'
// Posibles tipos que proveen una posible stack trace
_T interface{ StackTrace() []uintptr }
_C interface{ Callers() []uintptr }
_F interface{ StackFrames() []uintptr }
)
var (
G = struct {
ErrInvalidMatcher errs.ErrCode
ErrMatcherNotFound errs.ErrCode
} {
ErrInvalidMatcher : errs.ErrCode("sapis.matches:invalid-matcher"),
ErrMatcherNotFound: errs.ErrCode("sapis.matches:invalid-matcher"),
}
)

@ -31,35 +31,48 @@ type (
Bytes interface {
IsError () bool
Success () []byte
Error () error
Cause () error
}
BytesSuccess []byte
BytesError struct {
error
}
BytesError struct { error }
)
func (_ BytesSuccess) IsError () bool { return false }
func (_ BytesSuccess) IsError () bool {
return false }
func (_ BytesSuccess) Cause () error {
return nil }
func (r BytesSuccess) Success () []byte {
return r }
func DoBytesError (err error) BytesError {
return BytesError { error: err } }
func (_ BytesSuccess) Error () error { return nil }
func (r BytesSuccess) Success () []byte { return r }
func (_ BytesError) IsError () bool {
return true }
func (r BytesError) Cause() error {
return r.error }
func MakeBytesError (cause error) BytesError {
return BytesError{ cause } }
func (_ BytesError) IsError () bool { return true }
func (_ BytesError) Success () []byte {
return nil }
func (_ BytesError) Success () []byte { return nil }
func (r BytesError) Error () error { return r.error }

@ -35,9 +35,7 @@ type (
IntSuccess int
IntError struct {
error
}
IntError struct { error }
)
@ -50,10 +48,10 @@ func (r IntSuccess) Success () int { return int(r) }
func (_ IntError) Success () int { return 0 }
func (_ IntError) IsError () bool { return true }
func (_ IntError) Success () int { return 0 }
func (e IntError) Error () error { return e.error }
func (r IntError) Error () error { return r.error }

@ -39,10 +39,7 @@ type (
data T
}
ResultError[T any] struct {
error
}
ResultError[T any] struct { error }
)
@ -59,16 +56,20 @@ func (_ ResultSuccess[T]) Error() error {
func (_ ResultError[T]) IsError () bool {
return false }
func (r ResultError[T]) Success() T {
var zero T
return zero }
return zero
}
func (r ResultError[T]) Error() error {
return r.error }
func (r ResultError[T]) IsError () bool {
return true }
func (r ResultError[T]) Error () error {
return r.error }

@ -35,9 +35,7 @@ type (
StringSuccess string
StringError struct {
error
}
StringError struct { error }
)
@ -50,10 +48,12 @@ func (r StringSuccess) Success () string { return string(r) }
func DoStringError (err error) StringError {
return StringError { error: err } }
func (_ StringError) IsError () bool { return true }
func (_ StringError) Success () string { return "" }
func (_ StringError) IsError () bool { return true }
func (r StringError) Error () error { return r.error }
func (e StringError) Error () error { return e.error }
func (_ StringError) Success () string { return "" }

@ -47,15 +47,15 @@ type (
)
func NewExpiration(tmo time.Duration, fnc func()) *Expiration {
func NewExpiration(duration time.Duration, expirer func()) *Expiration {
ex := &Expiration{
times: *NewChrono(false),
state: uint32(TimerStateCreated),
source: uint32(ExpirationSourceSelf),
timeout: int64(tmo),
expireFn: fnc,
timeout: int64(duration),
expireFn: expirer,
}
if tmo > 0 {
if duration > 0 {
atomic.StoreUint32(&ex.source,uint32(ExpirationSourceTimer))
}
return ex
@ -104,7 +104,7 @@ func (e *Expiration) Deadline() time.Time {
func (e *Expiration) Start(exp Expirer) error {
func (e *Expiration) Start(expirer Expirer) error {
if !atomic.CompareAndSwapUint32(&e.state,uint32(TimerStateCreated),uint32(TimerStateStarted)) {
return G.ErrAlreadyStarted
}
@ -113,8 +113,8 @@ func (e *Expiration) Start(exp Expirer) error {
to := time.Duration(atomic.LoadInt64(&e.timeout))
dl := st.Add(to)
if exp != nil {
pd, ph := exp.Deadline()
if expirer != nil {
pd, ph := expirer.Deadline()
if ph {
if pd.Before(st) {
atomic.StoreUint32(&e.state ,uint32(TimerStateExpired))

@ -47,7 +47,7 @@ type (
}
PulsarWorkFnc func() error
PulsarWorkFnc func(ctx context.Context) error
)
@ -109,7 +109,7 @@ func (p *Pulsar) Start(ctx context.Context) error {
case <-tk.C:
if TimerState(atomic.LoadUint32(&pl.state)) == TimerStateStarted {
if er := pl.workFn(); er != nil {
if er := pl.workFn(cx); er != nil {
pl.err.Store(er)
atomic.StoreUint32(&pl.state,uint32(TimerStateCanceled))
break EXIT

@ -24,13 +24,14 @@
package times
import (
"context"
"time"
)
type (
TimeTaskFnc func(now time.Time)
TimeTaskFnc func(now time.Time, ctx context.Context)
)
/*

@ -112,7 +112,7 @@ func (q *TimerQueue) Start(ctx context.Context) error {
if len(ts) > 0 {
go func(tm time.Time, tk []*TimerTask) {
for _, tt := range tk {
tt.TaskFn(tm)
tt.TaskFn(tm, ctx)
}
}(nw, ts)
}
@ -158,17 +158,17 @@ func (q *TimerQueue) Stop() error {
}
func (q *TimerQueue) Push(rat time.Time, fnc TimeTaskFnc) error {
func (q *TimerQueue) Push(runAt time.Time, task TimeTaskFnc) error {
switch {
case rat.Before(time.Now()):
case runAt.Before(time.Now()):
return G.ErrExpired
case fnc == nil:
case task == nil:
return G.ErrTimerTaskInvalid
case TimerState(atomic.LoadUint32(&q.state)) != TimerStateStarted:
return G.ErrNotStarted
default:
select {
case q.pushCh <- NewTimerTask(rat, fnc):
case q.pushCh <- NewTimerTask(runAt, task):
return nil
case <-q.ctx.Done():
return context.Canceled

@ -39,9 +39,9 @@ type (
)
func NewTimerTask(time time.Time, task TimeTaskFnc) *TimerTask {
func NewTimerTask(runAt time.Time, task TimeTaskFnc) *TimerTask {
return &TimerTask{
RunAt: time,
RunAt: runAt,
TaskFn: task,
}
}

@ -51,6 +51,14 @@ func (h *TimerTaskHeap) PopTimerTask() *TimerTask {
}
func (h *TimerTaskHeap) Push(ele interface{}) {
h.PushTimerTask(ele.(*TimerTask)) }
func (h *TimerTaskHeap) Pop() interface{} {
return h.PopTimerTask() }
func (h TimerTaskHeap) Len() int {
return len(h) }
@ -63,12 +71,7 @@ func (h TimerTaskHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i] }
func (h *TimerTaskHeap) Push(ele interface{}) {
h.PushTimerTask(ele.(*TimerTask)) }
func (h *TimerTaskHeap) Pop() interface{} {
return h.PopTimerTask() }

@ -40,6 +40,5 @@ type (
func (f BuildFnc) Build (packer Packer) error {
return f(packer)
}
return f(packer) }

@ -56,24 +56,40 @@ const (
type Flags bits.BFlags16
func (f Flags) Omit () bool { return f&FlagOmit != 0 }
func (f Flags) Omit () bool {
return f&FlagOmit != 0 }
func (f Flags) OmitEmpty () bool { return f&FlagOmitEmpty != 0 }
func (f Flags) Quote () bool { return f&FlagQuote != 0 }
func (f Flags) OmitEmpty () bool {
return f&FlagOmitEmpty != 0 }
func (f Flags) EscapeHTML () bool { return f&FlagScapeHTML != 0 }
func (f Flags) String () bool { return f&FlagString != 0 }
func (f Flags) Quote () bool {
return f&FlagQuote != 0 }
func (f Flags) Encrypted() bool { return f&FlagEncrypted != 0 }
func (f Flags) EscapeHTML () bool {
return f&FlagScapeHTML != 0 }
func (f Flags) Binary () bool { return f&(FlagBinary64|FlagBinary32) != 0 }
func (f Flags) Bin64 () bool { return f&FlagBinary64 != 0 }
func (f Flags) String () bool {
return f&FlagString != 0 }
func (f Flags) Bin32 () bool { return f&FlagBinary32 != 0 }
func (f Flags) Encrypted() bool {
return f&FlagEncrypted != 0 }
func (f Flags) Binary () bool {
return f&(FlagBinary64|FlagBinary32) != 0 }
func (f Flags) Bin64 () bool {
return f&FlagBinary64 != 0 }
func (f Flags) Bin32 () bool {
return f&FlagBinary32 != 0 }

@ -29,11 +29,7 @@ import (
"unicode/utf8"
)
const (
caseMask = ^byte(0x20) // Mask to ignore case in ASCII.
kelvin = '\u212a'
smallLongEss = '\u017f'
)
// GetFoldFunc returns one of four different case folding equivalence
// functions, from most general (and slow) to fastest:
@ -80,6 +76,7 @@ func GetFoldFunc(s []byte) FoldFnc {
return chars.G.ASCII.SimpleLetterEqualFold
}
// equalFoldRight is a specialization of bytes.EqualFold when s is
// known to be all ASCII (including punctuation), but contains an 's',
// 'S', 'k', or 'K', requiring a Unicode fold on the bytes in t.

@ -33,6 +33,13 @@ const(
TagKey = "pack"
)
const (
caseMask = ^byte(0x20) // Mask to ignore case in ASCII.
kelvin = '\u212a'
smallLongEss = '\u017f'
)
var (
G = struct {

@ -47,7 +47,8 @@ type (
Encrypter crypts.Encrypter
}
StateOptionFnc func (*State)
)
@ -132,6 +133,7 @@ func (s *State) Close(closer byte) {
s.counts = s.counts[:len(s.counts)-1]
}
func (s *State) Count() int {
if s.Error != nil {
return 0
@ -139,6 +141,7 @@ func (s *State) Count() int {
return s.counts[s.Level]
}
func (s *State) Inc () {
if s.Error == nil {
s.counts[s.Level] += 1

@ -24,6 +24,8 @@
package pjson
import (
"activething.com/go/gogo/core/opts"
"activething.com/go/gogo/core/results"
"activething.com/go/gogo/packs"
"encoding"
"encoding/json"
@ -33,8 +35,16 @@ import (
)
const maxCyclesAfter = 100
const jsonTag = "json"
const (
jsonTag = "json"
maxCyclesAfter = 100
defaultFlags = packs.Flags(0)
)
var (
G = struct {
@ -99,6 +109,19 @@ func initJSONChars() [utf8.RuneSelf]jsonCharAtt {
func Pack (value any, options ... opts.OptionFnc[Packer]) (res results.Bytes) {
p := NewPacker(options ...)
p.Pack(value,defaultFlags)
if p.Error() != nil {
res = results.DoBytesError(p.Error())
} else {
res = results.BytesSuccess(p.Packet())
}
p.Release()
return res
}

@ -30,7 +30,6 @@ import (
"encoding/base32"
"encoding/base64"
"encoding/json"
"fmt"
"math"
"reflect"
"strconv"
@ -69,13 +68,16 @@ func (p *Packer) Pack (value any, flags packs.Flags) {
p.PackAny(value,flags)
}
func (p *Packer) Packet () []byte {
return p.state.Bytes()
}
return p.state.Bytes() }
func (p *Packer) Error () error {
return p.state.Error
}
return p.state.Error }
func (p *Packer) Reset () {
@ -83,7 +85,10 @@ func (p *Packer) Reset () {
p.dirty = false
}
func (p *Packer) Release () {
p.dirty = false
packs.ReleaseState(p.state)
}
@ -253,13 +258,7 @@ func packString (state *packs.State, value string , flags packs.Flags) {
}
if flags.Encrypted() {
r := state.Encrypter.Encrypt([]byte(value))
if r.IsError() {
state.SetError(r.Error())
return
}
packBinary(state,r.Success(),flags|packs.FlagBinary64)
fmt.Printf("Errir %v\n",state.Error)
packBinary(state, []byte(value), flags|packs.FlagBinary64)
return
}
@ -344,10 +343,14 @@ func packBinary (state *packs.State, value []byte , flags packs.Flags) {
if flags.Encrypted() {
r := state.Encrypter.Encrypt(value)
if r.IsError() {
state.SetError(r.Error())
state.SetError(r.Cause())
return
}
packBinary(state,r.Success(),flags|packs.FlagBinary64)
state.WriteByte('"')
packBinary64(state, r.Success(), flags)
if state.Error == nil {
state.WriteByte('"')
}
return
}
@ -470,16 +473,16 @@ func packFloatString (state *packs.State, f float64, flags packs.Flags, bits int
}
abs := math.Abs(f)
fmt := byte('f')
fm := byte('f')
if abs != 0 {
if bits == 64 && (abs < 1e-6 || abs >= 1e21) || bits == 32 && (float32(abs) < 1e-6 || float32(abs) >= 1e21) {
fmt = 'e'
fm = 'e'
}
}
bf := state.Temp[:0]
bf = strconv.AppendFloat(bf, f, fmt, -1, int(bits))
if fmt == 'e' {
bf = strconv.AppendFloat(bf, f, fm, -1, int(bits))
if fm == 'e' {
// clean up e-09 to e-9
n := len(bf)
if n >= 4 && bf[n-4] == 'e' && bf[n-3] == '-' && bf[n-2] == '0' {
@ -521,6 +524,7 @@ func packListString (state *packs.State, list []string, flags packs.Flags) {
state.WriteByte(']')
}
func packListBool (state *packs.State, list []bool, flags packs.Flags) {
if !checkList(state,list == nil, len(list) ==0) {
return
@ -538,6 +542,7 @@ func packListBool (state *packs.State, list []bool, flags packs.Flags) {
state.WriteByte(']')
}
func packListInt [T int | int8 | int16 | int32 | int64](state *packs.State, list []T, flags packs.Flags) {
if !checkList(state,list == nil, len(list) ==0) {
return
@ -555,6 +560,7 @@ func packListInt [T int | int8 | int16 | int32 | int64](state *packs.State, lis
state.WriteByte(']')
}
func packListUInt [T uint | uint8 | uint16 | uint32 | uint64](state *packs.State, list []T, flags packs.Flags) {
if !checkList(state,list == nil, len(list) ==0) {
return
@ -572,6 +578,7 @@ func packListUInt [T uint | uint8 | uint16 | uint32 | uint64](state *packs.State
state.WriteByte(']')
}
func packListFloat[T float32 | float64](state *packs.State, list []T, flags packs.Flags, bits int) {
if !checkList(state,list == nil, len(list) ==0) {
return

@ -98,8 +98,11 @@ func _rTypePacker(rtype reflect.Type) rPackerFnc {
case reflect.Struct:
return rObjectPacker(rtype)
default:
return unsupportedTypePacker
}
return unsupportedTypePacker
}

@ -46,7 +46,10 @@ func rObjectPacker (rtype reflect.Type) rPackerFnc {
if !ok {
op,_ = G.fieldsCache.LoadOrStore(rtype,*newRObject(rtype))
}
return (op.(rObject)).pack
return func(s *packs.State, value reflect.Value, flags packs.Flags) {
op.(rObject).pack(s,value,flags)
}
//return (op.(rObject)).pack
}
@ -133,7 +136,7 @@ func newRObject(rtype reflect.Type) *rObject {
// Build nameEscHTML and nameNonEsc ahead of time.
nms.Reset()
nms.WriteByte('"')
nms.WriteHTMLScape(of.nameB)
nms.WriteHTML(of.nameB)
nms.Write2Byte('"',':')
of.nameS = nms.String()
of.nameU = `"` + of.name + `":`
@ -271,6 +274,7 @@ func isEmptyValue(v reflect.Value) bool {
return v.Float() == 0
case reflect.Interface, reflect.Pointer:
return v.IsNil()
default:
return false
}
return false
}

@ -26,6 +26,13 @@ package tokens
import "activething.com/go/gogo/core/errs"
const (
namedMatcher byte = '='
notMatcher byte = '!'
)
const (
@ -52,8 +59,12 @@ const (
var (
G = struct {
ErrMatcherNotFound errs.ErrCode
ErrInvalidTopic errs.ErrCode
ErrInvalidTopicLen errs.ErrCode
ErrInvalidToken errs.ErrCode
@ -68,6 +79,8 @@ var (
ErrInvalidTokenLen : errs.ErrCode ("sapis:tokens.invalid-token-len"),
ErrInvalidMatcher : errs.ErrCode ("sapis:tokens.invalid-matcher"),
ErrMatcherNotFound: errs.ErrCode("sapis.matches:invalid-matcher"),
}
)

@ -50,6 +50,7 @@ func (_ InvalidToken) Kind() TokenKind {
func (_ InvalidToken) Match(_ []byte) bool {
return false }
func (t InvalidToken) Source() []byte {
return t.source }

@ -21,7 +21,7 @@
// limitations under the License.
// ------------------------------------------------------------------------
package matches
package tokens
import "bytes"

@ -21,7 +21,7 @@
// limitations under the License.
// ------------------------------------------------------------------------
package matches
package tokens
import (
"activething.com/go/gogo/core/opts"
@ -31,24 +31,30 @@ import (
type (
Builder struct {
MatcherBuilder struct {
sync.RWMutex
matchers map[string]Matcher
}
BuilderFnc func (repo *Builder)
)
func NewBuilder(options ...opts.OptionFnc[Builder]) *Builder {
return opts.Apply(&Builder{ matchers: make(map[string]Matcher)}, options...)
func NewMatcherBuilder(options ...opts.OptionFnc[MatcherBuilder]) *MatcherBuilder {
return opts.Apply(&MatcherBuilder{
matchers: make(map[string]Matcher),
}, options...)
}
func (r *MatcherBuilder) Has(name string) bool {
r.RLock()
_,h := r.matchers[name]
r.Unlock()
return h
}
func (r *Builder) GetMatcher (name string) (m Matcher) {
func (r *MatcherBuilder) Get(name string) (m Matcher) {
r.RLock()
m, _ = r.matchers[name]
r.RUnlock()
@ -56,7 +62,7 @@ func (r *Builder) GetMatcher (name string) (m Matcher) {
}
func (r *Builder) SetMatcher (name string, matcher Matcher) {
func (r *MatcherBuilder) Set(name string, matcher Matcher) {
r.Lock()
if matcher == nil {
delete(r.matchers,name)
@ -71,32 +77,32 @@ func (r *Builder) SetMatcher (name string, matcher Matcher) {
func (r *Builder) BuildMatcher (data []byte) (Matcher,error) {
func (r *MatcherBuilder) Build (data []byte) (Matcher,error) {
data = data[1:len(data)-1]
if len(data) == 0 {
return nil,G.ErrInvalidMatcher
return nil, G.ErrInvalidMatcher
}
// Si es un matcher con nombre, lo buscamos
if data[0] == namedMatcher {
nm := string(data[1:])
if len(nm) == 0 {
return nil,G.ErrInvalidMatcher
return nil, G.ErrInvalidMatcher
}
r.RLock()
mc := r.matchers[nm]
r.Unlock()
if mc == nil {
return nil,G.ErrMatcherNotFound
return nil, G.ErrMatcherNotFound
}
return mc,nil
}
if data[1] == notMatcher {
if data[1] ==notMatcher {
d := data[1:]
if len(d) == 0 {
return nil,G.ErrInvalidMatcher
return nil, G.ErrInvalidMatcher
}
return MatchFnc(NotMatchFn(d)),nil
}
@ -113,5 +119,5 @@ func (r *Builder) BuildMatcher (data []byte) (Matcher,error) {
}
r.Unlock()
return nil,G.ErrInvalidMatcher.WithCause(er)
return nil, G.ErrInvalidMatcher.WithCause(er)
}

@ -23,20 +23,18 @@
package tokens
import "activething.com/go/gogo/sapis/matches"
type (
MatcherToken struct {
source []byte
MatchFn matches.MatchFnc
MatchFn MatchFnc
}
)
func NewMatcherToken(mfn matches.MatchFnc, src []byte) *MatcherToken {
func NewMatcherToken(mfn MatchFnc, src []byte) *MatcherToken {
return &MatcherToken{
MatchFn: mfn,
source: src,

@ -23,14 +23,12 @@
package tokens
import "activething.com/go/gogo/sapis/matches"
type (
Token interface {
matches.Matcher
Matcher
Kind () TokenKind

@ -25,14 +25,13 @@ package tokens
import (
"activething.com/go/gogo/core/opts"
"activething.com/go/gogo/sapis/matches"
)
type (
Tokenizer struct {
TokenizerOptions
matcher matches.Builder
matcher MatcherBuilder
}
)
@ -41,7 +40,7 @@ type (
func NewTokenizer(options ...opts.OptionFnc[TokenizerOptions]) *Tokenizer {
return &Tokenizer{
TokenizerOptions: *NewBuilderOptions(options...),
matcher : *matches.NewBuilder(),
matcher : *NewMatcherBuilder(),
}
}
@ -114,7 +113,7 @@ func (b *Tokenizer) MakeToken(source []byte) Token {
}
if source[ln-1] != b.MatchEnd || ln > b.TokenMinLen+2 {
m,e := b.matcher.BuildMatcher(source)
m,e := b.matcher.Build(source)
if e != nil {
return *NewInvalidToken(G.ErrInvalidMatcher.WithCause(e),source)
}

@ -29,11 +29,8 @@ type (
Topic struct {
kind TokenKind
source []byte
tokens []Token
}
)
@ -45,6 +42,7 @@ func NewTopic(builder *Tokenizer, topic []byte, allows TokenKind) *Topic {
return tp
}
func (t Topic) Len() int {
return len(t.tokens) }

@ -29,6 +29,7 @@ type (
WildcardToken struct{}
)

Loading…
Cancel
Save

Powered by TurnKey Linux.