diff --git a/app/main.go b/app/main.go index fa0d85e..d741473 100644 --- a/app/main.go +++ b/app/main.go @@ -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()) + } diff --git a/app/tests/benchmarks_test.go b/app/tests/benchmarks_test.go index 3ae69d6..33fab72 100644 --- a/app/tests/benchmarks_test.go +++ b/app/tests/benchmarks_test.go @@ -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() } diff --git a/core/bins/appender.go b/core/bins/appender.go index 7b70a56..e2ab311 100644 --- a/core/bins/appender.go +++ b/core/bins/appender.go @@ -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) } diff --git a/core/bins/bfields/bfield.go b/core/bins/bfields/bfield.go new file mode 100644 index 0000000..84338e5 --- /dev/null +++ b/core/bins/bfields/bfield.go @@ -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) +} + + + + + diff --git a/core/bins/bfields/gogo.go b/core/bins/bfields/gogo.go new file mode 100644 index 0000000..413f38f --- /dev/null +++ b/core/bins/bfields/gogo.go @@ -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"), + } +) + + + + + + diff --git a/core/bins/buffer.go b/core/bins/buffer.go index b5fb243..7c0ae3c 100644 --- a/core/bins/buffer.go +++ b/core/bins/buffer.go @@ -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) { diff --git a/core/bins/buffer_op.go b/core/bins/buffer_op.go index 7ad3df4..fcd49f6 100644 --- a/core/bins/buffer_op.go +++ b/core/bins/buffer_op.go @@ -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 diff --git a/core/bins/buffer_pool.go b/core/bins/buffer_pool.go index b788c70..b82f6f0 100644 --- a/core/bins/buffer_pool.go +++ b/core/bins/buffer_pool.go @@ -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 diff --git a/core/bins/buffer_pool_ops.go b/core/bins/buffer_pool_ops.go index aa89bb0..d68b0a0 100644 --- a/core/bins/buffer_pool_ops.go +++ b/core/bins/buffer_pool_ops.go @@ -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) diff --git a/core/bins/buffer_writer_binary.go b/core/bins/buffer_writer_binary.go index 0afe420..2571f5e 100644 --- a/core/bins/buffer_writer_binary.go +++ b/core/bins/buffer_writer_binary.go @@ -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) } diff --git a/core/bins/buffer_writer_string.go b/core/bins/buffer_writer_string.go index e8f9bf2..0a55246 100644 --- a/core/bins/buffer_writer_string.go +++ b/core/bins/buffer_writer_string.go @@ -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 { diff --git a/core/bins/gogo.go b/core/bins/gogo.go index a25eaf4..50d6476 100644 --- a/core/bins/gogo.go +++ b/core/bins/gogo.go @@ -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 diff --git a/core/bits/bflags.go b/core/bits/bflags.go index cd3c23a..17695e1 100644 --- a/core/bits/bflags.go +++ b/core/bits/bflags.go @@ -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)) diff --git a/core/bits/bflags_16.go b/core/bits/bflags_16.go index 9039cfa..d1c756b 100644 --- a/core/bits/bflags_16.go +++ b/core/bits/bflags_16.go @@ -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)) } diff --git a/core/chars/ascii_char_atts.go b/core/chars/ascii_char_atts.go index fdd6985..9c22332 100644 --- a/core/chars/ascii_char_atts.go +++ b/core/chars/ascii_char_atts.go @@ -25,18 +25,7 @@ package chars -const ( - ASCIIAttControl CharAtt = 1 << iota - ASCIIAttPrintable - ASCIIAttAlpha - ASCIIAttAlphaLower - ASCIIAttAlphaUpper - ASCIIAttDigit - ASCIIAttHex - - ASCIIAttDigitHex = ASCIIAttHex | ASCIIAttDigit -) type ( diff --git a/core/chars/char_att.go b/core/chars/char_att.go index bf11e06..962e6df 100644 --- a/core/chars/char_att.go +++ b/core/chars/char_att.go @@ -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 } /* :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/core/chars/char_atts.go b/core/chars/char_atts.go index 3a79540..5ba488c 100644 --- a/core/chars/char_atts.go +++ b/core/chars/char_atts.go @@ -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 diff --git a/core/chars/gogo.go b/core/chars/gogo.go index 1c69e2e..0c286fe 100644 --- a/core/chars/gogo.go +++ b/core/chars/gogo.go @@ -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 { diff --git a/core/contexts/cancel.go b/core/contexts/cancel.go index e9c7b7d..89b7551 100644 --- a/core/contexts/cancel.go +++ b/core/contexts/cancel.go @@ -43,6 +43,7 @@ func NewCancel() *Cancel { } } + func (c *Cancel) Cancel() { if atomic.CompareAndSwapUint32(&c.active,1,0) { close(c.doneCh) diff --git a/core/crypts/decrypter.go b/core/crypts/decrypter.go index 2d6f764..fe72d95 100644 --- a/core/crypts/decrypter.go +++ b/core/crypts/decrypter.go @@ -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) } diff --git a/core/crypts/encrypter.go b/core/crypts/encrypter.go index f95cc94..dc60753 100644 --- a/core/crypts/encrypter.go +++ b/core/crypts/encrypter.go @@ -37,5 +37,6 @@ type ( EncrypterNop struct {} ) + func (_ EncrypterNop) Encrypt (_ []byte) results.Bytes { - return results.MakeBytesError(G.ErrNotImplemented) } \ No newline at end of file + return results.DoBytesError(G.ErrNotImplemented) } \ No newline at end of file diff --git a/core/errs/causer.go b/core/errs/causer.go index 9347b87..090259a 100644 --- a/core/errs/causer.go +++ b/core/errs/causer.go @@ -39,7 +39,9 @@ type ( CauserFnc func() error ) -func (f CauserFnc) Cause() error { return f() } +func (f CauserFnc) Cause() error { + return f() } + /* :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/core/errs/err_cause.go b/core/errs/err_cause.go index 53afb58..45c49a5 100644 --- a/core/errs/err_cause.go +++ b/core/errs/err_cause.go @@ -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 } /* :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/core/errs/err_code.go b/core/errs/err_code.go index a84c87e..f3c658f 100644 --- a/core/errs/err_code.go +++ b/core/errs/err_code.go @@ -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...) } + + + /* :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/core/errs/err_group.go b/core/errs/err_group.go index 5789dc3..352c189 100644 --- a/core/errs/err_group.go +++ b/core/errs/err_group.go @@ -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...) } + + /* :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/core/errs/err_info.go b/core/errs/err_info.go index 7f3136a..b6a7a43 100644 --- a/core/errs/err_info.go +++ b/core/errs/err_info.go @@ -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 } + + /* :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/core/errs/err_info_ops.go b/core/errs/err_info_ops.go index ab62722..285e23d 100644 --- a/core/errs/err_info_ops.go +++ b/core/errs/err_info_ops.go @@ -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 { diff --git a/core/errs/err_list.go b/core/errs/err_list.go index d1e07c8..b86815a 100644 --- a/core/errs/err_list.go +++ b/core/errs/err_list.go @@ -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 { diff --git a/core/errs/error_handler.go b/core/errs/error_handler.go index cbc3271..ebfa409 100644 --- a/core/errs/error_handler.go +++ b/core/errs/error_handler.go @@ -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) } diff --git a/core/errs/gogo.go b/core/errs/gogo.go index 4473bea..399382d 100644 --- a/core/errs/gogo.go +++ b/core/errs/gogo.go @@ -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) diff --git a/core/errs/stack_trace.go b/core/errs/stack_trace.go index 407c2fb..92b40ab 100644 --- a/core/errs/stack_trace.go +++ b/core/errs/stack_trace.go @@ -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 { diff --git a/core/errs/stack_trace_frame.go b/core/errs/stack_trace_frame.go index 0e09dba..9bf26f7 100644 --- a/core/errs/stack_trace_frame.go +++ b/core/errs/stack_trace_frame.go @@ -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 } diff --git a/core/errs/stack_tracer.go b/core/errs/stack_tracer.go index c7f8ad5..ba5a770 100644 --- a/core/errs/stack_tracer.go +++ b/core/errs/stack_tracer.go @@ -26,9 +26,12 @@ package errs type ( + + StackTracer interface { Stack() StackTrace } + ) /* diff --git a/sapis/matches/gogo.go b/core/errs/types.go similarity index 68% rename from sapis/matches/gogo.go rename to core/errs/types.go index 58d5b93..1b62b73 100644 --- a/sapis/matches/gogo.go +++ b/core/errs/types.go @@ -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"), - } -) - - - - diff --git a/core/results/bytes.go b/core/results/bytes.go index 9aeabbf..fe78757 100644 --- a/core/results/bytes.go +++ b/core/results/bytes.go @@ -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 } diff --git a/core/results/int.go b/core/results/int.go index 600100e..6d2c8b5 100644 --- a/core/results/int.go +++ b/core/results/int.go @@ -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 } diff --git a/core/results/result.go b/core/results/result.go index ce48c9b..17dc0ee 100644 --- a/core/results/result.go +++ b/core/results/result.go @@ -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 } diff --git a/core/results/string.go b/core/results/string.go index f00d833..9371008 100644 --- a/core/results/string.go +++ b/core/results/string.go @@ -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 "" } diff --git a/core/times/expiration.go b/core/times/expiration.go index e8ab8f8..a02128a 100644 --- a/core/times/expiration.go +++ b/core/times/expiration.go @@ -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)) diff --git a/core/times/pulsar.go b/core/times/pulsar.go index d7c3022..5372e3b 100644 --- a/core/times/pulsar.go +++ b/core/times/pulsar.go @@ -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 diff --git a/core/times/time_task.go b/core/times/time_task.go index e0b2e63..5f62074 100644 --- a/core/times/time_task.go +++ b/core/times/time_task.go @@ -24,13 +24,14 @@ package times import ( + "context" "time" ) type ( - TimeTaskFnc func(now time.Time) + TimeTaskFnc func(now time.Time, ctx context.Context) ) /* diff --git a/core/times/timer_queue.go b/core/times/timer_queue.go index 4778c28..2bd212b 100644 --- a/core/times/timer_queue.go +++ b/core/times/timer_queue.go @@ -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 diff --git a/core/times/timer_task.go b/core/times/timer_task.go index af9998d..89930e9 100644 --- a/core/times/timer_task.go +++ b/core/times/timer_task.go @@ -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, } } diff --git a/core/times/timer_task_heap.go b/core/times/timer_task_heap.go index f59adab..5c9ee0a 100644 --- a/core/times/timer_task_heap.go +++ b/core/times/timer_task_heap.go @@ -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() } diff --git a/packs/builder.go b/packs/builder.go index 008d966..c5e899b 100644 --- a/packs/builder.go +++ b/packs/builder.go @@ -40,6 +40,5 @@ type ( func (f BuildFnc) Build (packer Packer) error { - return f(packer) -} + return f(packer) } diff --git a/packs/flags.go b/packs/flags.go index 268d2ca..0ac5f42 100644 --- a/packs/flags.go +++ b/packs/flags.go @@ -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 } diff --git a/packs/fold.go b/packs/fold.go index 0caed53..4fa2e40 100644 --- a/packs/fold.go +++ b/packs/fold.go @@ -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. diff --git a/packs/gogo.go b/packs/gogo.go index 58cf91d..9e56719 100644 --- a/packs/gogo.go +++ b/packs/gogo.go @@ -33,6 +33,13 @@ const( TagKey = "pack" ) +const ( + caseMask = ^byte(0x20) // Mask to ignore case in ASCII. + kelvin = '\u212a' + smallLongEss = '\u017f' +) + + var ( G = struct { diff --git a/packs/packer_state.go b/packs/packer_state.go index e78c997..0a9c74a 100644 --- a/packs/packer_state.go +++ b/packs/packer_state.go @@ -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 diff --git a/packs/pjson/gogo.go b/packs/pjson/gogo.go index 7213855..08e9bde 100644 --- a/packs/pjson/gogo.go +++ b/packs/pjson/gogo.go @@ -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 +} + + diff --git a/packs/pjson/packer.go b/packs/pjson/packer.go index 299ec6b..0c7a5dc 100644 --- a/packs/pjson/packer.go +++ b/packs/pjson/packer.go @@ -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 diff --git a/packs/pjson/rpacker.go b/packs/pjson/rpacker.go index 583b91e..4d90d86 100644 --- a/packs/pjson/rpacker.go +++ b/packs/pjson/rpacker.go @@ -98,8 +98,11 @@ func _rTypePacker(rtype reflect.Type) rPackerFnc { case reflect.Struct: return rObjectPacker(rtype) + + default: + return unsupportedTypePacker } - return unsupportedTypePacker + } diff --git a/packs/pjson/rpacker_object.go b/packs/pjson/rpacker_object.go index 596c784..b8a45e0 100644 --- a/packs/pjson/rpacker_object.go +++ b/packs/pjson/rpacker_object.go @@ -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 } \ No newline at end of file diff --git a/sapis/tokens/gogo.go b/sapis/tokens/gogo.go index 9de04c8..8bd7265 100644 --- a/sapis/tokens/gogo.go +++ b/sapis/tokens/gogo.go @@ -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"), + } ) diff --git a/sapis/tokens/invalid_token.go b/sapis/tokens/invalid_token.go index a16effc..2cf581a 100644 --- a/sapis/tokens/invalid_token.go +++ b/sapis/tokens/invalid_token.go @@ -50,6 +50,7 @@ func (_ InvalidToken) Kind() TokenKind { func (_ InvalidToken) Match(_ []byte) bool { return false } + func (t InvalidToken) Source() []byte { return t.source } diff --git a/sapis/matches/matcher.go b/sapis/tokens/matcher.go similarity index 98% rename from sapis/matches/matcher.go rename to sapis/tokens/matcher.go index 28654b0..236b582 100644 --- a/sapis/matches/matcher.go +++ b/sapis/tokens/matcher.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package matches +package tokens import "bytes" diff --git a/sapis/matches/builder.go b/sapis/tokens/matcher_builder.go similarity index 71% rename from sapis/matches/builder.go rename to sapis/tokens/matcher_builder.go index 490e0d9..9eed8f8 100644 --- a/sapis/matches/builder.go +++ b/sapis/tokens/matcher_builder.go @@ -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) } \ No newline at end of file diff --git a/sapis/tokens/matcher_token.go b/sapis/tokens/matcher_token.go index 4e9ad38..7123642 100644 --- a/sapis/tokens/matcher_token.go +++ b/sapis/tokens/matcher_token.go @@ -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, diff --git a/sapis/tokens/token.go b/sapis/tokens/token.go index 4767e0e..72df790 100644 --- a/sapis/tokens/token.go +++ b/sapis/tokens/token.go @@ -23,14 +23,12 @@ package tokens -import "activething.com/go/gogo/sapis/matches" - type ( Token interface { - matches.Matcher + Matcher Kind () TokenKind diff --git a/sapis/tokens/tokenizer.go b/sapis/tokens/tokenizer.go index ad092fb..0196854 100644 --- a/sapis/tokens/tokenizer.go +++ b/sapis/tokens/tokenizer.go @@ -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) } diff --git a/sapis/tokens/topic.go b/sapis/tokens/topic.go index 68e0286..22e2f33 100644 --- a/sapis/tokens/topic.go +++ b/sapis/tokens/topic.go @@ -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) } diff --git a/sapis/tokens/wildcard_token.go b/sapis/tokens/wildcard_token.go index ac414b9..a93b2a7 100644 --- a/sapis/tokens/wildcard_token.go +++ b/sapis/tokens/wildcard_token.go @@ -29,6 +29,7 @@ type ( WildcardToken struct{} + )