diff --git a/app/main.go b/app/main.go index 40c97a3..bc461bb 100644 --- a/app/main.go +++ b/app/main.go @@ -2,7 +2,7 @@ package main import ( "errs" - "errs/collr" + "errs/collects" "errs/fjson" "errs/ftext" "errs/stack" @@ -65,7 +65,7 @@ func (c MiCustomErr) Unwrap () error { return c.error } -func (c MiCustomErr) Collect (collector collr.Collector) { +func (c MiCustomErr) Collect (collector collects.Collector) { collector.AddFieldInt("UnInt",c.Int()) collector.AddFieldFloat("UnFloat",34.33) collector.AddFieldAny("UnoCualquiera",struct { @@ -82,7 +82,7 @@ func (c MiCustomErr) Collect (collector collr.Collector) { } -func printCollection (ec collr.ErrorCollection) { +func printCollection (ec collects.ErrorCollection) { if ec.Invalid != nil { fmt.Printf("INvalid %s\n", ec.Invalid.Error()) } diff --git a/core/ansi/non_escape_writer.go b/core/ansi/non_escape_writer.go index 77a4c6b..2f5ca13 100644 --- a/core/ansi/non_escape_writer.go +++ b/core/ansi/non_escape_writer.go @@ -43,7 +43,7 @@ func NewNonEscapeWriter(w io.Writer) *NonEscapeWriter { /* func (w *NonEscapeWriter) Write(data []byte) (n int, e error) { - var pt bytes.Buffer + var pt bytes.ABuffer var ef bool for _, b := range data { diff --git a/core/bits/active.go b/core/bits/active.go index ae00dce..3bc62b5 100644 --- a/core/bits/active.go +++ b/core/bits/active.go @@ -34,10 +34,10 @@ var ( G = struct { - ErrUnsupportedFlagType Err + ErrUnsupportedFlagType ErrBits }{ - ErrUnsupportedFlagType : Err{errs.ErrCode ("unsupported-bit-flag-type") }, + ErrUnsupportedFlagType : ErrBits{errs.ErrCode ("unsupported-bit-flag-type") }, } ) diff --git a/core/bits/err.go b/core/bits/err_bits.go similarity index 96% rename from core/bits/err.go rename to core/bits/err_bits.go index 6c80842..e268a63 100644 --- a/core/bits/err.go +++ b/core/bits/err_bits.go @@ -27,7 +27,7 @@ import "errs" type ( - Err struct { errs.ErrCode } + ErrBits struct { errs.ErrCode } ) diff --git a/core/btes/bfields/active.go b/core/btes/bfields/active.go index 17a490d..8bb9ffc 100644 --- a/core/btes/bfields/active.go +++ b/core/btes/bfields/active.go @@ -33,16 +33,16 @@ const( var ( G = struct { - ErrInvalidName ErrBField - ErrDuplicated ErrBField - ErrFixed ErrBField - ErrReadOnly ErrBField + ErrInvalidName ErrBFields + ErrDuplicated ErrBFields + ErrFixed ErrBFields + ErrReadOnly ErrBFields }{ - ErrInvalidName: ErrBField{errs.ErrCode("invalid-name")}, - ErrDuplicated : ErrBField{errs.ErrCode("duplicated-field")}, - ErrFixed : ErrBField{errs.ErrCode("bfields-fixed")}, - ErrReadOnly : ErrBField{errs.ErrCode("bfields-read-only")}, + ErrInvalidName: ErrBFields{errs.ErrCode("invalid-name")}, + ErrDuplicated : ErrBFields{errs.ErrCode("duplicated-field")}, + ErrFixed : ErrBFields{errs.ErrCode("bfields-fixed")}, + ErrReadOnly : ErrBFields{errs.ErrCode("bfields-read-only")}, } ) diff --git a/core/btes/bfields/err_bfield.go b/core/btes/bfields/err_bfields.go similarity index 96% rename from core/btes/bfields/err_bfield.go rename to core/btes/bfields/err_bfields.go index 1f634a7..20c63a7 100644 --- a/core/btes/bfields/err_bfield.go +++ b/core/btes/bfields/err_bfields.go @@ -27,6 +27,6 @@ import "errs" type ( - ErrBField struct { errs.ErrCode } + ErrBFields struct { errs.ErrCode } ) diff --git a/core/btes/matchs/active.go b/core/btes/matchs/active.go new file mode 100644 index 0000000..5897c95 --- /dev/null +++ b/core/btes/matchs/active.go @@ -0,0 +1,39 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name active.go +// Created by DEV +// Modified 24/04/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 matchs + + +var ( + + G = struct { + ErrInvalidMatcher ErrMatchs + ErrMatcherNotFound ErrMatchs + ErrInvalidBuilder ErrMatchs + }{ + ErrInvalidMatcher : ErrMatchs{ ErrCode("invalid-matcher")}, + ErrMatcherNotFound: ErrMatchs{ ErrCode("matcher-not-found")}, + ErrInvalidBuilder : ErrMatchs{ ErrCode("invalid-builder")}, + } + +) \ No newline at end of file diff --git a/core/btes/matchs/err_matchs.go b/core/btes/matchs/err_matchs.go new file mode 100644 index 0000000..001de9d --- /dev/null +++ b/core/btes/matchs/err_matchs.go @@ -0,0 +1,33 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name err_matchs.go +// Created by DEV +// Modified 24/04/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 matchs + +import "errs" + +type ( + + ErrMatchs { errs.ErrCode } +) + + diff --git a/core/btes/matchs/matcher.go b/core/btes/matchs/matcher.go new file mode 100644 index 0000000..527865b --- /dev/null +++ b/core/btes/matchs/matcher.go @@ -0,0 +1,26 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name matcher.go +// Created by DEV +// Modified 24/04/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 matchs + + diff --git a/core/btes/tokens/active.go b/core/btes/tokens/active.go new file mode 100644 index 0000000..ce5acc0 --- /dev/null +++ b/core/btes/tokens/active.go @@ -0,0 +1,43 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name active.go +// Created by DEV +// Modified 23/04/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 tokens + +import "errs" + +var ( + + G = struct { + ErrInvalidTopic ErrTokens + ErrInvalidTopicLen ErrTokens + ErrInvalidToken ErrTokens + ErrInvalidTokenLen ErrTokens + } { + ErrInvalidTopic : ErrTokens{errs.ErrCode("invalid-topic")}, + ErrInvalidTopicLen : ErrTokens{errs.ErrCode("invalid-topic-len")}, + ErrInvalidToken : ErrTokens{errs.ErrCode("invalid-token")}, + ErrInvalidTokenLen : ErrTokens{errs.ErrCode("invalid-token-len")}, + } +) + + diff --git a/core/btes/tokens/atokenizer.go b/core/btes/tokens/atokenizer.go new file mode 100644 index 0000000..377a9d7 --- /dev/null +++ b/core/btes/tokens/atokenizer.go @@ -0,0 +1,276 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name atokenizer.go +// Created by DEV +// Modified 24/04/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 tokens + + + + + + +const ( + + topicMinLen int = 1 + topicMaxLen int = 255 + topicMaxTokens int = 32 + topicMinTokens int = 1 + + tokenMinLen int = 1 + tokenMaxLen int = 256 + + // + // Token chars + // + tokenSep byte = '.' + tokenWildcard byte = '*' + tokenRelative byte = '+' + tokenMatchini byte = '{' + tokenMatchend byte = '}' + +) + + +type ( + + + + + // TokenizerCore + // Struct type + // Implements -> Tokenizer + // + TokenizerCore struct { + TokenSep byte + TokenWildcard byte + TokenRelative byte + TokenMathcIni byte + TokenMatchEnd byte + MinLenToken int + MaxLenToken int + MinLenTopic int + MaxLenTopic int + MinTokens int + MaxTokens int + + MatchBuilder mchs.Matchers + } + + + // TokenizerCoreFnc + // Function type + // + // + TokenizerCoreFnc func (tkz *TokenizerCore) + +) + + +// NewTokenizerCore +// Function constructor -> TokenizerCore +// +// +func NewTokenizerCore(ops ...TokenizerCoreFnc)(*TokenizerCore){ + tk := &TokenizerCore{ + TokenSep : tokenSep, + TokenWildcard : tokenWildcard, + TokenRelative : tokenRelative, + TokenMathcIni : tokenMatchini, + TokenMatchEnd : tokenMatchend, + MinLenToken : tokenMinLen, + MaxLenToken : tokenMaxLen, + MinLenTopic : topicMinLen, + MaxLenTopic : topicMaxLen, + MinTokens : topicMinTokens, + MaxTokens : topicMaxTokens, + } + + for _,o := range ops { + o(tk) } + + if tk.MaxTokens > topicMaxTokens { + tk.MaxTokens = topicMaxTokens + } + + if tk.MatchBuilder == nil { + tk.MatchBuilder = mchs.MatchersNoop{} } + + return tk +} + + +// NewTopic +// Function member -> TokenizerCore +// +// +func (t TokenizerCore) NewTopic (tpc []byte, alw Kind) *Topic { return NewTopic(t,tpc,alw) } + + +// Tokenize +// Function member -> TokenizerCore +// Implements -> Tokenizer +// +// +func (t TokenizerCore) Tokenize(tpc []byte, alw Kind) (Tokens, Kind){ + ln := len(tpc) + if ln < t.MinLenTopic || ln > t.MaxLenTopic { + return []Token{*(NewInvalidToken(G.ErrInvalidTopicLen,tpc)) }, TokenKindInvalid + } + + tl := [topicMaxTokens]Token{} + tt := TokenKindNone + m,c,x := 0,0,0 + + for i:=0; i= t.MaxTokens { + tl[c] = *(NewInvalidToken(G.ErrInvalidTopicLen,tpc[x:])) + return tl[:c+1], tt | TokenKindInvalid + } + tl[c] = t.NewToken(tpc[x:i]) + tk := tl[c].Kind() + if tk == TokenKindRelative { + tl[c]= NewInvalidToken(G.ErrInvalidToken,tpc[x:i]) + } else if tk & alw == 0 { + tt |= TokenKindInvalid + } + tt |= tl[c].Kind() + x = i + 1 + c++ + } + } + + if m != 0 { + tl[c] = *(NewInvalidToken(G.ErrInvalidTopic,tpc[x:])) + } else { + tl[c] = t.NewToken(tpc[x:]) + } + + return tl[:c+1], tt | tl[c].Kind() + +} + + +// Split +// Function member -> TokenizerCore +// +// +func (t TokenizerCore) Split (tpc []byte, alw Kind)([][]byte, Kind){ + var ms, ps,x int + var tk, pk Kind + ln := len(tpc) + ar := [topicMaxTokens][]byte{} + + for i:=0; i< ln; i++ { + switch tpc[i] { + case t.TokenMathcIni : ms++ + case t.TokenMatchEnd : ms-- + case t.TokenSep: + if ms == 0 { + ar[ps] = tpc[x:i] + if pk = t.Kind(ar[ps]); pk & alw == 0 { + return nil, TokenKindInvalid + } + tk|= pk + x = i + 1 + ps++ + } + } + } + ar[ps] = tpc[x:] + if pk = t.Kind(ar[ps]); pk& alw == 0 { + return nil, TokenKindInvalid + } + tk |= pk + + return ar[:ps+1],tk +} + + + + +// NewToken +// Function member -> TokenizerCore +// +// +func (t TokenizerCore) NewToken(Token []byte)(Token){ + ln := len(Token) + if ln < t.MinLenToken || ln > t.MaxLenToken { + return InvalidToken{ error: nil, source: Token } } + + if ln == 1 { + switch Token[0] { + case t.TokenWildcard : return WildcardToken{} + case t.TokenRelative : return RelativeToken{} + case t.TokenMathcIni, + t.TokenMatchEnd : return *(NewInvalidToken(G.ErrInvalidTopicLen,Token)) } + } + + if Token[0] != t.TokenMathcIni { + return LiteralToken(Token) } + + if Token[ln-1] == t.TokenMatchEnd && ln > t.MinLenToken+ 2 { + m,e := t.MatchBuilder.Build(Token) + if e == nil { + return *(NewMatcherToken(m.Match,Token)) } + return *(NewInvalidToken(e,Token)) + } + + return *(NewInvalidToken(mchs.Errs.ErrInvalidMatcher,Token)) +} + + + + +// Kind +// Function member -> TokenizerCore +// +func (t TokenizerCore) Kind (Token []byte)(Kind){ + ln := len(Token) + if ln < t.MinLenToken || ln > t.MaxLenToken { + return TokenKindInvalid + } + + if ln == 1 { + switch Token[0] { + case t.TokenWildcard : return TokenWildcard + case t.TokenRelative : return TokenRelative + case t.TokenMathcIni, + t.TokenMatchEnd : return TokenKindInvalid + } + } + + if Token[0] == t.TokenMathcIni { + if Token[ln-1] == t.TokenMatchEnd { + return TokenMatcher } + return TokenKindInvalid + } + return TokenLiteral +} + + + diff --git a/core/btes/tokens/err_tokens.go b/core/btes/tokens/err_tokens.go new file mode 100644 index 0000000..8786f3f --- /dev/null +++ b/core/btes/tokens/err_tokens.go @@ -0,0 +1,34 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name err_token.go +// Created by DEV +// Modified 23/04/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 tokens + +import "errs" + +type ( + + ErrTokens struct { errs.ErrCode } + +) + + diff --git a/core/btes/tokens/kind.go b/core/btes/tokens/kind.go new file mode 100644 index 0000000..4fa6a26 --- /dev/null +++ b/core/btes/tokens/kind.go @@ -0,0 +1,77 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name kind.go +// Created by DEV +// Modified 23/04/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 tokens + +const ( + + // Kind enum values + // + TokenKindNone Kind = 0 + TokenKindLiteral Kind = 1 + TokenKindWildcard Kind = 2 + TokenKindMatcher Kind = 4 + TokenKindRelative Kind = 8 + TokenKindInvalid Kind = 128 + // + // Kind compund values + // + TokenKindAny = TokenKindRelative | TokenKindWildcard + TokenKindTopic = TokenKindLiteral | TokenKindMatcher | TokenKindAny + TokenKindMatchable= TokenKindLiteral | TokenKindMatcher + TokenKindAll = TokenKindInvalid | TokenKindTopic + +) + + + +type ( + + Kind uint8 + +) + + + + +func (t Kind) HasLiteral () bool { + return t &TokenKindLiteral != 0 } + +func (t Kind) HasRelative () bool { + return t &TokenKindRelative != 0 } + +func (t Kind) HasWildcard () bool { + return t &TokenKindWildcard != 0 } + +func (t Kind) HasMatcher () bool { + return t &TokenKindMatcher != 0 } + +func (t Kind) HasInvalid () bool { + return t &TokenKindInvalid != 0 } + +func (t Kind) HasAny () bool { + return t &TokenKindAny != 0 } + +func (t Kind) HasMatchable() bool { + return t &TokenKindMatchable != 0 } + diff --git a/core/btes/tokens/token.go b/core/btes/tokens/token.go new file mode 100644 index 0000000..8363caa --- /dev/null +++ b/core/btes/tokens/token.go @@ -0,0 +1,36 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name token.go +// Created by DEV +// Modified 23/04/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 tokens + + +type ( + + Token interface { + Kind () Kind + Source() []byte + + Match (val []byte) bool + } + +) \ No newline at end of file diff --git a/core/btes/tokens/token_invalid.go b/core/btes/tokens/token_invalid.go new file mode 100644 index 0000000..61cf2d8 --- /dev/null +++ b/core/btes/tokens/token_invalid.go @@ -0,0 +1,49 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name token_invalid.go +// Created by DEV +// Modified 23/04/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 tokens + + +type ( + + InvalidToken struct { + error + source []byte + } + +) + + +func NewInvalidToken(err error, src []byte) *InvalidToken { + return &InvalidToken{ error : err, source: src }} + + +func (_ InvalidToken) Kind () Kind { + return TokenKindInvalid +} + +func (_ InvalidToken) Match (_ []byte) bool { + return false } + +func (t InvalidToken) Source()[]byte { + return t.source } diff --git a/core/btes/tokens/token_literal.go b/core/btes/tokens/token_literal.go new file mode 100644 index 0000000..9428906 --- /dev/null +++ b/core/btes/tokens/token_literal.go @@ -0,0 +1,46 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name token_literal.go +// Created by DEV +// Modified 23/04/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 tokens + +import "bytes" + +type ( + + + // LiteralToken + // Implements -> Token + LiteralToken []byte + +) + + +func (_ LiteralToken) Kind () Kind { + return TokenKindLiteral +} + +func (t LiteralToken) Match (val []byte) bool { + return bytes.Equal(t, val) } + +func (t LiteralToken) Source()[]byte { + return t } \ No newline at end of file diff --git a/core/btes/tokens/token_matcher.go b/core/btes/tokens/token_matcher.go new file mode 100644 index 0000000..44b212b --- /dev/null +++ b/core/btes/tokens/token_matcher.go @@ -0,0 +1,50 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name token_matcher.go +// Created by DEV +// Modified 23/04/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 tokens + + +type ( + + MatcherToken struct { + source []byte + matchFn MatchFnc + } + + MatchFnc func (target []byte) bool +) + + +func NewMatcherToken (mfn MatchFnc, src []byte) *MatcherToken { + return &MatcherToken{ matchFn: mfn, source: src } } + + +func (_ MatcherToken) Kind () Kind { + return TokenKindMatcher +} + +func (t MatcherToken) Match(val []byte) bool { + return t.matchFn(val) } + +func (t MatcherToken) Source()[]byte { + return t.source } \ No newline at end of file diff --git a/core/btes/tokens/token_relative.go b/core/btes/tokens/token_relative.go new file mode 100644 index 0000000..1e75434 --- /dev/null +++ b/core/btes/tokens/token_relative.go @@ -0,0 +1,43 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name token_relative.go +// Created by DEV +// Modified 23/04/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 tokens + + + + +type ( + + RelativeToken struct {} +) + + +func (_ RelativeToken) Kind () Kind { + return TokenKindRelative +} + +func (_ RelativeToken) Match(_ []byte) bool { + return true } + +func (_ RelativeToken) Source()[]byte { + return nil } diff --git a/core/btes/tokens/token_wildcard.go b/core/btes/tokens/token_wildcard.go new file mode 100644 index 0000000..60012f1 --- /dev/null +++ b/core/btes/tokens/token_wildcard.go @@ -0,0 +1,41 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name token_wildcard.go +// Created by DEV +// Modified 23/04/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 tokens + + +type ( + + WildcardToken struct {} +) + + +func (_ WildcardToken) Kind () Kind { + return TokenKindWildcard +} + +func (_ WildcardToken) Match(_ []byte) bool { + return true } + +func (_ WildcardToken) Source()[]byte { + return nil } diff --git a/core/btes/tokens/tokenizer.go b/core/btes/tokens/tokenizer.go new file mode 100644 index 0000000..b29be8d --- /dev/null +++ b/core/btes/tokens/tokenizer.go @@ -0,0 +1,41 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name tokenizer.go +// Created by DEV +// Modified 24/04/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 tokens + + +type ( + + Tokenizer interface { + + NewToken (Token []byte) Token + + TokenKind (Token []byte) Kind + + Split (subject []byte, allow Kind) ([][]byte , Kind) + Tokenize (topic []byte, allow Kind) (Tokens, Kind) + } + +) + + diff --git a/core/btes/tokens/tokens.go b/core/btes/tokens/tokens.go new file mode 100644 index 0000000..8009e7e --- /dev/null +++ b/core/btes/tokens/tokens.go @@ -0,0 +1,32 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name tokens.go +// Created by DEV +// Modified 23/04/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 tokens + + + + +type ( + + Tokens []Token +) \ No newline at end of file diff --git a/core/btes/tokens/topic.go b/core/btes/tokens/topic.go new file mode 100644 index 0000000..a4ad66b --- /dev/null +++ b/core/btes/tokens/topic.go @@ -0,0 +1,64 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name topic.go +// Created by DEV +// Modified 24/04/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 tokens + + + +type ( + + + // Topic + // Struct type + // + // + Topic struct { + kind Kind + source []byte + tokens Tokens + } + + + + // TopicList + // Slice type + // Implements -> sort.Interface + // + // + TopicList []Topic + +) + + +// NewTopic +// Function constructor -> Topic +// +// +func NewTopic (tkz Tokenizer, tpc []byte, alw Kind)(*Topic){ + tp := &Topic{ + source : tpc } + tp.tokens, + tp.kind = tkz.Tokenize(tpc,alw) + return tp +} + diff --git a/core/tbase/astrings/active.go b/core/btypes/astrings/active.go similarity index 100% rename from core/tbase/astrings/active.go rename to core/btypes/astrings/active.go diff --git a/core/tbase/astrings/camel.go b/core/btypes/astrings/camel.go similarity index 100% rename from core/tbase/astrings/camel.go rename to core/btypes/astrings/camel.go diff --git a/core/tbase/astrings/snake.go b/core/btypes/astrings/snake.go similarity index 100% rename from core/tbase/astrings/snake.go rename to core/btypes/astrings/snake.go diff --git a/core/tbase/astrings/string.go b/core/btypes/astrings/string.go similarity index 100% rename from core/tbase/astrings/string.go rename to core/btypes/astrings/string.go diff --git a/core/tbase/astrings/transformer.go b/core/btypes/astrings/transformer.go similarity index 100% rename from core/tbase/astrings/transformer.go rename to core/btypes/astrings/transformer.go diff --git a/core/tbase/astrings/transformers.go b/core/btypes/astrings/transformers.go similarity index 100% rename from core/tbase/astrings/transformers.go rename to core/btypes/astrings/transformers.go diff --git a/core/btypes/go.mod b/core/btypes/go.mod new file mode 100644 index 0000000..40534d4 --- /dev/null +++ b/core/btypes/go.mod @@ -0,0 +1,3 @@ +module btypes + +go 1.22 diff --git a/core/tbase/numbers.go b/core/btypes/numbers.go similarity index 100% rename from core/tbase/numbers.go rename to core/btypes/numbers.go diff --git a/core/tbase/slices/strings.go b/core/btypes/slices/strings.go similarity index 100% rename from core/tbase/slices/strings.go rename to core/btypes/slices/strings.go diff --git a/core/cdcs/go.mod b/core/cdcs/go.mod deleted file mode 100644 index f1a9eb0..0000000 --- a/core/cdcs/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module cdcs - -go 1.22 diff --git a/core/codecs/base32/writer.go b/core/codecs/base32/writer.go new file mode 100644 index 0000000..4e6e7b2 --- /dev/null +++ b/core/codecs/base32/writer.go @@ -0,0 +1,70 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name writer.go +// Created by DEV +// Modified 23/04/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 base32 + +import ( + "bins/mems" + "encoding/base32" +) + +func Write(b *mems.ABuffer, value, null, empty []byte, isQuoted bool, quote byte) (er error) { + if value == nil { + _,_ = b.Write(null) + return nil + } + if len(value) == 0 { + _,_ = b.Write(empty) + return nil + } + + p := b.Len() + if isQuoted { + b.WriteByte(quote) + } + + var t [64]byte + ln := base32.StdEncoding.EncodedLen(len(value)) + if ln <= len(t) { + dst := t[:ln] + base32.StdEncoding.Encode(dst, value) + _,er = b.Write(dst) + } else if ln <= 1024 { + dst := make([]byte, ln) + base32.StdEncoding.Encode(dst, value) + _,er = b.Write(dst) + } else if er == nil { + ec := base32.NewEncoder(base32.StdEncoding, b) + _,_ = ec.Write(value) + return ec.Close() + } + + if er == nil { + if isQuoted { + b.WriteByte(quote) + } + } else { + b.Truncate(p) + } + return er +} diff --git a/core/btes/bfers/writer_encoding.go b/core/codecs/base64/writer.go similarity index 64% rename from core/btes/bfers/writer_encoding.go rename to core/codecs/base64/writer.go index 088f259..52f5643 100644 --- a/core/btes/bfers/writer_encoding.go +++ b/core/codecs/base64/writer.go @@ -2,7 +2,7 @@ // Project active2 // Active Thing (activething.com) git.activething.com/go // -// File name writer_encoding.go +// File name writer.go // Created by DEV // Modified 23/04/2024 // @@ -21,14 +21,16 @@ // limitations under the License. // ------------------------------------------------------------------------ -package bfers +package base64 import ( - "encoding/base32" + "bins/mems" "encoding/base64" ) -func (b *Buffer) WriteBase64(value, null, empty []byte, isQuoted bool, quote byte) (er error) { + + +func Write(b *mems.ABuffer, value, null, empty []byte, isQuoted bool, quote byte) (er error) { if value == nil { _,_ = b.Write(null) return nil @@ -72,45 +74,3 @@ func (b *Buffer) WriteBase64(value, null, empty []byte, isQuoted bool, quote byt -func (b *Buffer) WriteBase32(value, null, empty []byte, isQuoted bool, quote byte) (er error) { - if value == nil { - _,_ = b.Write(null) - return nil - } - if len(value) == 0 { - _,_ = b.Write(empty) - return nil - } - - p := b.Len() - if isQuoted { - b.WriteByte(quote) - } - - var t [64]byte - ln := base32.StdEncoding.EncodedLen(len(value)) - if ln <= len(t) { - dst := t[:ln] - base32.StdEncoding.Encode(dst, value) - _,er = b.Write(dst) - } else if ln <= 1024 { - dst := make([]byte, ln) - base32.StdEncoding.Encode(dst, value) - _,er = b.Write(dst) - } else if er == nil { - ec := base32.NewEncoder(base32.StdEncoding, b) - _,_ = ec.Write(value) - return ec.Close() - } - - if er == nil { - if isQuoted { - b.WriteByte(quote) - } - } else { - b.Truncate(p) - } - return er -} - - diff --git a/core/cdcs/cjson/active.go b/core/codecs/cjson/active.go similarity index 100% rename from core/cdcs/cjson/active.go rename to core/codecs/cjson/active.go diff --git a/core/cdcs/cjson/char_att.go b/core/codecs/cjson/char_att.go similarity index 100% rename from core/cdcs/cjson/char_att.go rename to core/codecs/cjson/char_att.go diff --git a/core/cdcs/cjson/writer.go b/core/codecs/cjson/writer.go similarity index 82% rename from core/cdcs/cjson/writer.go rename to core/codecs/cjson/writer.go index ef36e90..edc46a7 100644 --- a/core/cdcs/cjson/writer.go +++ b/core/codecs/cjson/writer.go @@ -24,7 +24,9 @@ package cjson import ( - "bins/bfers" + "bins/mems" + "codecs/base32" + "codecs/base64" "math" "strconv" "time" @@ -32,7 +34,7 @@ import ( ) -func WriteString(b *bfers.Buffer, value string, escapeHTML bool ) { +func WriteString(b *mems.ABuffer, value string, escapeHTML bool ) { if len(value) == 0 { b.Write2Byte('"', '"') return @@ -100,7 +102,7 @@ func WriteString(b *bfers.Buffer, value string, escapeHTML bool ) { -func WriteUint (b *bfers.Buffer, value uint64 , quoted bool) { +func WriteUint (b *mems.ABuffer, value uint64 , quoted bool) { if quoted { b.WriteByte('"') } @@ -115,7 +117,7 @@ func WriteUint (b *bfers.Buffer, value uint64 , quoted bool) { } -func WriteBool (b *bfers.Buffer, value bool , quoted bool) { +func WriteBool (b *mems.ABuffer, value bool , quoted bool) { if value { b.WOQ(quoted,'"', G.TrueValue) } else { @@ -124,7 +126,7 @@ func WriteBool (b *bfers.Buffer, value bool , quoted bool) { } -func WriteInt (b *bfers.Buffer, value int64 , quoted bool) { +func WriteInt (b *mems.ABuffer, value int64 , quoted bool) { if quoted { b.WriteByte('"') } @@ -139,7 +141,7 @@ func WriteInt (b *bfers.Buffer, value int64 , quoted bool) { } -func WriteFloat (b *bfers.Buffer, f float64, bits int, quoted bool) { +func WriteFloat (b *mems.ABuffer, f float64, bits int, quoted bool) { var t [64]byte if math.IsInf(f, 0) || math.IsNaN(f) { _,_ = b.Write(G.FloatNaN) @@ -169,7 +171,7 @@ func WriteFloat (b *bfers.Buffer, f float64, bits int, quoted bool) { } -func WriteDate(b *bfers.Buffer, value time.Time, layout string, quote bool) { +func WriteDate(b *mems.ABuffer, value time.Time, layout string, quote bool) { if layout == "" { layout = time.RFC3339 } @@ -183,9 +185,9 @@ func WriteDate(b *bfers.Buffer, value time.Time, layout string, quote bool) { } -func WriteBase64(b *bfers.Buffer, value []byte) (er error) { - return b.WriteBase64(value,G.NullValue,G.EmptyValue,true,'"') } +func WriteBase64(b *mems.ABuffer, value []byte) (er error) { + return base64.Write(b,value,G.NullValue,G.EmptyValue,true,'"') } -func WriteBase32(b *bfers.Buffer, value []byte) (er error) { - return b.WriteBase32(value,G.NullValue,G.EmptyValue,true,'"') } \ No newline at end of file +func WriteBase32(b *mems.ABuffer, value []byte) (er error) { + return base32.Write(b,value,G.NullValue,G.EmptyValue,true,'"') } \ No newline at end of file diff --git a/core/codecs/go.mod b/core/codecs/go.mod new file mode 100644 index 0000000..70099ac --- /dev/null +++ b/core/codecs/go.mod @@ -0,0 +1,3 @@ +module codecs + +go 1.22 diff --git a/core/timers/active.go b/core/cronus/active.go similarity index 62% rename from core/timers/active.go rename to core/cronus/active.go index 909a28a..dd7d73e 100644 --- a/core/timers/active.go +++ b/core/cronus/active.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package timers +package cronus import "errs" @@ -29,24 +29,24 @@ var ( G = struct { - ErrExpired Err - ErrTimeout Err - ErrIntervalInvalid Err - ErrNotStarted Err - ErrNotPaused Err - ErrAlreadyStarted Err - ErrTransitionInvalid Err - ErrTimerTaskInvalid Err + ErrExpired ErrCronus + ErrTimeout ErrCronus + ErrIntervalInvalid ErrCronus + ErrNotStarted ErrCronus + ErrNotPaused ErrCronus + ErrAlreadyStarted ErrCronus + ErrTransitionInvalid ErrCronus + ErrTimerTaskInvalid ErrCronus } { - ErrExpired: Err{ errs.ErrCode("expired")}, - ErrTimeout: Err{ errs.ErrCode("timeout")}, - ErrIntervalInvalid: Err{ errs.ErrCode("interval_invalid")}, - ErrNotStarted: Err{ errs.ErrCode("not_started")}, - ErrNotPaused: Err{ errs.ErrCode("not_paused")}, - ErrAlreadyStarted: Err{ errs.ErrCode("already_started")}, - ErrTransitionInvalid: Err{ errs.ErrCode("transition_invalid")}, - ErrTimerTaskInvalid: Err{ errs.ErrCode("timer_task_invalid")}, + ErrExpired: ErrCronus{errs.ErrCode("expired")}, + ErrTimeout: ErrCronus{errs.ErrCode("timeout")}, + ErrIntervalInvalid: ErrCronus{errs.ErrCode("interval_invalid")}, + ErrNotStarted: ErrCronus{errs.ErrCode("not_started")}, + ErrNotPaused: ErrCronus{errs.ErrCode("not_paused")}, + ErrAlreadyStarted: ErrCronus{errs.ErrCode("already_started")}, + ErrTransitionInvalid: ErrCronus{errs.ErrCode("transition_invalid")}, + ErrTimerTaskInvalid: ErrCronus{errs.ErrCode("timer_task_invalid")}, } diff --git a/core/timers/chrono.go b/core/cronus/chrono.go similarity index 99% rename from core/timers/chrono.go rename to core/cronus/chrono.go index 9164614..7df013a 100644 --- a/core/timers/chrono.go +++ b/core/cronus/chrono.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package timers +package cronus import ( "sync/atomic" diff --git a/core/timers/chronometer.go b/core/cronus/chronometer.go similarity index 98% rename from core/timers/chronometer.go rename to core/cronus/chronometer.go index da30045..4b825c0 100644 --- a/core/timers/chronometer.go +++ b/core/cronus/chronometer.go @@ -22,7 +22,7 @@ // ------------------------------------------------------------------------ -package timers +package cronus import ( "time" diff --git a/core/timers/err.go b/core/cronus/err_cronus.go similarity index 95% rename from core/timers/err.go rename to core/cronus/err_cronus.go index 35a9957..e704bff 100644 --- a/core/timers/err.go +++ b/core/cronus/err_cronus.go @@ -21,12 +21,12 @@ // limitations under the License. // ------------------------------------------------------------------------ -package timers +package cronus import "errs" type ( - Err struct { errs.ErrCode } + ErrCronus struct { errs.ErrCode } ) \ No newline at end of file diff --git a/core/timers/expiration.go b/core/cronus/expiration.go similarity index 99% rename from core/timers/expiration.go rename to core/cronus/expiration.go index 66e303b..4b5258e 100644 --- a/core/timers/expiration.go +++ b/core/cronus/expiration.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package timers +package cronus import ( "sync/atomic" diff --git a/core/timers/expiration_source.go b/core/cronus/expiration_source.go similarity index 99% rename from core/timers/expiration_source.go rename to core/cronus/expiration_source.go index da24175..019aebd 100644 --- a/core/timers/expiration_source.go +++ b/core/cronus/expiration_source.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package timers +package cronus const ( diff --git a/core/timers/expirer.go b/core/cronus/expirer.go similarity index 98% rename from core/timers/expirer.go rename to core/cronus/expirer.go index 7162bf1..3fec93f 100644 --- a/core/timers/expirer.go +++ b/core/cronus/expirer.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package timers +package cronus import ( "time" diff --git a/core/timers/go.mod b/core/cronus/go.mod similarity index 100% rename from core/timers/go.mod rename to core/cronus/go.mod diff --git a/core/timers/pulsar.go b/core/cronus/pulsar.go similarity index 99% rename from core/timers/pulsar.go rename to core/cronus/pulsar.go index b87545d..746468b 100644 --- a/core/timers/pulsar.go +++ b/core/cronus/pulsar.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package timers +package cronus import ( "context" diff --git a/core/timers/time_task.go b/core/cronus/time_task.go similarity index 98% rename from core/timers/time_task.go rename to core/cronus/time_task.go index 5bcc147..3b896fc 100644 --- a/core/timers/time_task.go +++ b/core/cronus/time_task.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package timers +package cronus import ( "context" diff --git a/core/timers/timer_queue.go b/core/cronus/timer_queue.go similarity index 99% rename from core/timers/timer_queue.go rename to core/cronus/timer_queue.go index a991ba0..31e94f1 100644 --- a/core/timers/timer_queue.go +++ b/core/cronus/timer_queue.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package timers +package cronus import ( "container/heap" diff --git a/core/timers/timer_state.go b/core/cronus/timer_state.go similarity index 99% rename from core/timers/timer_state.go rename to core/cronus/timer_state.go index 00c88b2..214ac89 100644 --- a/core/timers/timer_state.go +++ b/core/cronus/timer_state.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package timers +package cronus const ( diff --git a/core/timers/timer_task.go b/core/cronus/timer_task.go similarity index 99% rename from core/timers/timer_task.go rename to core/cronus/timer_task.go index e52ef44..15d2c83 100644 --- a/core/timers/timer_task.go +++ b/core/cronus/timer_task.go @@ -22,7 +22,7 @@ // ------------------------------------------------------------------------ -package timers +package cronus import ( "time" diff --git a/core/timers/timer_task_heap.go b/core/cronus/timer_task_heap.go similarity index 99% rename from core/timers/timer_task_heap.go rename to core/cronus/timer_task_heap.go index 13f53dd..0de58cb 100644 --- a/core/timers/timer_task_heap.go +++ b/core/cronus/timer_task_heap.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package timers +package cronus type ( diff --git a/core/crypts/active.go b/core/crypts/active.go index 22a1ceb..541a82f 100644 --- a/core/crypts/active.go +++ b/core/crypts/active.go @@ -28,8 +28,8 @@ import "errs" var ( G = struct { - ErrNotImplemented Err + ErrNotImplemented ErrCrypts }{ - ErrNotImplemented: Err { errs.ErrCode("crypter-not-implemented")} , + ErrNotImplemented: ErrCrypts{errs.ErrCode("crypter-not-implemented")} , } ) \ No newline at end of file diff --git a/core/crypts/err.go b/core/crypts/err_crypts.go similarity index 96% rename from core/crypts/err.go rename to core/crypts/err_crypts.go index cfc6ca7..5f94c2b 100644 --- a/core/crypts/err.go +++ b/core/crypts/err_crypts.go @@ -25,6 +25,6 @@ package crypts import "errs" -type Err struct { errs.ErrCode } +type ErrCrypts struct { errs.ErrCode } diff --git a/core/times/active.go b/core/dates/active.go similarity index 93% rename from core/times/active.go rename to core/dates/active.go index 6b4a364..4a91726 100644 --- a/core/times/active.go +++ b/core/dates/active.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package times +package dates import "errs" @@ -36,10 +36,10 @@ var ( G = struct { - ErrInvalidDateRange Err + ErrInvalidDateRange ErrDates }{ - ErrInvalidDateRange : Err{ errs.ErrCode ("invalid-date-range")}, + ErrInvalidDateRange : ErrDates{errs.ErrCode ("invalid-date-range")}, } ) diff --git a/core/times/bdates/active.go b/core/dates/bdates/active.go similarity index 100% rename from core/times/bdates/active.go rename to core/dates/bdates/active.go diff --git a/core/times/bdates/bmonth.go b/core/dates/bdates/bmonth.go similarity index 100% rename from core/times/bdates/bmonth.go rename to core/dates/bdates/bmonth.go diff --git a/core/times/bdates/bweek.go b/core/dates/bdates/bweek.go similarity index 100% rename from core/times/bdates/bweek.go rename to core/dates/bdates/bweek.go diff --git a/core/times/bdates/byear.go b/core/dates/bdates/byear.go similarity index 97% rename from core/times/bdates/byear.go rename to core/dates/bdates/byear.go index 7cab073..3491d1a 100644 --- a/core/times/bdates/byear.go +++ b/core/dates/bdates/byear.go @@ -44,12 +44,12 @@ func NewBYear (year int) *BYear { panic(G.ErrInvalidYear) } at := BYearAtt(BYearAttSet) - if times.IsYearLeap(year) { + if dates.IsYearLeap(year) { at|=BYearAttLeap } return &BYear { atts : at, - first: byte(times.DayOfWeek(year,1,1)), + first: byte(dates.DayOfWeek(year,1,1)), year : byte(year-1900), } } diff --git a/core/times/bdates/byear_att.go b/core/dates/bdates/byear_att.go similarity index 100% rename from core/times/bdates/byear_att.go rename to core/dates/bdates/byear_att.go diff --git a/core/times/bdates/err.go b/core/dates/bdates/err.go similarity index 100% rename from core/times/bdates/err.go rename to core/dates/bdates/err.go diff --git a/core/times/date_days.go b/core/dates/date_days.go similarity index 99% rename from core/times/date_days.go rename to core/dates/date_days.go index 70e1931..711c7c1 100644 --- a/core/times/date_days.go +++ b/core/dates/date_days.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package times +package dates import "time" diff --git a/core/times/date_days_range.go b/core/dates/date_days_range.go similarity index 99% rename from core/times/date_days_range.go rename to core/dates/date_days_range.go index d9a40c3..3417350 100644 --- a/core/times/date_days_range.go +++ b/core/dates/date_days_range.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package times +package dates type ( diff --git a/core/times/duration_formatter.go b/core/dates/duration_formatter.go similarity index 99% rename from core/times/duration_formatter.go rename to core/dates/duration_formatter.go index d7b059f..eab99e1 100644 --- a/core/times/duration_formatter.go +++ b/core/dates/duration_formatter.go @@ -22,7 +22,7 @@ // ------------------------------------------------------------------------ -package times +package dates import ( "strconv" diff --git a/core/times/err.go b/core/dates/err_dates.go similarity index 95% rename from core/times/err.go rename to core/dates/err_dates.go index 76537f4..d285d31 100644 --- a/core/times/err.go +++ b/core/dates/err_dates.go @@ -21,13 +21,13 @@ // limitations under the License. // ------------------------------------------------------------------------ -package times +package dates import "errs" type ( - Err struct { errs.ErrCode } + ErrDates struct { errs.ErrCode } ) diff --git a/core/times/go.mod b/core/dates/go.mod similarity index 100% rename from core/times/go.mod rename to core/dates/go.mod diff --git a/core/times/time_formatter.go b/core/dates/time_formatter.go similarity index 99% rename from core/times/time_formatter.go rename to core/dates/time_formatter.go index d8f86ed..90ffaaa 100644 --- a/core/times/time_formatter.go +++ b/core/dates/time_formatter.go @@ -22,7 +22,7 @@ // ------------------------------------------------------------------------ -package times +package dates import ( "strconv" diff --git a/core/errs/active.go b/core/errs/active.go index eb0eadc..cc9966e 100644 --- a/core/errs/active.go +++ b/core/errs/active.go @@ -28,8 +28,6 @@ import ( "errs/ftext" "errs/stack" "fmt" - "reflect" - "sync" ) const ( @@ -73,12 +71,15 @@ var ( Formatter : ftext.DefaultFormatter(), } + /* g = struct { mux sync.RWMutex stackTraceRType reflect.Type }{ stackTraceRType : reflect.TypeOf(stack.Trace(nil)), } + + */ ) diff --git a/core/errs/collr/active.go b/core/errs/collects/active.go similarity index 99% rename from core/errs/collr/active.go rename to core/errs/collects/active.go index 07a95d3..3050747 100644 --- a/core/errs/collr/active.go +++ b/core/errs/collects/active.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package collr +package collects import ( "reflect" diff --git a/core/errs/collr/collectable.go b/core/errs/collects/collectable.go similarity index 98% rename from core/errs/collr/collectable.go rename to core/errs/collects/collectable.go index 8fcf8d0..4c2a656 100644 --- a/core/errs/collr/collectable.go +++ b/core/errs/collects/collectable.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package collr +package collects type ( diff --git a/core/errs/collr/collector.go b/core/errs/collects/collector.go similarity index 98% rename from core/errs/collr/collector.go rename to core/errs/collects/collector.go index 6d64fbe..4524757 100644 --- a/core/errs/collr/collector.go +++ b/core/errs/collects/collector.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package collr +package collects import "time" diff --git a/core/errs/collr/error_collection.go b/core/errs/collects/error_collection.go similarity index 99% rename from core/errs/collr/error_collection.go rename to core/errs/collects/error_collection.go index 99dad57..6dc4eae 100644 --- a/core/errs/collr/error_collection.go +++ b/core/errs/collects/error_collection.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package collr +package collects import ( "errors" diff --git a/core/errs/collr/error_collector.go b/core/errs/collects/error_collector.go similarity index 95% rename from core/errs/collr/error_collector.go rename to core/errs/collects/error_collector.go index d56e6fb..cc274e1 100644 --- a/core/errs/collr/error_collector.go +++ b/core/errs/collects/error_collector.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package collr +package collects type ( diff --git a/core/errs/collr/field_collector.go b/core/errs/collects/field_collector.go similarity index 98% rename from core/errs/collr/field_collector.go rename to core/errs/collects/field_collector.go index 4904a14..c76d0b5 100644 --- a/core/errs/collr/field_collector.go +++ b/core/errs/collects/field_collector.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package collr +package collects type ( diff --git a/core/errs/collr/field_collectors.go b/core/errs/collects/field_collectors.go similarity index 98% rename from core/errs/collr/field_collectors.go rename to core/errs/collects/field_collectors.go index 25d13d9..2e74b61 100644 --- a/core/errs/collr/field_collectors.go +++ b/core/errs/collects/field_collectors.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package collr +package collects type ( diff --git a/core/errs/collr/field_head.go b/core/errs/collects/field_head.go similarity index 98% rename from core/errs/collr/field_head.go rename to core/errs/collects/field_head.go index d40eeaf..68cdea4 100644 --- a/core/errs/collr/field_head.go +++ b/core/errs/collects/field_head.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package collr +package collects type ( diff --git a/core/errs/collr/field_kind.go b/core/errs/collects/field_kind.go similarity index 98% rename from core/errs/collr/field_kind.go rename to core/errs/collects/field_kind.go index a67ba15..1fd22a5 100644 --- a/core/errs/collr/field_kind.go +++ b/core/errs/collects/field_kind.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package collr +package collects const ( diff --git a/core/errs/collr/fields.go b/core/errs/collects/fields.go similarity index 99% rename from core/errs/collr/fields.go rename to core/errs/collects/fields.go index dca5db3..0290e62 100644 --- a/core/errs/collr/fields.go +++ b/core/errs/collects/fields.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package collr +package collects import ( "sort" diff --git a/core/errs/err_cause.go b/core/errs/err_cause.go index a0b6606..92dced9 100644 --- a/core/errs/err_cause.go +++ b/core/errs/err_cause.go @@ -23,7 +23,7 @@ package errs -import "errs/collr" +import "errs/collects" type ( @@ -67,4 +67,4 @@ func (e ErrCause) String () string { return string(G.Formatter.FormatError(e)) } -func (_ ErrCause) Collect(_ collr.Collector) {} \ No newline at end of file +func (_ ErrCause) Collect(_ collects.Collector) {} \ No newline at end of file diff --git a/core/errs/err_code.go b/core/errs/err_code.go index 0407e3c..f2f4bb3 100644 --- a/core/errs/err_code.go +++ b/core/errs/err_code.go @@ -23,7 +23,7 @@ package errs -import "errs/collr" +import "errs/collects" type ( @@ -69,6 +69,6 @@ func (e ErrCode) String () string { return string(G.Formatter.FormatError(e)) } -func (e ErrCode) Collect (collector collr.Collector) { +func (e ErrCode) Collect (collector collects.Collector) { collector.AddFieldString(fieldNameCode,string(e)) } \ No newline at end of file diff --git a/core/errs/err_info.go b/core/errs/err_info.go index fa8da81..e4909d1 100644 --- a/core/errs/err_info.go +++ b/core/errs/err_info.go @@ -24,7 +24,7 @@ package errs import ( - "errs/collr" + "errs/collects" "fmt" "time" ) @@ -103,7 +103,7 @@ func (e ErrInfo) String () string { -func (e ErrInfo) Collect (collector collr.Collector) { +func (e ErrInfo) Collect (collector collects.Collector) { collector.AddFieldString(fieldNameMessage,e.message) collector.AddFieldString(fieldNameInfo,e.info) collector.AddFieldDate (fieldNameDate,e.date) diff --git a/core/errs/err_multi.go b/core/errs/err_multi.go index d74db54..0fe7801 100644 --- a/core/errs/err_multi.go +++ b/core/errs/err_multi.go @@ -23,7 +23,7 @@ package errs -import "errs/collr" +import "errs/collects" type ( @@ -71,6 +71,6 @@ func (e ErrMulti) String () string { -func (_ ErrMulti) Collect (collector collr.Collector) { +func (_ ErrMulti) Collect (collector collects.Collector) { collector.AddFieldString(fieldNameCode,CodeMultiError) } diff --git a/core/errs/err_panic.go b/core/errs/err_panic.go index 8f45d9c..3ffeebb 100644 --- a/core/errs/err_panic.go +++ b/core/errs/err_panic.go @@ -23,7 +23,7 @@ package errs -import "errs/collr" +import "errs/collects" type ( @@ -68,5 +68,5 @@ func (e ErrPanic) String () string { -func (_ ErrPanic) Collect (collector collr.Collector) { +func (_ ErrPanic) Collect (collector collects.Collector) { collector.AddFieldString(fieldNameCode,CodePanicError) } \ No newline at end of file diff --git a/core/errs/err_param.go b/core/errs/err_param.go index c2cb58f..46811b6 100644 --- a/core/errs/err_param.go +++ b/core/errs/err_param.go @@ -24,7 +24,7 @@ package errs import ( - "errs/collr" + "errs/collects" "fmt" ) @@ -85,7 +85,7 @@ func (e ErrParam) String () string { return string(G.Formatter.FormatError(e)) } -func (e ErrParam) Collect(collector collr.Collector) { +func (e ErrParam) Collect(collector collects.Collector) { collector.AddFieldString(fieldNameCode,e.code) if len(e.param) > 0 { collector.AddFieldString(fieldNameParam,e.param) diff --git a/core/errs/err_trace.go b/core/errs/err_trace.go index f6fb20f..29344b5 100644 --- a/core/errs/err_trace.go +++ b/core/errs/err_trace.go @@ -24,7 +24,7 @@ package errs import ( - "errs/collr" + "errs/collects" "errs/stack" ) @@ -83,4 +83,4 @@ func (e ErrTrace) String () string { -func (_ ErrTrace) Collect (_ collr.Collector) {} \ No newline at end of file +func (_ ErrTrace) Collect (_ collects.Collector) {} \ No newline at end of file diff --git a/core/errs/fjson/json_builder.go b/core/errs/fjson/json_builder.go index 07f799b..759dcb8 100644 --- a/core/errs/fjson/json_builder.go +++ b/core/errs/fjson/json_builder.go @@ -24,10 +24,10 @@ package fjson import ( - "bins/bfers" - "cdcs/cjson" + "bins/mems" + "codecs/cjson" "encoding/json" - "errs/collr" + "errs/collects" "fmt" "strings" ) @@ -37,7 +37,7 @@ type ( jsonBuilder struct { f *JSONFormatter - b *bfers.Buffer + b *mems.ABuffer encoder *json.Encoder sep string pretty bool @@ -49,22 +49,22 @@ type ( func newJsonBuilder (f *JSONFormatter) *jsonBuilder { sep := ":" - if f.UseSpace() && f.ShowPretty() { + if f.HasUseSpace() && f.HasShowPretty() { sep = ": " } return &jsonBuilder{ - f : f, - b : bfers.NewBuffer(), - pretty : f.ShowPretty(), - sep : sep, + f : f, + b : mems.NewABuffer(), + pretty : f.HasShowPretty(), + sep : sep, } } func (b *jsonBuilder) format (err error) { - cl := collr.NewErrorCollection(err) - cl.Collect(b.f.AddFields(),b.f.AddCauses(),b.f.AddTrace()) + cl := collects.NewErrorCollection(err) + cl.Collect(b.f.HasAddFields(),b.f.HasAddCauses(),b.f.HasAddTrace()) if cl.Invalid != nil { b.writeFormatError(cl.Invalid) @@ -75,7 +75,7 @@ func (b *jsonBuilder) format (err error) { } -func (b *jsonBuilder) write (coll *collr.ErrorCollection, cont bool, level int) { +func (b *jsonBuilder) write (coll *collects.ErrorCollection, cont bool, level int) { if b.invalid != nil { return } @@ -120,10 +120,10 @@ func (b *jsonBuilder) write (coll *collr.ErrorCollection, cont bool, level int) if b.pretty { b.b.WriteByte('\n') } - b.writeField(collr.FieldNameError,coll.ErrStr, indObj,true,false, false) + b.writeField(collects.FieldNameError,coll.ErrStr, indObj,true,false, false) - if b.f.AddTypes() { + if b.f.HasAddTypes() { types := coll.Types b.b.WriteByte(',') @@ -132,10 +132,10 @@ func (b *jsonBuilder) write (coll *collr.ErrorCollection, cont bool, level int) } if len(types) == 1 { - b.writeField(collr.FieldNameType, types[0].String(), indObj, true, false,false) + b.writeField(collects.FieldNameType, types[0].String(), indObj, true, false,false) } else { - b.writeOpen(collr.FieldNameTypes, indObj, '[', b.pretty) + b.writeOpen(collects.FieldNameTypes, indObj, '[', b.pretty) for i, t := range coll.TypesStr { if b.pretty { b.b.WriteString(ind2Obj) @@ -165,7 +165,7 @@ func (b *jsonBuilder) write (coll *collr.ErrorCollection, cont bool, level int) } coll.Fields.Sort() - b.writeOpen(collr.FieldNameFields, indObj, '{', b.pretty) + b.writeOpen(collects.FieldNameFields, indObj, '{', b.pretty) var n = 0 for _, h := range heads { @@ -201,10 +201,10 @@ func (b *jsonBuilder) write (coll *collr.ErrorCollection, cont bool, level int) } if len(causes) == 1 { - b.writeOpen(collr.FieldNameCause, indObj, 0, false) + b.writeOpen(collects.FieldNameCause, indObj, 0, false) b.write(&causes[0], true,level+1) } else if len(causes) > 1 { - b.writeOpen(collr.FieldNameCauses, indObj, '[', b.pretty) + b.writeOpen(collects.FieldNameCauses, indObj, '[', b.pretty) for i, ce := range causes { if i > 0 { b.b.WriteByte(',') @@ -229,7 +229,7 @@ func (b *jsonBuilder) write (coll *collr.ErrorCollection, cont bool, level int) if b.pretty { b.b.WriteByte('\n') } - b.writeFieldName(collr.FieldNameTrace,indObj) + b.writeFieldName(collects.FieldNameTrace,indObj) if b.encoder == nil { b.encoder = json.NewEncoder(b.b) @@ -296,61 +296,61 @@ func (b *jsonBuilder) writeField (name, value, indent string, quote, coma, nl bo } -func (b *jsonBuilder) writeFieldValue (fields collr.Fields, field *collr.FieldHead, level int) bool { +func (b *jsonBuilder) writeFieldValue (fields collects.Fields, field *collects.FieldHead, level int) bool { switch field.Kind { - case collr.FieldKindFloat: + case collects.FieldKindFloat: n := fields.GetFieldValueFloat(field) - if n == 0 && b.f.IgnoreDefaults() { + if n == 0 && b.f.HasIgnoreDefaults() { return false } - cjson.WriteFloat(b.b,n,64,b.f.UseQuote()) + cjson.WriteFloat(b.b,n,64,b.f.HasUseQuote()) return true - case collr.FieldKindInt: + case collects.FieldKindInt: n := fields.GetFieldValueInt(field) - if n == 0 && b.f.IgnoreDefaults() { + if n == 0 && b.f.HasIgnoreDefaults() { return false } - cjson.WriteInt(b.b,int64(n),b.f.UseQuote()) + cjson.WriteInt(b.b,int64(n),b.f.HasUseQuote()) return true - case collr.FieldKindString: + case collects.FieldKindString: s := fields.GetFieldValueString(field) - if len(s) == 0 && b.f.IgnoreDefaults() { + if len(s) == 0 && b.f.HasIgnoreDefaults() { return false } - cjson.WriteString(b.b,s,b.f.EscapeHTML()) + cjson.WriteString(b.b,s,b.f.HasEscapeHTML()) return true - case collr.FieldKindTime: + case collects.FieldKindTime: d := fields.GetFieldValueDate(field) - if d.IsZero() && b.f.IgnoreDefaults(){ + if d.IsZero() && b.f.HasIgnoreDefaults(){ return false } cjson.WriteDate(b.b,d,b.f.layout.TimeLayout,true) return true - case collr.FieldKindDate: + case collects.FieldKindDate: d := fields.GetFieldValueDate(field) - if d.IsZero() && b.f.IgnoreDefaults(){ + if d.IsZero() && b.f.HasIgnoreDefaults(){ return false } cjson.WriteDate(b.b,d,b.f.layout.DateLayout,true) return true - case collr.FieldKindBool: + case collects.FieldKindBool: t := fields.GetFieldValueBool(field) - if !t && b.f.IgnoreDefaults() { + if !t && b.f.HasIgnoreDefaults() { return false } - cjson.WriteBool(b.b,t,b.f.UseQuote()) + cjson.WriteBool(b.b,t,b.f.HasUseQuote()) return true default: a := fields.GetFieldValueAny(field) if a == nil { - if b.f.IgnoreDefaults() { + if b.f.HasIgnoreDefaults() { return false } b.b.WOQ(true,'"',cjson.G.NullValue) @@ -359,7 +359,7 @@ func (b *jsonBuilder) writeFieldValue (fields collr.Fields, field *collr.FieldHe if b.encoder == nil { b.encoder = json.NewEncoder(b.b) - b.encoder.SetEscapeHTML(b.f.EscapeHTML()) + b.encoder.SetEscapeHTML(b.f.HasEscapeHTML()) } if b.pretty { @@ -377,7 +377,7 @@ func (b *jsonBuilder) writeFieldValue (fields collr.Fields, field *collr.FieldHe b.b.Reset() b.b.WriteByte('{') b.writeFieldName("json-formatter-error","") - cjson.WriteString(b.b,err.Error(),b.f.EscapeHTML()) + cjson.WriteString(b.b,err.Error(),b.f.HasEscapeHTML()) b.b.WriteByte('}') } diff --git a/core/errs/fjson/json_formatter.go b/core/errs/fjson/json_formatter.go index 3c31286..cbdadc2 100644 --- a/core/errs/fjson/json_formatter.go +++ b/core/errs/fjson/json_formatter.go @@ -69,5 +69,7 @@ func WithLayout (config LayoutFnc) JSONFormatterFnc { func WithOptions (set, unset Option) JSONFormatterFnc { return func(f *JSONFormatter) { - f.Option |= set - f.Option &^= unset } } + f.Option = f.Option.Add(set) + f.Option = f.Option.Del(unset) + } +} diff --git a/core/errs/fjson/option.go b/core/errs/fjson/option.go index 70398f6..8f0b042 100644 --- a/core/errs/fjson/option.go +++ b/core/errs/fjson/option.go @@ -46,33 +46,41 @@ type ( Option uint16 ) -func (o Option) AddTypes () bool { +func (o Option) Add (opt Option) Option { + return o | opt +} + +func (o Option) Del (opt Option) Option { + return o &^ opt } + + +func (o Option) HasAddTypes() bool { return o&AddTypes != 0 } -func (o Option) AddFields () bool { +func (o Option) HasAddFields() bool { return o&AddFields != 0 } -func (o Option) AddCauses () bool { +func (o Option) HasAddCauses() bool { return o&AddCauses != 0 } -func (o Option) AddTrace () bool { +func (o Option) HasAddTrace() bool { return o&AddTrace != 0 } -func (o Option) ShowPretty () bool { +func (o Option) HasShowPretty() bool { return o&ShowPretty != 0 } -func (o Option) UseSpace () bool { +func (o Option) HasUseSpace() bool { return o&UseSpace != 0 } -func (o Option) UseQuote () bool { +func (o Option) HasUseQuote() bool { return o&UseQuote != 0 } -func (o Option) SortFields () bool { +func (o Option) HasSortFields() bool { return o&SortFields != 0 } -func (o Option) IgnoreDefaults() bool { +func (o Option) HasIgnoreDefaults() bool { return o&IgnoreDefaults != 0 } -func (o Option) EscapeHTML() bool { +func (o Option) HasEscapeHTML() bool { return o&EscapeHTML != 0 } diff --git a/core/errs/ftext/active.go b/core/errs/ftext/active.go index 513d978..8ae57f4 100644 --- a/core/errs/ftext/active.go +++ b/core/errs/ftext/active.go @@ -25,12 +25,12 @@ package ftext import ( "ansi" + "btypes/astrings" "errs/stack" "fmt" "reflect" "strings" "sync" - "tbase/astrings" ) diff --git a/core/errs/ftext/option.go b/core/errs/ftext/option.go index 2eaf3ec..77961ab 100644 --- a/core/errs/ftext/option.go +++ b/core/errs/ftext/option.go @@ -44,31 +44,36 @@ type ( Option uint16 ) +func (o Option) Add (opt Option) Option { + return o | opt +} + +func (o Option) Del (opt Option) Option { + return o &^ opt } func (o Option) SetDefaults () Option { - return optionsDefault -} + return optionsDefault } -func (o Option) AddTypes() bool { +func (o Option) HasAddTypes() bool { return o&AddTypes !=0 } -func (o Option) AddFields() bool { +func (o Option) HasAddFields() bool { return o&AddFields !=0 } -func (o Option) AddCauses() bool { +func (o Option) HasAddCauses() bool { return o&AddCauses !=0 } -func (o Option) AddTrace() bool { +func (o Option) HasAddTrace() bool { return o&AddTrace !=0 } -func (o Option) IgnoreEmpty() bool { +func (o Option) HasIgnoreEmpty() bool { return o&IgnoreEmpty !=0 } -func (o Option) ShowAnsi () bool { +func (o Option) HasShowAnsi() bool { return o&ShowAnsi !=0 } -func (o Option) UseIndent() bool { +func (o Option) HasUseIndent() bool { return o&UseIndent !=0 } \ No newline at end of file diff --git a/core/errs/ftext/text_builder.go b/core/errs/ftext/text_builder.go index 97d8b3b..6c39d26 100644 --- a/core/errs/ftext/text_builder.go +++ b/core/errs/ftext/text_builder.go @@ -25,8 +25,8 @@ package ftext import ( "ansi" - "bins/bfers" - "errs/collr" + "bins/mems" + "errs/collects" "fmt" "strings" ) @@ -35,10 +35,10 @@ type ( TextBuilder struct { f *TextFormatter - b *bfers.Buffer + b *mems.ABuffer useAux bool - auxB *bfers.Buffer + auxB *mems.ABuffer level int ansiC ansi.Code @@ -53,12 +53,12 @@ type ( func newTextBuilder(formatter *TextFormatter) *TextBuilder { b := &TextBuilder{ f : formatter, - b : bfers.NewBuffer(), - useAux: len(formatter.valueTrans) > 0, - ansiC : formatter.layout.AnsiC, + b : mems.NewABuffer(), + useAux: len(formatter.valueTrans) > 0, + ansiC : formatter.layout.AnsiC, } if b.useAux { - b.auxB = bfers.NewBuffer() + b.auxB = mems.NewABuffer() } else { b.auxB = b.b } @@ -73,7 +73,7 @@ func (b *TextBuilder) AddText (text string) { b.b.WriteString(text) } func (b *TextBuilder) AddTextAnsi (ansiC ansi.Code, text string) { - if b.f.ShowAnsi() { + if b.f.HasShowAnsi() { if ansiC == 0 { ansiC = b.ansiC } @@ -95,15 +95,15 @@ func (b *TextBuilder) SetAnsi(ansiC ansi.Code) { func (b *TextBuilder) format (err error) { - c := collr.NewErrorCollection(err) - if c.Collect(b.f.AddFields(), b.f.AddCauses(), b.f.AddTrace()); c.Invalid != nil { + c := collects.NewErrorCollection(err) + if c.Collect(b.f.HasAddFields(), b.f.HasAddCauses(), b.f.HasAddTrace()); c.Invalid != nil { //b.writeFormatError(cl.Invalid) return } b.write(c, 0) } -func (b *TextBuilder) write (c *collr.ErrorCollection, level int) { +func (b *TextBuilder) write (c *collects.ErrorCollection, level int) { if b.invalid != nil { return } @@ -131,17 +131,17 @@ func (b *TextBuilder) write (c *collr.ErrorCollection, level int) { }(b,&d, c.Err) f.sections.Head.begin(b) - b.writeFieldNameValue(collr.FieldNameError, c.ErrStr, ind) - if f.AddTypes() { + b.writeFieldNameValue(collects.FieldNameError, c.ErrStr, ind) + if f.HasAddTypes() { if len(c.TypesStr) == 1 { - b.writeFieldNameValue(collr.FieldNameType, c.TypesStr[0], ind) + b.writeFieldNameValue(collects.FieldNameType, c.TypesStr[0], ind) } else { - b.writeFieldNameValue(collr.FieldNameTypes, strings.Join(c.TypesStr, ","), ind) + b.writeFieldNameValue(collects.FieldNameTypes, strings.Join(c.TypesStr, ","), ind) } } f.sections.Head.end(b) - if f.AddFields() && c.Fields.Len() > 0 { + if f.HasAddFields() && c.Fields.Len() > 0 { f.sections.Fields.begin(b) heads := c.Fields.GetHeads() for _,fl := range heads { @@ -217,7 +217,7 @@ func (b *TextBuilder) writeFieldEnd () { func (b *TextBuilder) writeFieldNameValue(name string, value string, indent string) { p:= b.b.Len() b.writeFieldBegin(name,indent) - if b.f.IgnoreEmpty() && len(value) == 0 { + if b.f.HasIgnoreEmpty() && len(value) == 0 { b.b.Truncate(p) return } @@ -226,7 +226,7 @@ func (b *TextBuilder) writeFieldNameValue(name string, value string, indent stri } -func (b *TextBuilder) writeField (fields collr.Fields, field *collr.FieldHead, indent string) { +func (b *TextBuilder) writeField (fields collects.Fields, field *collects.FieldHead, indent string) { p := b.b.Len() b.writeFieldBegin(field.Name,indent) if !b.writeFieldValue(fields,field) { @@ -237,41 +237,41 @@ func (b *TextBuilder) writeField (fields collr.Fields, field *collr.FieldHead, i } -func (b *TextBuilder) writeFieldValue (fields collr.Fields, field *collr.FieldHead) bool { +func (b *TextBuilder) writeFieldValue (fields collects.Fields, field *collects.FieldHead) bool { switch field.Kind { - case collr.FieldKindFloat: + case collects.FieldKindFloat: b.auxB.WriteFloatStr(fields.GetFieldValueFloat(field),'f',-1) - case collr.FieldKindInt: + case collects.FieldKindInt: b.auxB.WriteIntStr(int64(fields.GetFieldValueInt(field)),10) - case collr.FieldKindString: + case collects.FieldKindString: s := fields.GetFieldValueString(field) - if b.f.IgnoreEmpty() && len(s) == 0 { + if b.f.HasIgnoreEmpty() && len(s) == 0 { return false } b.auxB.WriteString(fields.GetFieldValueString(field)) - case collr.FieldKindTime: + case collects.FieldKindTime: b.auxB.WriteDateStr(fields.GetFieldValueDate(field), b.f.layout.TimeLayout) - case collr.FieldKindDate: + case collects.FieldKindDate: b.auxB.WriteDateStr(fields.GetFieldValueDate(field), b.f.layout.DateLayout) - case collr.FieldKindBool: + case collects.FieldKindBool: b.auxB.WriteBoolStr(fields.GetFieldValueBool(field)) default: a := fields.GetFieldValueAny(field) if a == nil { - if b.f.IgnoreEmpty() { + if b.f.HasIgnoreEmpty() { return false } b.auxB.WOQ(false,'"', g.nullValue) } else { s := fmt.Sprintf("%#v",a) - if b.f.IgnoreEmpty() && len(s) == 0 { + if b.f.HasIgnoreEmpty() && len(s) == 0 { return false } b.auxB.WriteString(s) diff --git a/core/errs/ftext/text_formatter.go b/core/errs/ftext/text_formatter.go index d6e03d6..626a7c7 100644 --- a/core/errs/ftext/text_formatter.go +++ b/core/errs/ftext/text_formatter.go @@ -24,8 +24,8 @@ package ftext import ( + "btypes/astrings" "errs/stack" - "tbase/astrings" ) type ( @@ -102,8 +102,8 @@ func WithErrorFallbacks (format, cause, trace ErrorFallbackFnc) TextFormatterFnc func WithOptions (set, unset Option) TextFormatterFnc { return func(f *TextFormatter) { - f.Option |= set - f.Option &^= unset } } + f.Option = f.Option.Add(set) + f.Option = f.Option.Del(unset) } } func WithNameTransformers(transformer ...astrings.Transformer) TextFormatterFnc { diff --git a/core/btes/bfers/buffer.go b/core/mems/abuffer.go similarity index 78% rename from core/btes/bfers/buffer.go rename to core/mems/abuffer.go index fcd6baf..84e74ad 100644 --- a/core/btes/bfers/buffer.go +++ b/core/mems/abuffer.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package bfers +package mems import ( "bins/chars" @@ -31,17 +31,13 @@ import ( "unicode/utf8" ) -const ( - maxInt = int(^uint(0) >> 1) - MinRead = 512 -) type ( - Buffer struct { + ABuffer struct { data []byte off int ini [64]byte @@ -50,27 +46,27 @@ type ( ) -func NewBuffer() *Buffer { - return &Buffer{} } +func NewABuffer() *ABuffer { + return &ABuffer{} } -func (b *Buffer) Len() int { +func (b *ABuffer) Len() int { return len(b.data) - b.off } -func (b *Buffer) Cap() int { +func (b *ABuffer) Cap() int { return cap(b.data) } -func (b *Buffer) isEmpty() bool { +func (b *ABuffer) isEmpty() bool { return len(b.data) <= b.off } -func (b *Buffer) Bytes() []byte { +func (b *ABuffer) Bytes() []byte { return b.data[b.off:] } -func (b *Buffer) String() string { +func (b *ABuffer) String() string { if b == nil { return "" } @@ -78,14 +74,14 @@ func (b *Buffer) String() string { } -func (b *Buffer) Reset() { +func (b *ABuffer) Reset() { b.data = b.data[:0] b.off = 0 b.lastOp = opInvalid } -func (b *Buffer) Truncate(size int) { +func (b *ABuffer) Truncate(size int) { if size == 0 { b.Reset() return @@ -98,7 +94,7 @@ func (b *Buffer) Truncate(size int) { } -func (b *Buffer) Read(data []byte) (count int, err error) { +func (b *ABuffer) Read(data []byte) (count int, err error) { b.lastOp = opInvalid if b.isEmpty() { b.Reset() @@ -116,7 +112,7 @@ func (b *Buffer) Read(data []byte) (count int, err error) { } -func (b *Buffer) ReadFrom(reader io.Reader) (count int64, err error) { +func (b *ABuffer) ReadFrom(reader io.Reader) (count int64, err error) { b.lastOp = opInvalid for { i := b.tryGrowByStrategy(MinRead) @@ -137,7 +133,7 @@ func (b *Buffer) ReadFrom(reader io.Reader) (count int64, err error) { } -func (b *Buffer) ReadByte() (byte, error) { +func (b *ABuffer) ReadByte() (byte, error) { if b.isEmpty() { b.Reset() return 0, io.EOF @@ -149,20 +145,20 @@ func (b *Buffer) ReadByte() (byte, error) { } -func (b *Buffer) ReadBytes(delimiter byte) (result []byte, er error) { +func (b *ABuffer) 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) { +func (b *ABuffer) 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) { +func (b *ABuffer) ReadRune() (run rune, size int, err error) { if b.isEmpty() { b.Reset() return 0, 0, io.EOF @@ -180,7 +176,7 @@ func (b *Buffer) ReadRune() (run rune, size int, err error) { } -func (b *Buffer) readSlice(delimiter byte) (ln []byte, er error) { +func (b *ABuffer) readSlice(delimiter byte) (ln []byte, er error) { i := bytes.IndexByte(b.data[b.off:], delimiter) end := b.off + i + 1 if i < 0 { @@ -194,7 +190,7 @@ func (b *Buffer) readSlice(delimiter byte) (ln []byte, er error) { } -func (b *Buffer) UnreadRune() error { +func (b *ABuffer) UnreadRune() error { if b.lastOp <= opInvalid { return G.ErrUnreadInvalid } @@ -206,7 +202,7 @@ func (b *Buffer) UnreadRune() error { } -func (b *Buffer) UnreadByte() error { +func (b *ABuffer) UnreadByte() error { if b.lastOp == opInvalid { return G.ErrUnreadInvalid } @@ -218,7 +214,7 @@ func (b *Buffer) UnreadByte() error { } -func (b *Buffer) AppendWith(appender Appender) { +func (b *ABuffer) AppendWith(appender Appender) { b.lastOp = opInvalid if appender != nil { b.data = appender.Append(b.data) @@ -226,20 +222,20 @@ func (b *Buffer) AppendWith(appender Appender) { } -func (b *Buffer) Write(value []byte) (int, error) { +func (b *ABuffer) Write(value []byte) (int, error) { b.lastOp = opInvalid return copy(b.data[b.tryGrow(len(value)):], value), nil } -func (b *Buffer) W (value []byte) { +func (b *ABuffer) W (value []byte) { b.lastOp = opInvalid copy(b.data[b.tryGrow(len(value)):], value) } // WOQ With Optional Quoted -func (b *Buffer) WOQ (add bool, quote byte, value []byte) { +func (b *ABuffer) WOQ (add bool, quote byte, value []byte) { b.lastOp = opInvalid if !add { copy(b.data[b.tryGrow(len(value)):], value) @@ -252,7 +248,7 @@ func (b *Buffer) WOQ (add bool, quote byte, value []byte) { } -func (b *Buffer) WriteHTML(source []byte) { +func (b *ABuffer) WriteHTML(source []byte) { st := 0 for i,c := range source { if c == '<' || c == '>' || c == '&' { @@ -279,13 +275,13 @@ func (b *Buffer) WriteHTML(source []byte) { } -func (b *Buffer) WriteByte(value byte) { +func (b *ABuffer) WriteByte(value byte) { b.lastOp = opInvalid b.data[b.tryGrow(1)] = value } -func (b *Buffer) Write2Byte(valueA, valueB byte) { +func (b *ABuffer) Write2Byte(valueA, valueB byte) { b.lastOp = opInvalid p := b.tryGrow(2) b.data[p] = valueA @@ -293,15 +289,15 @@ func (b *Buffer) Write2Byte(valueA, valueB byte) { } -func (b *Buffer) WriteString(value string) { +func (b *ABuffer) WriteString(value string) { b.W([]byte(value)) } -func (b *Buffer) WriteTo(writer io.Writer) (int64, error) { +func (b *ABuffer) WriteTo(writer io.Writer) (int64, error) { return b.writeTo(writer, false) } -func (b *Buffer) FlushTo(writer io.Writer) (int64, error) { +func (b *ABuffer) FlushTo(writer io.Writer) (int64, error) { return b.writeTo(writer, true) } @@ -310,7 +306,7 @@ func (b *Buffer) FlushTo(writer io.Writer) (int64, error) { -func (b *Buffer) writeTo(writer io.Writer, reset bool) (count int64, err error) { +func (b *ABuffer) writeTo(writer io.Writer, reset bool) (count int64, err error) { if reset { b.lastOp = opInvalid } @@ -335,7 +331,7 @@ func (b *Buffer) writeTo(writer io.Writer, reset bool) (count int64, err error) } -func (b *Buffer) tryGrow(size int) int { +func (b *ABuffer) tryGrow(size int) int { m := len(b.data) if size <= cap(b.data)-m { b.data = b.data[:m+size] @@ -368,7 +364,7 @@ func (b *Buffer) tryGrow(size int) int { } -func (b *Buffer) tryGrowByResize(size int) (int, bool) { +func (b *ABuffer) tryGrowByResize(size int) (int, bool) { if l := len(b.data); size <= cap(b.data)-l { b.data = b.data[:l+size] return l, true @@ -377,7 +373,7 @@ func (b *Buffer) tryGrowByResize(size int) (int, bool) { } -func (b *Buffer) tryGrowByStrategy(size int) int { +func (b *ABuffer) tryGrowByStrategy(size int) int { m := len(b.data) if m == 0 && b.off != 0 { b.Reset() diff --git a/core/btes/bfers/writer_binary.go b/core/mems/abuffer_w_binary.go similarity index 71% rename from core/btes/bfers/writer_binary.go rename to core/mems/abuffer_w_binary.go index 9ca7731..8a69566 100644 --- a/core/btes/bfers/writer_binary.go +++ b/core/mems/abuffer_w_binary.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package bfers +package mems import ( "encoding/binary" @@ -31,7 +31,7 @@ import ( -func (b *Buffer) WriteBool(value bool) { +func (b *ABuffer) WriteBool(value bool) { if value { b.WriteByte(1) return @@ -40,11 +40,11 @@ func (b *Buffer) WriteBool(value bool) { } -func (b *Buffer) WriteRune(value rune, byteOrder binary.ByteOrder) { +func (b *ABuffer) WriteRune(value rune, byteOrder binary.ByteOrder) { b.WriteUint32(uint32(value), byteOrder) } -func (b *Buffer) WriteUint16(value uint16, byteOrder binary.ByteOrder) { +func (b *ABuffer) WriteUint16(value uint16, byteOrder binary.ByteOrder) { b.lastOp = opInvalid if byteOrder == nil { byteOrder = binary.LittleEndian @@ -53,7 +53,7 @@ func (b *Buffer) WriteUint16(value uint16, byteOrder binary.ByteOrder) { } -func (b *Buffer) WriteUint32(value uint32, byteOrder binary.ByteOrder) { +func (b *ABuffer) WriteUint32(value uint32, byteOrder binary.ByteOrder) { b.lastOp = opInvalid if byteOrder == nil { byteOrder = binary.LittleEndian @@ -62,7 +62,7 @@ func (b *Buffer) WriteUint32(value uint32, byteOrder binary.ByteOrder) { } -func (b *Buffer) WriteUint64(value uint64, byteOrder binary.ByteOrder) { +func (b *ABuffer) WriteUint64(value uint64, byteOrder binary.ByteOrder) { if byteOrder == nil { byteOrder = binary.LittleEndian } @@ -70,27 +70,27 @@ func (b *Buffer) WriteUint64(value uint64, byteOrder binary.ByteOrder) { } -func (b *Buffer) WriteInt16(value int16, byteOrder binary.ByteOrder) { +func (b *ABuffer) WriteInt16(value int16, byteOrder binary.ByteOrder) { b.WriteUint16(uint16(value), byteOrder) } -func (b *Buffer) WriteInt32(value int32, byteOrder binary.ByteOrder) { +func (b *ABuffer) WriteInt32(value int32, byteOrder binary.ByteOrder) { b.WriteUint32(uint32(value), byteOrder) } -func (b *Buffer) WriteInt64(value int64, byteOrder binary.ByteOrder) { +func (b *ABuffer) WriteInt64(value int64, byteOrder binary.ByteOrder) { b.WriteUint64(uint64(value), byteOrder) } -func (b *Buffer) WriteFloat32(value float32, byteOrder binary.ByteOrder) { +func (b *ABuffer) WriteFloat32(value float32, byteOrder binary.ByteOrder) { b.WriteUint32(math.Float32bits(value), byteOrder) } -func (b *Buffer) WriteFloat64(value float64, byteOrder binary.ByteOrder) { +func (b *ABuffer) WriteFloat64(value float64, byteOrder binary.ByteOrder) { b.WriteUint64(math.Float64bits(value), byteOrder) } -func (b *Buffer) WriteComplex64(value complex64, byteOrder binary.ByteOrder) { +func (b *ABuffer) WriteComplex64(value complex64, byteOrder binary.ByteOrder) { b.lastOp = opInvalid if byteOrder == nil { byteOrder = binary.LittleEndian @@ -101,7 +101,7 @@ func (b *Buffer) WriteComplex64(value complex64, byteOrder binary.ByteOrder) { } -func (b *Buffer) WriteComplex128(value complex128, byteOrder binary.ByteOrder) { +func (b *ABuffer) WriteComplex128(value complex128, byteOrder binary.ByteOrder) { b.lastOp = opInvalid if byteOrder == nil { byteOrder = binary.LittleEndian @@ -112,7 +112,7 @@ func (b *Buffer) WriteComplex128(value complex128, byteOrder binary.ByteOrder) { } -func (b *Buffer) WriteTime(value time.Time) error { +func (b *ABuffer) WriteTime(value time.Time) error { b.lastOp = opInvalid d, e := value.MarshalBinary() if e != nil { @@ -123,5 +123,5 @@ func (b *Buffer) WriteTime(value time.Time) error { } -func (b *Buffer) WriteDuration(val time.Duration) { +func (b *ABuffer) WriteDuration(val time.Duration) { b.WriteInt64(int64(val), binary.LittleEndian) } diff --git a/core/btes/bfers/writer_string.go b/core/mems/abuffer_w_string.go similarity index 81% rename from core/btes/bfers/writer_string.go rename to core/mems/abuffer_w_string.go index 8004372..c31ece2 100644 --- a/core/btes/bfers/writer_string.go +++ b/core/mems/abuffer_w_string.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package bfers +package mems import ( "strconv" @@ -29,12 +29,12 @@ import ( "unicode/utf8" ) -func (b *Buffer) WriteBoolStr(value bool) { +func (b *ABuffer) WriteBoolStr(value bool) { b.lastOp = opInvalid b.data = strconv.AppendBool(b.data, value) } -func (b *Buffer) WriteRuneStr(value rune) int { +func (b *ABuffer) WriteRuneStr(value rune) int { if value < utf8.RuneSelf { b.WriteByte(byte(value)) return 1 @@ -46,7 +46,7 @@ func (b *Buffer) WriteRuneStr(value rune) int { return cn } -func (b *Buffer) WriteUIntStr(value uint64, base int) { +func (b *ABuffer) WriteUIntStr(value uint64, base int) { b.lastOp = opInvalid if base == 0 { base = 10 @@ -54,7 +54,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) { +func (b *ABuffer) WriteIntStr(value int64, base int) { b.lastOp = opInvalid if base == 0 { base = 10 @@ -62,7 +62,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) { +func (b *ABuffer) WriteFloatStr(value float64, formatter byte, precision int) { b.lastOp = opInvalid if formatter == 0 { formatter = 'f' @@ -70,7 +70,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) { +func (b *ABuffer) WriteComplexStr(value complex128, formatter byte, precision int) { b.lastOp = opInvalid if formatter == 0 { formatter = 'f' @@ -78,7 +78,7 @@ func (b *Buffer) WriteComplexStr(value complex128, formatter byte, precision int b.data = append(b.data, strconv.FormatComplex(value, formatter, precision, 128)...) } -func (b *Buffer) WriteDateStr (value time.Time, layout string) { +func (b *ABuffer) WriteDateStr (value time.Time, layout string) { b.lastOp = opInvalid if layout == "" { layout = time.RFC822 diff --git a/core/btes/bfers/active.go b/core/mems/active.go similarity index 69% rename from core/btes/bfers/active.go rename to core/mems/active.go index fee538c..3174d39 100644 --- a/core/btes/bfers/active.go +++ b/core/mems/active.go @@ -21,7 +21,8 @@ // limitations under the License. // ------------------------------------------------------------------------ -package bfers +package mems + const ( @@ -30,27 +31,32 @@ const ( minSize = 1 << minBitSize maxSize = 1 << (minBitSize + poolSteps - 1) + maxInt = int(^uint(0) >> 1) + MinRead = 512 + poolSteps = 20 poolThreshold = 42000 poolPercentile = 0.95 + + ) var ( G = struct { - ErrOutOfRange ErrBuffer - ErrWriteCount ErrBuffer - ErrTooShort ErrBuffer - ErrTooLarge ErrBuffer - ErrNegativeRead ErrBuffer - ErrUnreadInvalid ErrBuffer + ErrOutOfRange ErrMems + ErrWriteCount ErrMems + ErrTooShort ErrMems + ErrTooLarge ErrMems + ErrNegativeRead ErrMems + ErrUnreadInvalid ErrMems }{ - ErrOutOfRange: ErrBuffer{"out-of-range"}, - ErrWriteCount: ErrBuffer{"write-count"}, - ErrTooShort: ErrBuffer{"too-short"}, - ErrTooLarge: ErrBuffer{"too-large"}, - ErrNegativeRead: ErrBuffer{"negative-read"}, - ErrUnreadInvalid: ErrBuffer{"unread-invalid"}, + ErrOutOfRange: ErrMems("out-of-range"), + ErrWriteCount: ErrMems("write-count"), + ErrTooShort: ErrMems("too-short"), + ErrTooLarge: ErrMems("too-large"), + ErrNegativeRead: ErrMems("negative-read"), + ErrUnreadInvalid: ErrMems("unread-invalid"), } g = struct { @@ -62,10 +68,10 @@ var ( -func AcquireBuffer () *Buffer { +func AcquireABuffer() *ABuffer { return g.bufferPool.Get() } -func ReleaseBuffer (buffer *Buffer) { +func ReleaseABuffer(buffer *ABuffer) { g.bufferPool.Put(buffer) } diff --git a/core/btes/bfers/appender.go b/core/mems/appender.go similarity index 98% rename from core/btes/bfers/appender.go rename to core/mems/appender.go index 6707391..4bbd4a8 100644 --- a/core/btes/bfers/appender.go +++ b/core/mems/appender.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package bfers +package mems type ( diff --git a/core/btes/bfers/err_buffer.go b/core/mems/err_mems.go similarity index 70% rename from core/btes/bfers/err_buffer.go rename to core/mems/err_mems.go index 32a0458..c4d44dd 100644 --- a/core/btes/bfers/err_buffer.go +++ b/core/mems/err_mems.go @@ -21,13 +21,28 @@ // limitations under the License. // ------------------------------------------------------------------------ -package bfers +package mems + +import "errs/collects" type ( - ErrBuffer struct { string } + // ErrMems no puede heredar directamente de Errs.Code + // ya que es utilizada por fjson y ftext lo que crea + // un ciclo de importaciones + // + ErrMems string ) -func (e ErrBuffer) Error() string { - return e.string -} \ No newline at end of file + +func (e ErrMems) Error() string { + return string(e) } + + +func (e ErrMems) Code () string { + return string(e) } + + + +func (e ErrMems) Collect (c collects.Collector) { + c.AddFieldString(collects.FieldNameCode,string(e)) } \ No newline at end of file diff --git a/core/btes/bfers/operation.go b/core/mems/operation.go similarity index 98% rename from core/btes/bfers/operation.go rename to core/mems/operation.go index c189ae8..e4f38a5 100644 --- a/core/btes/bfers/operation.go +++ b/core/mems/operation.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package bfers +package mems const ( diff --git a/core/btes/bfers/pool.go b/core/mems/pool.go similarity index 96% rename from core/btes/bfers/pool.go rename to core/mems/pool.go index 071c3c3..067cf32 100644 --- a/core/btes/bfers/pool.go +++ b/core/mems/pool.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package bfers +package mems import ( "sort" @@ -73,18 +73,18 @@ func (p *Pool) CallsThreshold() uint64 { return atomic.LoadUint64(&p.threshold) } -func (p *Pool) Get() *Buffer { +func (p *Pool) Get() *ABuffer { b := p.inner.Get() p.AddAcquired() if b == nil { p.AddCreated() - return NewBuffer() + return NewABuffer() } - return b.(*Buffer) + return b.(*ABuffer) } -func (p *Pool) Put(buffer *Buffer) { +func (p *Pool) Put(buffer *ABuffer) { if buffer == nil { return } diff --git a/core/pkrs/pjson/list_pack_builder.go b/core/pkrs/pjson/list_pack_builder.go deleted file mode 100644 index 66d9991..0000000 --- a/core/pkrs/pjson/list_pack_builder.go +++ /dev/null @@ -1,80 +0,0 @@ -// ------------------------------------------------------------------------ -// Project atila -// Active Thing (activething.com) git.activething.com/go -// -// File name builder_list.go -// Created by DEV -// Modified 06/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 pjson - -import ( - "packs" - "time" -) - -func (p *JSONPacker) ItemAny (value any, flags pkrs.Flags) { p.addItem(func(){ p.PackAny(value,flags) }) } - - -func (p *JSONPacker) ItemRaw (value []byte, flags pkrs.Flags) { p.addItem(func() { p.PackRaw(value,flags) }) } - -func (p *JSONPacker) ItemBinary (value []byte, flags pkrs.Flags) { p.addItem(func (){ p.PackBinary(value,flags) }) } - -func (p *JSONPacker) ItemString (value string, flags pkrs.Flags) { p.addItem(func (){ p.PackString(value,flags) }) } - - -func (p *JSONPacker) ItemBool (value bool, flags pkrs.Flags) { p.addItem(func (){ p.PackBool(value,flags) }) } - -func (p *JSONPacker) ItemInt8 (value int8 , flags pkrs.Flags) { p.addItem(func (){ packInt(p.state,int64(value),flags) }) } -func (p *JSONPacker) ItemInt16 (value int16, flags pkrs.Flags) { p.addItem(func (){ packInt(p.state,int64(value),flags) }) } -func (p *JSONPacker) ItemInt32 (value int32, flags pkrs.Flags) { p.addItem(func (){ packInt(p.state,int64(value),flags) }) } -func (p *JSONPacker) ItemInt64 (value int64, flags pkrs.Flags) { p.addItem(func (){ packInt(p.state,value,flags) }) } - -func (p *JSONPacker) ItemUInt8 (value uint8 , flags pkrs.Flags){ p.addItem(func (){ packUInt(p.state,uint64(value),flags) }) } -func (p *JSONPacker) ItemUInt16 (value uint16, flags pkrs.Flags){ p.addItem(func (){ packUInt(p.state,uint64(value),flags) }) } -func (p *JSONPacker) ItemUInt32 (value uint32, flags pkrs.Flags){ p.addItem(func (){ packUInt(p.state,uint64(value),flags) }) } -func (p *JSONPacker) ItemUInt64 (value uint64, flags pkrs.Flags){ p.addItem(func (){ packUInt(p.state,uint64(value),flags) }) } - -func (p *JSONPacker) ItemFloat32 (value float32, flags pkrs.Flags){ p.addItem(func (){ packFloatString(p.state,float64(value),flags,32)})} -func (p *JSONPacker) ItemFloat64 (value float64, flags pkrs.Flags){ p.addItem(func (){ packFloatString(p.state,value,flags,64) })} - -func (p *JSONPacker) ItemDate (value time.Time, flags pkrs.Flags) { p.addItem(func(){ packDate(p.state,value,flags); p.state.Inc() })} - - -func (p *JSONPacker) ItemList (builder func(pkrs.ListPackBuilder, pkrs.Flags), flags pkrs.Flags) { - p.addItem(func(){ p.PackList(builder,flags) }) } - -func (p *JSONPacker) ItemMap (builder func(pkrs.MapPackBuilder, pkrs.Flags), flags pkrs.Flags) { - p.addItem(func(){ p.PackMap(builder,flags) }) } - -func (p *JSONPacker) ItemObject(builder func(pkrs.ObjectPackBuilder, pkrs.Flags), flags pkrs.Flags) { - p.addItem(func(){ p.PackObject(builder,flags) }) } - - - -func (p *JSONPacker) addItem (caller func()) { - if p.state.Count() > 0 { - p.state.WriteByte(',') - } - caller() - if p.state != nil { - p.state.Inc() - } -} - - diff --git a/core/syncs/tasks/completion_state.go b/core/syncs/ctasks/active.go similarity index 53% rename from core/syncs/tasks/completion_state.go rename to core/syncs/ctasks/active.go index 8b223a5..7123c7a 100644 --- a/core/syncs/tasks/completion_state.go +++ b/core/syncs/ctasks/active.go @@ -2,7 +2,7 @@ // Project atila // Active Thing (activething.com) git.activething.com/go // -// File name completion_state.go +// File name gogo.go // Created by DEV // Modified 20/02/2024 // @@ -21,38 +21,43 @@ // limitations under the License. // ------------------------------------------------------------------------ -package tasks +package ctasks +import "errs" +const ( -const ( - - CompletionStateCreated CompletionState = iota - CompletionStateStarted - CompletionStateCompleted - CompletionStateCanceled - CompletionStateFaulted + CompletionFromChild int = iota * -1 + CompletionFromSelf + CompletionFromParent + CompletionFromContext + CompletionFromTimer + CompletionFromRequest ) -type ( +var ( - CompletionState uint32 + G = struct { -) + ErrInvalidCompletion ErrCTasks + ErrInvalidState ErrCTasks + ErrCancelByParent ErrCTasks + ErrCancelByRequest ErrCTasks + ErrCancelByContext ErrCTasks + ErrCancelByTimer ErrCTasks + }{ + ErrInvalidCompletion: ErrCTasks{errs.ErrCode("invalid-completion")}, + ErrInvalidState : ErrCTasks{errs.ErrCode("invalid-state")}, + ErrCancelByParent : ErrCTasks{errs.ErrCode("cancel-by-parent")}, + ErrCancelByRequest : ErrCTasks{errs.ErrCode("cancel-by-request")}, + ErrCancelByContext : ErrCTasks{errs.ErrCode("cancel-by-context")}, + ErrCancelByTimer : ErrCTasks{errs.ErrCode("cancel-by-timer")}, -func (s CompletionState) String () string { - switch s { - case CompletionStateCreated : return "created" - case CompletionStateStarted : return "started" - case CompletionStateCompleted: return "completed" - case CompletionStateCanceled : return "canceled" - case CompletionStateFaulted : return "faulted" - default: return "??" - } -} + } +) diff --git a/core/syncs/tasks/completer.go b/core/syncs/ctasks/completer.go similarity index 84% rename from core/syncs/tasks/completer.go rename to core/syncs/ctasks/completer.go index 873c9c0..a4f6320 100644 --- a/core/syncs/tasks/completer.go +++ b/core/syncs/ctasks/completer.go @@ -21,22 +21,22 @@ // limitations under the License. // ------------------------------------------------------------------------ -package tasks +package ctasks type ( Completer interface { - Complete (context CompletionContext, cid int) + Complete (context Context, cid int) } - CompleteFnc func (context CompletionContext, cid int) + CompleteFnc func (context Context, cid int) ) -func (f CompleteFnc) Complete (context CompletionContext, cid int) { +func (f CompleteFnc) Complete (context Context, cid int) { f(context,cid) } diff --git a/core/syncs/tasks/completion.go b/core/syncs/ctasks/completion.go similarity index 54% rename from core/syncs/tasks/completion.go rename to core/syncs/ctasks/completion.go index 42a1639..e28418a 100644 --- a/core/syncs/tasks/completion.go +++ b/core/syncs/ctasks/completion.go @@ -21,14 +21,16 @@ // limitations under the License. // ------------------------------------------------------------------------ -package tasks +package ctasks import ( "context" "opts" "sync" "sync/atomic" - "timers" + "syncs/works" + "time" + cronus "timers" ) type ( @@ -38,15 +40,15 @@ type ( mux sync.RWMutex wgr sync.WaitGroup - parent CompletionContext - expiration *timers.Expiration + parent Context + expiration *cronus.Expiration - mode CompletionMode - state uint32 + mode Mode + state uint32 pending uint32 - cid int - result CompletionResult + cid int + result Result dispatchFn dispatchFnc cancelFn func() @@ -54,6 +56,7 @@ type ( completers []Completer } + CompletionFnc func (c *Completion) error dispatchFnc func (*Completion, Completer, int) error @@ -61,38 +64,42 @@ type ( ) -func NewCompletion (options ...opts.GOptionErrFnc[Completion]) (*Completion,error) { - c,e := opts.GApplyAndCheck[Completion](&Completion { - mode : CompletionModeAll, +func NewCompletion (options ...CompletionFnc) (*Completion,error) { + + c := &Completion { + mode : ModeAll, cid : CompletionFromSelf, dispatchFn: dispatcher, - },options...) - if e != nil { - return nil,e + } + for _,o := range options { + if er := o(c); er != nil { + return nil,er + } } if c.expiration == nil { - c.expiration = timers.NewExpiration(0,nil) + c.expiration = cronus.NewExpiration(0,nil) } return c,nil } -func (c *Completion) Mode () CompletionMode { +func (c *Completion) Mode () Mode { return c.mode } -func (c *Completion) State () CompletionState { - return CompletionState(atomic.LoadUint32(&c.state)) } +func (c *Completion) State () State { + return State(atomic.LoadUint32(&c.state)) } func (c *Completion) Pending() int { return int(atomic.LoadUint32(&c.pending)) } func (c *Completion) IsCompleted () bool { - return c.State() > CompletionStateStarted } + return c.State() > StateStarted +} -func (c *Completion) Chrono () timers.Chronometer { +func (c *Completion) Chrono () cronus.Chronometer { return c.expiration.Chono() } -func (c *Completion) Result () CompletionResult { +func (c *Completion) Result () Result { c.wgr.Wait() return c.result } @@ -103,7 +110,7 @@ func (c *Completion) Wait () { func (c *Completion) AddCompleter (cms ... Completer) error { c.mux.Lock() - if c.State() != CompletionStateCreated { + if c.State() != StateCreated { c.mux.Unlock() return G.ErrInvalidState } @@ -116,22 +123,22 @@ func (c *Completion) AddCompleter (cms ... Completer) error { func (c *Completion) Cancel () { - c.notify(CompletionFromRequest,CompletionStateCanceled,nil,G.ErrCancelByRequest) } + c.notify(CompletionFromRequest, StateCanceled,nil,G.ErrCancelByRequest) } func (c *Completion) Start (ctx context.Context) error { return c.complete(ctx,nil,CompletionFromSelf) } -func (c *Completion) Complete (cmp CompletionContext, cid int) { +func (c *Completion) Complete (cmp Context, cid int) { _ = c.complete(nil,cmp,cid) } -func (c *Completion) complete (ctx context.Context, cctx CompletionContext, cid int) error { +func (c *Completion) complete (ctx context.Context, cctx Context, cid int) error { c.mux.Lock() - if c.State() != CompletionStateCreated { + if c.State() != StateCreated { c.mux.Unlock() return G.ErrInvalidState } @@ -140,7 +147,7 @@ func (c *Completion) complete (ctx context.Context, cctx CompletionContext, cid // en tiempo de la completion en caso de que exista, o bien de la // completion padre o bien del contexto. // - var ex timers.Expirer + var ex cronus.Expirer if cctx != nil { c.parent = cctx @@ -148,7 +155,7 @@ func (c *Completion) complete (ctx context.Context, cctx CompletionContext, cid c.cid = cid if c.parent.IsCompleted() { c.mux.Unlock() - c.notify(CompletionFromParent,CompletionStateCanceled,nil,G.ErrCancelByParent) + c.notify(CompletionFromParent, StateCanceled,nil,G.ErrCancelByParent) return G.ErrCancelByParent } ex = c.parent @@ -159,8 +166,8 @@ func (c *Completion) complete (ctx context.Context, cctx CompletionContext, cid c.Context = ctx if ctx.Err() != nil { c.mux.Unlock() - c.notify(CompletionFromContext,CompletionStateCanceled,nil,G.ErrCancelByContext) - return G.ErrCancelByContext.ToErrCause(ctx.Err()) + c.notify(CompletionFromContext, StateCanceled,nil,G.ErrCancelByContext) + return G.ErrCancelByContext.WrapWithCause(ctx.Err()) } ch := make(chan struct{}) @@ -169,8 +176,8 @@ func (c *Completion) complete (ctx context.Context, cctx CompletionContext, cid select { case <- ch: case <- cc.Context.Done() : - er := G.ErrCancelByContext.ToErrCause(cc.Context.Err()) - cc.notify(CompletionFromContext,CompletionStateCanceled,nil,er) + er := G.ErrCancelByContext.WrapWithCause(cc.Context.Err()) + cc.notify(CompletionFromContext, StateCanceled,nil,er) } }(c,ch) } @@ -179,18 +186,18 @@ func (c *Completion) complete (ctx context.Context, cctx CompletionContext, cid if er := c.expiration.Start(ex); er != nil { c.mux.Unlock() - c.notify(CompletionFromSelf,CompletionStateFaulted,nil,er) + c.notify(CompletionFromSelf, StateFaulted,nil,er) return er } - atomic.StoreUint32(&c.state,uint32(CompletionStateStarted)) + atomic.StoreUint32(&c.state,uint32(StateStarted)) c.wgr.Add(1) go func (c *Completion) { ln := len(c.completers) if ln == 0 { c.mux.Unlock() - c.notify(CompletionFromSelf, CompletionStateCompleted, nil, nil) + c.notify(CompletionFromSelf, StateCompleted, nil, nil) return } @@ -203,7 +210,7 @@ func (c *Completion) complete (ctx context.Context, cctx CompletionContext, cid return } if er := c.dispatchFn(c,cm,ix); er != nil { - c.notify(CompletionFromSelf,CompletionStateFaulted,nil,er) + c.notify(CompletionFromSelf, StateFaulted,nil,er) return } } @@ -215,14 +222,14 @@ func (c *Completion) complete (ctx context.Context, cctx CompletionContext, cid func (c *Completion) Notify (frm int, val interface{}, err error) { - c.notify(frm,CompletionStateCompleted,val,err) } + c.notify(frm, StateCompleted,val,err) } -func (c *Completion) notify (frm int, ste CompletionState, val interface{}, err error) { +func (c *Completion) notify (frm int, ste State, val interface{}, err error) { c.mux.Lock() os := c.State() - if os > CompletionStateStarted { + if os > StateStarted { c.mux.Unlock() return } @@ -232,26 +239,26 @@ func (c *Completion) notify (frm int, ste CompletionState, val interface{}, err switch { case c.mode.IsAnyOrResult() && val != nil: - atomic.StoreUint32(&c.state,uint32(CompletionStateCompleted)) - c.result = NewCompletionResultValue(frm, val) + atomic.StoreUint32(&c.state,uint32(StateCompleted)) + c.result = NewResultValue(frm, val) case c.mode.IsAnyOrError() && err != nil: - atomic.StoreUint32(&c.state,uint32(CompletionStateFaulted)) - c.result = NewCompletionResultError(frm, err) + atomic.StoreUint32(&c.state,uint32(StateFaulted)) + c.result = NewResultError(frm, err) - case c.mode == completionModeTask: - c.result = NewCompletionResult(frm, val, err) + case c.mode == ModeTask: + c.result = NewResult(frm, val, err) default: - if c.mode == CompletionModeAll { + if c.mode == ModeAll { if c.result == nil { - c.result = NewCompletionResultList(c.cid, NewCompletionResult(frm, val, err)) + c.result = NewResultList(c.cid, NewResult(frm, val, err)) } else { - c.result.(*CompletionResultList).Add(NewCompletionResult(frm, val, err)) + c.result.(*ResultList).Add(NewResult(frm, val, err)) } } if cn == 0 { - atomic.StoreUint32(&c.state,uint32(CompletionStateCompleted)) + atomic.StoreUint32(&c.state,uint32(StateCompleted)) } else { c.mux.Unlock() return @@ -260,7 +267,7 @@ func (c *Completion) notify (frm int, ste CompletionState, val interface{}, err } else { atomic.StoreUint32(&c.state,uint32(ste)) - c.result = NewCompletionResult(frm,val,err) + c.result = NewResult(frm,val,err) } _ = c.expiration.Stop() @@ -272,11 +279,11 @@ func (c *Completion) notify (frm int, ste CompletionState, val interface{}, err // Solo notificamos a las completions hijas y al padre en caso de que se haya iniciado - if os == CompletionStateStarted { + if os == StateStarted { for _, ch := range c.completers { // Notificamos solo a los completer que a su vez implementan - // CompletionContext - if cm, is := ch.(CompletionContext); is { + // Context + if cm, is := ch.(Context); is { if !cm.IsCompleted() { cm.Notify(CompletionFromParent, nil, G.ErrCancelByParent) } @@ -298,4 +305,69 @@ func (c *Completion) notify (frm int, ste CompletionState, val interface{}, err func dispatcher (completion *Completion, completer Completer, cid int) error { go completer.Complete(completion,cid) return nil -} \ No newline at end of file +} + + + + + + +// WithMode +// Desc: Función para el constructor de Completion, +// establece el mode de como se llegara a la completion +// +func WithMode (mode Mode) opts.GOptionErrFnc[Completion] { + return func(c *Completion) error { + c.mode = mode + return nil + } +} + + +// WithTimeout +// Desc: Función para el constructor de Completion +// Establece el tiempo máximo de la completion +// +func WithTimeout (tmo time.Duration) opts.GOptionErrFnc[Completion] { + return func(c *Completion) error { + c.expiration = cronus.NewExpiration(tmo,func(){ + c.notify(CompletionFromTimer, StateCanceled,nil,G.ErrCancelByTimer) + }) + return nil + } +} + + +// WithCompleters +// Desc: Función para el constructor de Completion, +// añade los objeto a completar en la completion +// +func WithCompleters (completers ... Completer) opts.GOptionErrFnc[Completion] { + return func(c *Completion) error { + if c.State() != StateCreated { + return G.ErrInvalidState + } + for _, cm := range completers { + c.completers = append(c.completers, cm) + } + return nil + } +} + + +// WithWorkPool +// Desc: Función para el constructor de Completion, +// utiliza un pool de trabajo para completar +// las tareas. +// +func WithWorkPool (pool *works.Pool) opts.GOptionErrFnc[Completion] { + return func(c *Completion) error { + c.dispatchFn = dispatchFnc(func (cm *Completion, cr Completer, ci int) error { + return pool.DoWork(c,func(){ + cr.Complete(cm,ci) + }) + }) + return nil + } +} + diff --git a/core/syncs/tasks/completion_context.go b/core/syncs/ctasks/context.go similarity index 96% rename from core/syncs/tasks/completion_context.go rename to core/syncs/ctasks/context.go index d7cbeef..17d139d 100644 --- a/core/syncs/tasks/completion_context.go +++ b/core/syncs/ctasks/context.go @@ -21,13 +21,13 @@ // limitations under the License. // ------------------------------------------------------------------------ -package tasks +package ctasks import "context" type ( - CompletionContext interface { + Context interface { context.Context IsCompleted () bool diff --git a/core/syncs/ctasks/err_ctasks.go b/core/syncs/ctasks/err_ctasks.go new file mode 100644 index 0000000..9ab177c --- /dev/null +++ b/core/syncs/ctasks/err_ctasks.go @@ -0,0 +1,33 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name err_tasks.go +// Created by DEV +// Modified 23/04/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 ctasks + +import "errs" + +type ( + + ErrCTasks struct { errs.ErrCode } +) + + diff --git a/core/syncs/tasks/completion_mode.go b/core/syncs/ctasks/mode.go similarity index 65% rename from core/syncs/tasks/completion_mode.go rename to core/syncs/ctasks/mode.go index ba1502f..fe27eb5 100644 --- a/core/syncs/tasks/completion_mode.go +++ b/core/syncs/ctasks/mode.go @@ -21,55 +21,57 @@ // limitations under the License. // ------------------------------------------------------------------------ -package tasks +package ctasks const( - CompletionModeAll CompletionMode = iota + ModeAll Mode = iota - // CompletionModeAny Las tareas se ejecutaran haste que se + // ModeAny Las tareas se ejecutaran haste que se //produzca el primer resultado o el primer error - CompletionModeAny + ModeAny - //CompletionModeResult Las tareas se ejecutaran hasta que + //ModeResult Las tareas se ejecutaran hasta que //se obtenga el primer resultado. - CompletionModeResult + ModeResult - //CompletionModeError Las tareas se completaran en el momento de + //ModeError Las tareas se completaran en el momento de //que se produzca un error. - CompletionModeError + ModeError //CompletionModeTask Modo para las completions de una sola task - completionModeTask + ModeTask ) type ( - CompletionMode uint8 + Mode uint8 ) -func (m CompletionMode) IsAnyOrResult () bool { - return m == CompletionModeResult || m == CompletionModeAny } +func (m Mode) IsAnyOrResult () bool { + return m == ModeResult || m == ModeAny +} -func (m CompletionMode) IsAnyOrError () bool { - return m == CompletionModeError || m == CompletionModeAny } +func (m Mode) IsAnyOrError () bool { + return m == ModeError || m == ModeAny +} -func (m CompletionMode) String () string { +func (m Mode) String () string { switch m { - case CompletionModeAll : return "all" - case CompletionModeAny : return "any" - case CompletionModeResult: return "result" - case CompletionModeError : return "error" - case completionModeTask : return "task" + case ModeAll: return "all" + case ModeAny: return "any" + case ModeResult: return "result" + case ModeError: return "error" + case ModeTask: return "task" default: return "??" } diff --git a/core/syncs/tasks/completion_result.go b/core/syncs/ctasks/result.go similarity index 79% rename from core/syncs/tasks/completion_result.go rename to core/syncs/ctasks/result.go index 6df152f..fb41237 100644 --- a/core/syncs/tasks/completion_result.go +++ b/core/syncs/ctasks/result.go @@ -21,13 +21,13 @@ // limitations under the License. // ------------------------------------------------------------------------ -package tasks +package ctasks type ( - CompletionResult interface { + Result interface { CID () int @@ -35,17 +35,17 @@ type ( Error() error - Kind () CompletionResultKind + Kind () ResultKind } ) -func NewCompletionResult (cid int, val any, err error) CompletionResult { +func NewResult(cid int, val any, err error) Result { if err != nil { - return *NewCompletionResultError(cid,err) + return *NewResultError(cid,err) } if val != nil { - return *NewCompletionResultValue(cid,val) + return *NewResultValue(cid,val) } - return CompletionResultVoid(cid) + return ResultVoid(cid) } \ No newline at end of file diff --git a/core/syncs/tasks/completion_result_error.go b/core/syncs/ctasks/result_error.go similarity index 78% rename from core/syncs/tasks/completion_result_error.go rename to core/syncs/ctasks/result_error.go index 000b467..3e977d1 100644 --- a/core/syncs/tasks/completion_result_error.go +++ b/core/syncs/ctasks/result_error.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package tasks +package ctasks @@ -29,30 +29,31 @@ package tasks type ( - CompletionResultError struct { + ResultError struct { cid int err error } ) -func NewCompletionResultError (cid int, err error) *CompletionResultError { - return &CompletionResultError{ +func NewResultError(cid int, err error) *ResultError { + return &ResultError{ cid : cid, err : err, } } -func (r CompletionResultError) CID () int { +func (r ResultError) CID () int { return r.cid } -func (_ CompletionResultError) Kind () CompletionResultKind { - return CompletionResultKindError } +func (_ ResultError) Kind () ResultKind { + return ResultKindError +} -func (_ CompletionResultError) Value () any { +func (_ ResultError) Value () any { return nil } -func (r CompletionResultError) Error () error { +func (r ResultError) Error () error { return r.err } diff --git a/core/syncs/tasks/completion_result_kind.go b/core/syncs/ctasks/result_kind.go similarity index 64% rename from core/syncs/tasks/completion_result_kind.go rename to core/syncs/ctasks/result_kind.go index 37ef56d..1378801 100644 --- a/core/syncs/tasks/completion_result_kind.go +++ b/core/syncs/ctasks/result_kind.go @@ -21,48 +21,52 @@ // limitations under the License. // ------------------------------------------------------------------------ -package tasks +package ctasks const( - CompletionResultKindVoid CompletionResultKind = iota - CompletionResultKindError - CompletionResultKindValue - CompletionResultKindList + ResultKindVoid ResultKind = iota + ResultKindError + ResultKindValue + ResultKindList ) type ( - CompletionResultKind uint8 + ResultKind uint8 ) -func (k CompletionResultKind) IsVoid () bool { - return k == CompletionResultKindVoid } +func (k ResultKind) IsVoid () bool { + return k == ResultKindVoid +} -func (k CompletionResultKind) IsError() bool { - return k == CompletionResultKindError} +func (k ResultKind) IsError() bool { + return k == ResultKindError +} -func (k CompletionResultKind) IsValue() bool { - return k == CompletionResultKindValue} +func (k ResultKind) IsValue() bool { + return k == ResultKindValue +} -func (k CompletionResultKind) IsList () bool { - return k == CompletionResultKindList } +func (k ResultKind) IsList () bool { + return k == ResultKindList +} -func (k CompletionResultKind) String () string { +func (k ResultKind) String () string { switch k { - case CompletionResultKindVoid : return "void" - case CompletionResultKindValue: return "value" - case CompletionResultKindError: return "error" - case CompletionResultKindList : return "list" + case ResultKindVoid: return "void" + case ResultKindValue: return "value" + case ResultKindError: return "error" + case ResultKindList: return "list" default: return "??" } diff --git a/core/syncs/tasks/completion_result_list.go b/core/syncs/ctasks/result_list.go similarity index 73% rename from core/syncs/tasks/completion_result_list.go rename to core/syncs/ctasks/result_list.go index c531ae3..bbf36cc 100644 --- a/core/syncs/tasks/completion_result_list.go +++ b/core/syncs/ctasks/result_list.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package tasks +package ctasks @@ -29,43 +29,44 @@ package tasks type ( - CompletionResultList struct { + ResultList struct { cid int - results []CompletionResult + results []Result } ) -func NewCompletionResultList (cid int, results ... CompletionResult) *CompletionResultList { - ls := make([]CompletionResult,len(results)) +func NewResultList(cid int, results ...Result) *ResultList { + ls := make([]Result,len(results)) copy(ls, results) - return &CompletionResultList{ + return &ResultList{ cid: cid, results: ls, } } -func (r *CompletionResultList) Add (rsl CompletionResult) { +func (r *ResultList) Add (rsl Result) { if rsl != nil { r.results = append(r.results, rsl) } } -func (r CompletionResultList) CID () int { +func (r ResultList) CID () int { return r.cid } -func (_ CompletionResultList) Kind () CompletionResultKind { - return CompletionResultKindList } +func (_ ResultList) Kind () ResultKind { + return ResultKindList +} -func (_ CompletionResultList) Error () error { +func (_ ResultList) Error () error { return nil } -func (r CompletionResultList) Value () any { +func (r ResultList) Value () any { return r.results } diff --git a/core/syncs/tasks/completion_result_value.go b/core/syncs/ctasks/result_value.go similarity index 78% rename from core/syncs/tasks/completion_result_value.go rename to core/syncs/ctasks/result_value.go index 3bd8161..f764fb5 100644 --- a/core/syncs/tasks/completion_result_value.go +++ b/core/syncs/ctasks/result_value.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package tasks +package ctasks @@ -30,30 +30,31 @@ package tasks type ( - CompletionResultValue struct { + ResultValue struct { cid int value any } ) -func NewCompletionResultValue (cid int, value any) *CompletionResultValue { - return &CompletionResultValue{ +func NewResultValue(cid int, value any) *ResultValue { + return &ResultValue{ cid : cid, value: value, } } -func (r CompletionResultValue) CID () int { +func (r ResultValue) CID () int { return r.cid } -func (_ CompletionResultValue) Kind () CompletionResultKind { - return CompletionResultKindValue } +func (_ ResultValue) Kind () ResultKind { + return ResultKindValue +} -func (_ CompletionResultValue) Error () error { +func (_ ResultValue) Error () error { return nil } -func (r CompletionResultValue) Value () any { +func (r ResultValue) Value () any { return r.value } diff --git a/core/syncs/tasks/completion_result_void.go b/core/syncs/ctasks/result_void.go similarity index 83% rename from core/syncs/tasks/completion_result_void.go rename to core/syncs/ctasks/result_void.go index 13c8b7e..69d4459 100644 --- a/core/syncs/tasks/completion_result_void.go +++ b/core/syncs/ctasks/result_void.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package tasks +package ctasks @@ -30,23 +30,24 @@ package tasks type ( - CompletionResultVoid int + ResultVoid int ) -func (r CompletionResultVoid) CID () int { +func (r ResultVoid) CID () int { return int(r) } -func (_ CompletionResultVoid) Kind () CompletionResultKind { - return CompletionResultKindVoid } +func (_ ResultVoid) Kind () ResultKind { + return ResultKindVoid +} -func (_ CompletionResultVoid) Value () any { +func (_ ResultVoid) Value () any { return nil } -func (_ CompletionResultVoid) Error () error { +func (_ ResultVoid) Error () error { return nil } diff --git a/core/syncs/ctasks/state.go b/core/syncs/ctasks/state.go new file mode 100644 index 0000000..d5d6e06 --- /dev/null +++ b/core/syncs/ctasks/state.go @@ -0,0 +1,58 @@ +// ------------------------------------------------------------------------ +// Project atila +// Active Thing (activething.com) git.activething.com/go +// +// File name completion_state.go +// Created by DEV +// Modified 20/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 ctasks + + + +const ( + + StateCreated State = iota + StateStarted + StateCompleted + StateCanceled + StateFaulted + +) + + +type ( + + State uint32 + +) + + +func (s State) String () string { + switch s { + case StateCreated: return "created" + case StateStarted: return "started" + case StateCompleted: return "completed" + case StateCanceled: return "canceled" + case StateFaulted: return "faulted" + default: return "??" + } +} + + + diff --git a/core/syncs/tasks/completion_ops.go b/core/syncs/tasks/completion_ops.go deleted file mode 100644 index 0cc2ec6..0000000 --- a/core/syncs/tasks/completion_ops.go +++ /dev/null @@ -1,91 +0,0 @@ -// ------------------------------------------------------------------------ -// Project atila -// Active Thing (activething.com) git.activething.com/go -// -// File name completion_ops.go -// Created by DEV -// Modified 21/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 tasks - -import ( - "opts" - "time" - "timers" -) - - -// CompletionWithMode -// Desc: Función para el constructor de Completion, -// establece el mode de como se llegara a la completion -// -func CompletionWithMode (mode CompletionMode) opts.GOptionErrFnc[Completion] { - return func(c *Completion) error { - c.mode = mode - return nil - } -} - - -// CompletionWithTimeout -// Desc: Función para el constructor de Completion -// Establece el tiempo máximo de la completion -// -func CompletionWithTimeout (tmo time.Duration) opts.GOptionErrFnc[Completion] { - return func(c *Completion) error { - c.expiration = timers.NewExpiration(tmo,func(){ - c.notify(CompletionFromTimer,CompletionStateCanceled,nil,G.ErrCancelByTimer) - }) - return nil - } -} - - -// CompletionWithCompleters -// Desc: Función para el constructor de Completion, -// añade los objeto a completar en la completion -// -func CompletionWithCompleters (completers ... Completer) opts.GOptionErrFnc[Completion] { - return func(c *Completion) error { - if c.State() != CompletionStateCreated { - return G.ErrInvalidState - } - for _, cm := range completers { - c.completers = append(c.completers, cm) - } - return nil - } -} - - -// CompletionWithWorkPool -// Desc: Función para el constructor de Completion, -// utiliza un pool de trabajo para completar -// las tareas. -// -func CompletionWithWorkPool (pool *WorkerPool) opts.GOptionErrFnc[Completion] { - return func(c *Completion) error { - c.dispatchFn = dispatchFnc(func (cm *Completion, cr Completer, ci int) error { - return pool.DoWork(c,func(){ - cr.Complete(cm,ci) - }) - }) - return nil - } -} - diff --git a/core/syncs/tasks/gogo.go b/core/syncs/tasks/gogo.go deleted file mode 100644 index df3a53a..0000000 --- a/core/syncs/tasks/gogo.go +++ /dev/null @@ -1,66 +0,0 @@ -// ------------------------------------------------------------------------ -// Project atila -// Active Thing (activething.com) git.activething.com/go -// -// File name gogo.go -// Created by DEV -// Modified 20/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 tasks - -const ( - - CompletionFromChild int = 0 - CompletionFromSelf int = -1 - CompletionFromParent int = -2 - CompletionFromContext int = -3 - CompletionFromTimer int = -4 - CompletionFromRequest int = -5 - -) - - -var ( - - G = struct { - - ErrInvalidCompletion errs.ErrCode - ErrInvalidState errs.ErrCode - ErrCancelByParent errs.ErrCode - ErrCancelByRequest errs.ErrCode - ErrCancelByContext errs.ErrCode - ErrCancelByTimer errs.ErrCode - - ErrPoolStarted errs.ErrCode - ErrPoolStopped errs.ErrCode - ErrPoolAcquire errs.ErrCode - }{ - ErrInvalidCompletion: errs.ErrCode("syncs:tasks.invalid-completion"), - ErrInvalidState : errs.ErrCode("syncs:tasks.invalid-state"), - ErrCancelByParent : errs.ErrCode("syncs:tasks.cancel-by-parent"), - ErrCancelByRequest : errs.ErrCode("syncs:tasks.cancel-by-request"), - ErrCancelByContext : errs.ErrCode("syncs:tasks.cancel-by-context"), - ErrCancelByTimer : errs.ErrCode("syncs:tasks.cancel-by-timer"), - - ErrPoolStarted : errs.ErrCode("syncs:tasks.pool-started"), - ErrPoolStopped : errs.ErrCode("syncs:tasks.pool-stopped"), - ErrPoolAcquire : errs.ErrCode("syncs:tasks.pool-acquire"), - } -) - - diff --git a/core/syncs/works/active.go b/core/syncs/works/active.go new file mode 100644 index 0000000..9505ee3 --- /dev/null +++ b/core/syncs/works/active.go @@ -0,0 +1,56 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name active.go +// Created by DEV +// Modified 23/04/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 works + +import ( + "errs" + "time" +) + +const ( + + minWorkers = 10 + maxWorkers = 1000 + + minIdle = time.Millisecond * 100 + maxIdle = time.Second * 10 + +) + +var ( + + G = struct { + + ErrPoolStarted ErrWorks + ErrPoolStopped ErrWorks + ErrPoolAcquire ErrWorks + + }{ + ErrPoolStarted : ErrWorks{errs.ErrCode("pool-started")}, + ErrPoolStopped : ErrWorks{errs.ErrCode("pool-stopped")}, + ErrPoolAcquire : ErrWorks{errs.ErrCode("pool-acquire")}, + } +) + + diff --git a/core/syncs/works/err_works.go b/core/syncs/works/err_works.go new file mode 100644 index 0000000..d451d8a --- /dev/null +++ b/core/syncs/works/err_works.go @@ -0,0 +1,34 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name err_works.go +// Created by DEV +// Modified 23/04/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 works + +import "errs" + +type ( + + ErrWorks struct { errs.ErrCode } +) + + + diff --git a/core/syncs/tasks/worker_pool.go b/core/syncs/works/pool.go similarity index 71% rename from core/syncs/tasks/worker_pool.go rename to core/syncs/works/pool.go index a870959..75f5a77 100644 --- a/core/syncs/tasks/worker_pool.go +++ b/core/syncs/works/pool.go @@ -21,11 +21,10 @@ // limitations under the License. // ------------------------------------------------------------------------ -package tasks +package works import ( "context" - "opts" "runtime" "sync" "sync/atomic" @@ -33,19 +32,10 @@ import ( "time" ) -const ( - - minWorkers = 10 - maxWorkers = 1000 - - minIdle = time.Millisecond * 100 - maxIdle = time.Second * 10 - -) type ( - WorkerPool struct { + Pool struct { stats *syncs.PoolStatsInfo pool sync.Pool mux sync.Mutex @@ -61,47 +51,52 @@ type ( doneCh chan struct{} } + + PoolFnc func(wp *Pool) ) -func NewWorkerPool (options ...opts.GOptionFnc[WorkerPool]) *WorkerPool { +func NewPool(options ...PoolFnc) *Pool { c := int32(1) if runtime.GOMAXPROCS(0) == 1 { c = 0 } - wp := opts.GApply[WorkerPool](&WorkerPool{ + wp := &Pool{ stats : syncs.NewPoolStatsInfo(), maxIdle: int64(maxIdle), cap : c, max : maxWorkers, - state : uint32(WorkerPoolStateCreated), - }, options ...) + state : uint32(PoolStateCreated), + } + for _,o := range options { + o(wp) + } wp.pool.New = wp.newWorker return wp } -func (p *WorkerPool) newWorker () any { +func (p *Pool) newWorker () any { p.stats.AddCreated() - return &worker { + return &worker{ jobCh: make(chan func(), atomic.LoadInt32(&p.cap)) }} -func (p *WorkerPool) Stats () syncs.PoolStats { +func (p *Pool) Stats () syncs.PoolStats { return p.stats } -func (p *WorkerPool) State () WorkerPoolState { - return WorkerPoolState(atomic.LoadUint32(&p.state)) } +func (p *Pool) State () PoolState { + return PoolState(atomic.LoadUint32(&p.state)) } -func (p *WorkerPool) Count () int32 { +func (p *Pool) Count () int32 { return atomic.LoadInt32(&p.count) } -func (p *WorkerPool) MaxWorkers () int32 { +func (p *Pool) MaxWorkers () int32 { return atomic.LoadInt32(&p.max) } -func (p *WorkerPool) SetMaxWorkers (max int32) { +func (p *Pool) SetMaxWorkers (max int32) { if max <= 0 { max = maxWorkers } @@ -109,10 +104,10 @@ func (p *WorkerPool) SetMaxWorkers (max int32) { } -func (p *WorkerPool) WorkerCap () int32 { +func (p *Pool) WorkerCap () int32 { return atomic.LoadInt32(&p.cap) } -func (p *WorkerPool) SetWorkerCap (cap int32) { +func (p *Pool) SetWorkerCap (cap int32) { if cap <= 0 { cap = 0 } @@ -120,10 +115,10 @@ func (p *WorkerPool) SetWorkerCap (cap int32) { } -func (p *WorkerPool) MaxWorkerIdle () time.Duration { +func (p *Pool) MaxWorkerIdle () time.Duration { return time.Duration(atomic.LoadInt64(&p.maxIdle)) } -func (p *WorkerPool) SetMaxWorkerIdle (idle time.Duration) { +func (p *Pool) SetMaxWorkerIdle (idle time.Duration) { if idle < minIdle { idle = minIdle } @@ -134,29 +129,28 @@ func (p *WorkerPool) SetMaxWorkerIdle (idle time.Duration) { -func (p *WorkerPool) Done () <- chan struct{} { +func (p *Pool) Done () <- chan struct{} { return p.doneCh } -func (p *WorkerPool) Start () error { +func (p *Pool) Start () error { p.mux.Lock() st := p.State() - if st == WorkerPoolStateRunning { + if st == PoolStateRunning { p.mux.Unlock() return G.ErrPoolStarted } - - if st == WorkerPoolStateStopped { + if st == PoolStateStopped { atomic.StoreInt32(&p.count,0) } p.doneCh = make(chan struct{}) p.mux.Unlock() - go func(p *WorkerPool) { - atomic.StoreUint32(&p.state,uint32(WorkerPoolStateRunning)) + go func(p *Pool) { + atomic.StoreUint32(&p.state,uint32(PoolStateRunning)) var ls []*worker for { p.clearWorkers(&ls) @@ -173,13 +167,13 @@ func (p *WorkerPool) Start () error { } -func (p *WorkerPool) Stop () error { +func (p *Pool) Stop () error { p.mux.Lock() - if p.State() != WorkerPoolStateRunning { + if p.State() != PoolStateRunning { p.mux.Unlock() return G.ErrPoolStopped } - atomic.StoreUint32(&p.state,uint32(WorkerPoolStateStopped)) + atomic.StoreUint32(&p.state,uint32(PoolStateStopped)) close(p.doneCh) p.doneCh = nil @@ -197,9 +191,9 @@ func (p *WorkerPool) Stop () error { } -func (p *WorkerPool) DoWork(ctx context.Context, job func()) error { +func (p *Pool) DoWork(ctx context.Context, job func()) error { p.mux.Lock() - if p.State() != WorkerPoolStateRunning { + if p.State() != PoolStateRunning { p.mux.Unlock() return G.ErrPoolStopped } @@ -222,7 +216,7 @@ func (p *WorkerPool) DoWork(ctx context.Context, job func()) error { atomic.AddInt32(&p.count,1) wk = p.pool.Get().(*worker) - go func(p *WorkerPool, w *worker, x context.Context) { + go func(p *Pool, w *worker, x context.Context) { for job := range w.jobCh { if job == nil { @@ -233,7 +227,7 @@ func (p *WorkerPool) DoWork(ctx context.Context, job func()) error { p.mux.Lock() done := false - if p.State() != WorkerPoolStateStopped { + if p.State() != PoolStateStopped { w.lastTime = time.Now() p.workers = append(p.workers, w) done = true @@ -259,7 +253,7 @@ func (p *WorkerPool) DoWork(ctx context.Context, job func()) error { -func (p *WorkerPool) clearWorkers (cls *[]*worker) { +func (p *Pool) clearWorkers (cls *[]*worker) { p.mux.Lock() tm := time.Now() mi := time.Duration(atomic.LoadInt64(&p.maxIdle)) diff --git a/core/syncs/tasks/worker_pool_state.go b/core/syncs/works/pool_state.go similarity index 88% rename from core/syncs/tasks/worker_pool_state.go rename to core/syncs/works/pool_state.go index dca2a9d..67f5f77 100644 --- a/core/syncs/tasks/worker_pool_state.go +++ b/core/syncs/works/pool_state.go @@ -21,19 +21,19 @@ // limitations under the License. // ------------------------------------------------------------------------ -package tasks +package works const ( - WorkerPoolStateCreated WorkerPoolState = iota - WorkerPoolStateRunning - WorkerPoolStateStopped + PoolStateCreated PoolState = iota + PoolStateRunning + PoolStateStopped ) type ( - WorkerPoolState uint32 + PoolState uint32 ) diff --git a/core/syncs/tasks/worker.go b/core/syncs/works/worker.go similarity index 98% rename from core/syncs/tasks/worker.go rename to core/syncs/works/worker.go index b855c9f..b8dfc4d 100644 --- a/core/syncs/tasks/worker.go +++ b/core/syncs/works/worker.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package tasks +package works import "time" diff --git a/core/tbase/go.mod b/core/tbase/go.mod deleted file mode 100644 index 8fa5171..0000000 --- a/core/tbase/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module tbase - -go 1.22 diff --git a/go.work b/go.work index 4d36834..4ded262 100644 --- a/go.work +++ b/go.work @@ -4,7 +4,7 @@ use ( ./core/errs ./core/rsts - ./core/cdcs + ./core/codecs ./core/crypts ./core/vals ./core/btes @@ -12,12 +12,13 @@ use ( ./core/ansi ./core/opts ./core/syncs - ./core/times - ./core/timers + ./core/dates + ./core/cronus ./core/ctxs - ./core/tbase - ./core/pkrs - + ./core/btypes + ./core/btes/matchs + ./packs + ./logs ./app ) \ No newline at end of file diff --git a/logs/active.go b/logs/active.go new file mode 100644 index 0000000..777c35d --- /dev/null +++ b/logs/active.go @@ -0,0 +1,39 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name active.go +// Created by DEV +// Modified 23/04/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 logs + + +const ( + + LevelNameData string = "DATA" + LevelNameDebug string = "DEBUG" + LevelNameInfo string = "INFO" + LevelNameWarn string = "WARN" + LevelNameError string = "ERROR" + LevelNameFatal string = "FATAL" + + levelNameSep string = "|" +) + + diff --git a/logs/entry.go b/logs/entry.go new file mode 100644 index 0000000..6988990 --- /dev/null +++ b/logs/entry.go @@ -0,0 +1,41 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name entry.go +// Created by DEV +// Modified 23/04/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 logs + + + +type ( + + + Entry struct { + Logger Logger + + + } + + + EntryFnc func (entry *Entry) +) + + diff --git a/logs/go.mod b/logs/go.mod new file mode 100644 index 0000000..0b96933 --- /dev/null +++ b/logs/go.mod @@ -0,0 +1,3 @@ +module logs + +go 1.22 diff --git a/logs/level.go b/logs/level.go new file mode 100644 index 0000000..f557612 --- /dev/null +++ b/logs/level.go @@ -0,0 +1,167 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name level.go +// Created by DEV +// Modified 23/04/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 logs + +import ( + "math/bits" + "strings" +) + +const( + + levelsCount int = 6 + + LevelNone Level = 0 + LevelData Level = 1 << iota + LevelDebug + LevelInfo + LevelWarn + LevelError + LevelFatal + + LevelAll Level = LevelData|LevelDebug|LevelInfo|LevelWarn|LevelError|LevelFatal + +) + + +type ( + + + // Level + // Enum type + // + Level uint8 + +) + + +func (lv Level) Count() int{ + return bits.OnesCount8(uint8(lv)) } + + +func (lv Level) String() string { + return LevelNames(lv) } + + +func (lv Level) List () []Level { + return LevelList(lv) } + + + + +func (lv Level) Add(lvl Level) Level { + return lv | lvl } + + +func (lv Level) Del(lvl Level) Level { + return lv &^ lvl } + + + +func (lv Level) Has (lvl Level) bool { + return lv&lvl != 0 } + + + + +func (lv Level) HasData() bool { + return lv&LevelData!=0 } + + +func (lv Level) HasDebug() bool { + return lv&LevelDebug!=0 } + + +func (lv Level) HasInfo() bool { + return lv&LevelInfo!=0 } + + +func (lv Level) HasWarn() bool { + return lv&LevelWarn!=0 } + + +func (lv Level) HasError() bool { + return lv&LevelError!=0 } + + +func (lv Level) HasFatal() bool { + return lv&LevelFatal!=0 } + + + + + + +func LevelList(level Level) []Level { + var result [levelsCount]Level + x := 0 + for i := uint8(0); i <= uint8(levelsCount); i++ { + c := Level(1 << i) + if level.Has(c) { + result[x] = c + x++ + } + } + return result[:x] +} + + +func LevelNames (level Level) string { + if level == LevelNone { + return "" + } + ix := 0 + ls := make([]string, levelsCount) + if level&LevelData != 0 { ls[ix]=LevelNameData ; ix++ } + if level&LevelDebug!= 0 { ls[ix]=LevelNameDebug; ix++ } + if level&LevelInfo != 0 { ls[ix]=LevelNameInfo ; ix++ } + if level&LevelWarn != 0 { ls[ix]=LevelNameWarn ; ix++ } + if level&LevelError!= 0 { ls[ix]=LevelNameError; ix++ } + if level&LevelFatal!= 0 { ls[ix]=LevelNameFatal; ix++ } + if ix==0 { + return "" + } + return strings.Join(ls[:ix],levelNameSep) +} + + +func LevelWithNames(name string) Level { + if name == "" { + return LevelNone + } + lv := LevelNone + for _,sl := range strings.Split(strings.ToUpper(name),levelNameSep) { + switch sl { + case LevelNameData : lv|=LevelData + case LevelNameDebug : lv|=LevelDebug + case LevelNameInfo : lv|=LevelInfo + case LevelNameWarn : lv|=LevelWarn + case LevelNameError : lv|=LevelError + case LevelNameFatal : lv|=LevelFatal + } + } + return lv +} + + diff --git a/logs/logger.go b/logs/logger.go new file mode 100644 index 0000000..b125d5e --- /dev/null +++ b/logs/logger.go @@ -0,0 +1,43 @@ +// ------------------------------------------------------------------------ +// Project active2 +// Active Thing (activething.com) git.activething.com/go +// +// File name logger.go +// Created by DEV +// Modified 23/04/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 logs + + +type ( + + Logger interface { + + Name () string + Level() Level + + Fatal (message string, err error, options ...EntryFnc) + Error (message string, err error, options ...EntryFnc) + Warn (message string, options ...EntryFnc) + Info (message string, options ...EntryFnc) + Debug (message string, options ...EntryFnc) + Data (message string, data any, options ...EntryFnc) + } +) + + diff --git a/core/pkrs/active.go b/packs/active.go similarity index 57% rename from core/pkrs/active.go rename to packs/active.go index eebe601..d362850 100644 --- a/core/pkrs/active.go +++ b/packs/active.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package pkrs +package packs import ( "errs" @@ -44,27 +44,27 @@ var ( G = struct { - ErrInvalidState Err - ErrInvalidNode Err - ErrInvalidKey Err - ErrDuplicatedKey Err - ErrKeyRequired Err - ErrValueRequired Err - ErrInvalidList Err - ErrRedundantPack Err - ErrInvalidValue Err - ErrUnsupportedType Err + ErrInvalidState ErrPacks + ErrInvalidNode ErrPacks + ErrInvalidKey ErrPacks + ErrDuplicatedKey ErrPacks + ErrKeyRequired ErrPacks + ErrValueRequired ErrPacks + ErrInvalidList ErrPacks + ErrRedundantPack ErrPacks + ErrInvalidValue ErrPacks + ErrUnsupportedType ErrPacks }{ - ErrInvalidState : Err{errs.ErrCode("invalid-state")}, - ErrInvalidNode : Err{errs.ErrCode("invalid-node")}, - ErrInvalidKey : Err{errs.ErrCode("invalid-key")}, - ErrDuplicatedKey : Err{errs.ErrCode("duplicated-key")}, - ErrKeyRequired : Err{errs.ErrCode("key-required")}, - ErrValueRequired : Err{errs.ErrCode("value-required")}, - ErrInvalidList : Err{errs.ErrCode("invalid-list")}, - ErrRedundantPack : Err{errs.ErrCode("redundant-pack")}, - ErrInvalidValue : Err{errs.ErrCode("invalid-value")}, - ErrUnsupportedType: Err{errs.ErrCode("unsupported-type")}, + ErrInvalidState : ErrPacks{errs.ErrCode("invalid-state")}, + ErrInvalidNode : ErrPacks{errs.ErrCode("invalid-node")}, + ErrInvalidKey : ErrPacks{errs.ErrCode("invalid-key")}, + ErrDuplicatedKey : ErrPacks{errs.ErrCode("duplicated-key")}, + ErrKeyRequired : ErrPacks{errs.ErrCode("key-required")}, + ErrValueRequired : ErrPacks{errs.ErrCode("value-required")}, + ErrInvalidList : ErrPacks{errs.ErrCode("invalid-list")}, + ErrRedundantPack : ErrPacks{errs.ErrCode("redundant-pack")}, + ErrInvalidValue : ErrPacks{errs.ErrCode("invalid-value")}, + ErrUnsupportedType: ErrPacks{errs.ErrCode("unsupported-type")}, } g = struct { diff --git a/core/pkrs/builder.go b/packs/builder.go similarity index 98% rename from core/pkrs/builder.go rename to packs/builder.go index 2faad75..c5e899b 100644 --- a/core/pkrs/builder.go +++ b/packs/builder.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package pkrs +package packs diff --git a/core/pkrs/err.go b/packs/err_packs.go similarity index 95% rename from core/pkrs/err.go rename to packs/err_packs.go index 4c4bc92..6d9fc1d 100644 --- a/core/pkrs/err.go +++ b/packs/err_packs.go @@ -21,12 +21,12 @@ // limitations under the License. // ------------------------------------------------------------------------ -package pkrs +package packs import "errs" type ( - Err struct { errs.ErrCode } + ErrPacks struct { errs.ErrCode } ) \ No newline at end of file diff --git a/core/pkrs/flags.go b/packs/flags.go similarity index 99% rename from core/pkrs/flags.go rename to packs/flags.go index bc29e6c..11799e1 100644 --- a/core/pkrs/flags.go +++ b/packs/flags.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package pkrs +package packs import ( "bits" diff --git a/core/pkrs/fold.go b/packs/fold.go similarity index 99% rename from core/pkrs/fold.go rename to packs/fold.go index e30c284..a270311 100644 --- a/core/pkrs/fold.go +++ b/packs/fold.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package pkrs +package packs import ( "bins/chars" diff --git a/core/pkrs/go.mod b/packs/go.mod similarity index 100% rename from core/pkrs/go.mod rename to packs/go.mod diff --git a/core/pkrs/list_pack_builder.go b/packs/list_pack_builder.go similarity index 99% rename from core/pkrs/list_pack_builder.go rename to packs/list_pack_builder.go index 57b98f4..a2dc618 100644 --- a/core/pkrs/list_pack_builder.go +++ b/packs/list_pack_builder.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package pkrs +package packs import "time" diff --git a/core/pkrs/map_pack_builder.go b/packs/map_pack_builder.go similarity index 99% rename from core/pkrs/map_pack_builder.go rename to packs/map_pack_builder.go index e28fbbf..b30ccd3 100644 --- a/core/pkrs/map_pack_builder.go +++ b/packs/map_pack_builder.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package pkrs +package packs import "time" diff --git a/core/pkrs/object_pack_builder.go b/packs/object_pack_builder.go similarity index 99% rename from core/pkrs/object_pack_builder.go rename to packs/object_pack_builder.go index 6657bf0..1ac74c0 100644 --- a/core/pkrs/object_pack_builder.go +++ b/packs/object_pack_builder.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package pkrs +package packs import "time" diff --git a/core/pkrs/packer.go b/packs/packer.go similarity index 98% rename from core/pkrs/packer.go rename to packs/packer.go index f8a216a..c1930f1 100644 --- a/core/pkrs/packer.go +++ b/packs/packer.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package pkrs +package packs type ( diff --git a/core/pkrs/pjson/active.go b/packs/pjson/active.go similarity index 94% rename from core/pkrs/pjson/active.go rename to packs/pjson/active.go index 95cc091..7036bb6 100644 --- a/core/pkrs/pjson/active.go +++ b/packs/pjson/active.go @@ -39,7 +39,7 @@ const ( maxCyclesAfter = 100 - defaultFlags = pkrs.Flags(0) + defaultFlags = packs.Flags(0) ) @@ -59,7 +59,7 @@ var ( jsonMarshalerType: reflect.TypeOf((*json.Marshaler)(nil)).Elem(), textMarshalerType: reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem(), - packMarshalerType: reflect.TypeOf((*pkrs.Packer)(nil)).Elem(), + packMarshalerType: reflect.TypeOf((*packs.Packer)(nil)).Elem(), } ) diff --git a/core/pkrs/pjson/json_packer.go b/packs/pjson/json_packer.go similarity index 58% rename from core/pkrs/pjson/json_packer.go rename to packs/pjson/json_packer.go index c3ace5e..b3515fa 100644 --- a/core/pkrs/pjson/json_packer.go +++ b/packs/pjson/json_packer.go @@ -24,7 +24,7 @@ package pjson import ( - "cdcs/cjson" + "cdecs/cjson" "crypts" "encoding/json" "errs" @@ -38,7 +38,7 @@ type ( JSONPacker struct { - state *pkrs.State + state *packs.State dirty bool } @@ -49,7 +49,7 @@ type ( func NewJSONPacker(options ...JSONPackerFnc) *JSONPacker { pk := &JSONPacker{ - state : pkrs.NewState(), + state : packs.NewState(), } for _,o := range options { o(pk) @@ -59,12 +59,12 @@ func NewJSONPacker(options ...JSONPackerFnc) *JSONPacker { -func (p *JSONPacker) Pack (value any, flags pkrs.Flags) { +func (p *JSONPacker) Pack (value any, flags packs.Flags) { if p.state.Error != nil { - panic(pkrs.G.ErrInvalidState.WrapWithCause(p.state.Error)) + panic(packs.G.ErrInvalidState.WrapWithCause(p.state.Error)) } if p.dirty { - panic(pkrs.G.ErrInvalidState) + panic(packs.G.ErrInvalidState) } p.dirty = true p.PackAny(value,flags) @@ -86,14 +86,14 @@ func (p *JSONPacker) Reset () { func (p *JSONPacker) Release () { p.dirty = false - pkrs.ReleaseState(p.state) + packs.ReleaseState(p.state) } -func (p *JSONPacker) PackAny (value any, flags pkrs.Flags) { +func (p *JSONPacker) PackAny (value any, flags packs.Flags) { if p.state.Error != nil { - panic(pkrs.G.ErrInvalidState.WrapWithCause(p.state.Error)) + panic(packs.G.ErrInvalidState.WrapWithCause(p.state.Error)) } if value == nil { p.state.W(cjson.G.NullValue) @@ -101,7 +101,7 @@ func (p *JSONPacker) PackAny (value any, flags pkrs.Flags) { } switch v := value.(type) { - case pkrs.Builder: + case packs.Builder: p.state.SetError(v.Build(p)) case json.Marshaler: @@ -166,45 +166,45 @@ func (p *JSONPacker) PackAny (value any, flags pkrs.Flags) { -func (p *JSONPacker) PackRaw (value []byte, flags pkrs.Flags) { packRaw(p.state,value,flags) } +func (p *JSONPacker) PackRaw (value []byte, flags packs.Flags) { packRaw(p.state,value,flags) } -func (p *JSONPacker) PackBinary (value []byte, flags pkrs.Flags) { packBinary(p.state,value,flags) } -func (p *JSONPacker) PackString (value string, flags pkrs.Flags) { packString (p.state,value,flags) } +func (p *JSONPacker) PackBinary (value []byte, flags packs.Flags) { packBinary(p.state,value,flags) } +func (p *JSONPacker) PackString (value string, flags packs.Flags) { packString (p.state,value,flags) } -func (p *JSONPacker) PackBool (value bool, flags pkrs.Flags) { packBool(p.state,value,flags) } +func (p *JSONPacker) PackBool (value bool, flags packs.Flags) { packBool(p.state,value,flags) } -func (p *JSONPacker) PackInt8 (value int8 , flags pkrs.Flags) { packInt(p.state,int64(value),flags) } -func (p *JSONPacker) PackInt16 (value int16, flags pkrs.Flags) { packInt(p.state,int64(value),flags) } -func (p *JSONPacker) PackInt32 (value int32, flags pkrs.Flags) { packInt(p.state,int64(value),flags) } -func (p *JSONPacker) PackInt64 (value int64, flags pkrs.Flags) { packInt(p.state,value,flags)} +func (p *JSONPacker) PackInt8 (value int8 , flags packs.Flags) { packInt(p.state,int64(value),flags) } +func (p *JSONPacker) PackInt16 (value int16, flags packs.Flags) { packInt(p.state,int64(value),flags) } +func (p *JSONPacker) PackInt32 (value int32, flags packs.Flags) { packInt(p.state,int64(value),flags) } +func (p *JSONPacker) PackInt64 (value int64, flags packs.Flags) { packInt(p.state,value,flags)} -func (p *JSONPacker) PackUInt8 (value uint8 , flags pkrs.Flags) { packUInt(p.state,uint64(value),flags) } -func (p *JSONPacker) PackUInt16 (value uint16, flags pkrs.Flags) { packUInt(p.state,uint64(value),flags) } -func (p *JSONPacker) PackUInt32 (value uint32, flags pkrs.Flags) { packUInt(p.state,uint64(value),flags) } -func (p *JSONPacker) PackUInt64 (value uint64, flags pkrs.Flags) { packUInt(p.state, value,flags) } +func (p *JSONPacker) PackUInt8 (value uint8 , flags packs.Flags) { packUInt(p.state,uint64(value),flags) } +func (p *JSONPacker) PackUInt16 (value uint16, flags packs.Flags) { packUInt(p.state,uint64(value),flags) } +func (p *JSONPacker) PackUInt32 (value uint32, flags packs.Flags) { packUInt(p.state,uint64(value),flags) } +func (p *JSONPacker) PackUInt64 (value uint64, flags packs.Flags) { packUInt(p.state, value,flags) } -func (p *JSONPacker) PackFloat32 (value float32, flags pkrs.Flags) { packFloatString(p.state, float64(value), flags, 32) } -func (p *JSONPacker) PackFloat64 (value float64, flags pkrs.Flags) { packFloatString(p.state, value, flags, 64) } +func (p *JSONPacker) PackFloat32 (value float32, flags packs.Flags) { packFloatString(p.state, float64(value), flags, 32) } +func (p *JSONPacker) PackFloat64 (value float64, flags packs.Flags) { packFloatString(p.state, value, flags, 64) } -func (p *JSONPacker) PackDate (value time.Time, flags pkrs.Flags) { packDate(p.state,value,flags) } +func (p *JSONPacker) PackDate (value time.Time, flags packs.Flags) { packDate(p.state,value,flags) } -func (p *JSONPacker) PackList (builder func(pkrs.ListPackBuilder, pkrs.Flags), flags pkrs.Flags) { - p.packCompound('[',']',builder==nil,func(pk *JSONPacker, fl pkrs.Flags){ builder(pk,fl) },flags) +func (p *JSONPacker) PackList (builder func(packs.ListPackBuilder, packs.Flags), flags packs.Flags) { + p.packCompound('[',']',builder==nil,func(pk *JSONPacker, fl packs.Flags){ builder(pk,fl) },flags) } -func (p *JSONPacker) PackMap (builder func(pkrs.MapPackBuilder, pkrs.Flags), flags pkrs.Flags) { - p.packCompound('{','}',builder==nil,func(pk *JSONPacker, fl pkrs.Flags){ builder(pk,fl) },flags) +func (p *JSONPacker) PackMap (builder func(packs.MapPackBuilder, packs.Flags), flags packs.Flags) { + p.packCompound('{','}',builder==nil,func(pk *JSONPacker, fl packs.Flags){ builder(pk,fl) },flags) } -func (p *JSONPacker) PackObject(builder func(pkrs.ObjectPackBuilder, pkrs.Flags), flags pkrs.Flags) { - p.packCompound('{','}',builder==nil,func(pk *JSONPacker, fl pkrs.Flags){ builder(pk,fl) },flags) +func (p *JSONPacker) PackObject(builder func(packs.ObjectPackBuilder, packs.Flags), flags packs.Flags) { + p.packCompound('{','}',builder==nil,func(pk *JSONPacker, fl packs.Flags){ builder(pk,fl) },flags) } -func (p *JSONPacker) packCompound (opener, closer byte, isnil bool, buildFn func(*JSONPacker, pkrs.Flags), flags pkrs.Flags) { +func (p *JSONPacker) packCompound (opener, closer byte, isnil bool, buildFn func(*JSONPacker, packs.Flags), flags packs.Flags) { if p.state.Error != nil { - panic(pkrs.G.ErrInvalidState.WrapWithCause(p.state.Error)) + panic(packs.G.ErrInvalidState.WrapWithCause(p.state.Error)) } if isnil { p.state.W(cjson.G.NullValue) @@ -229,9 +229,9 @@ func (p *JSONPacker) packCompound (opener, closer byte, isnil bool, buildFn func -func packRaw (state *pkrs.State, value []byte, flags pkrs.Flags) { +func packRaw (state *packs.State, value []byte, flags packs.Flags) { if state.Error != nil { - panic(pkrs.G.ErrInvalidState.WrapWithCause(state.Error)) + panic(packs.G.ErrInvalidState.WrapWithCause(state.Error)) } if value == nil { state.W(cjson.G.NullValue) @@ -244,9 +244,9 @@ func packRaw (state *pkrs.State, value []byte, flags pkrs.Flags) { state.WOQ(flags.Quote(),'"',value) } -func packString (state *pkrs.State, value string , flags pkrs.Flags) { +func packString (state *packs.State, value string , flags packs.Flags) { if state.Error != nil { - panic(pkrs.G.ErrInvalidState.WrapWithCause(state.Error)) + panic(packs.G.ErrInvalidState.WrapWithCause(state.Error)) } if len(value) == 0 { @@ -255,7 +255,7 @@ func packString (state *pkrs.State, value string , flags pkrs.Flags) { } if flags.Encrypted() { - packEncrypted(state, []byte(value), flags|pkrs.FlagBinary64) + packEncrypted(state, []byte(value), flags|packs.FlagBinary64) return } @@ -264,11 +264,11 @@ func packString (state *pkrs.State, value string , flags pkrs.Flags) { return } - cjson.WriteString(state.Buffer,value,flags.EscapeHTML()) + cjson.WriteString(state.ABuffer,value,flags.EscapeHTML()) } -func packEncrypted (state *pkrs.State, value []byte, flags pkrs.Flags) { +func packEncrypted (state *packs.State, value []byte, flags packs.Flags) { r := state.Encrypter.Encrypt(value) if !r.Ok() { state.SetError(r.Fail()) @@ -276,70 +276,70 @@ func packEncrypted (state *pkrs.State, value []byte, flags pkrs.Flags) { } if !flags.Binary() { - flags|=pkrs.FlagBinary64 + flags|= packs.FlagBinary64 } packBinary(state,value,flags) } -func packBinary (state *pkrs.State, value []byte , flags pkrs.Flags) { +func packBinary (state *packs.State, value []byte , flags packs.Flags) { if state.Error != nil { - panic(pkrs.G.ErrInvalidState.WrapWithCause(state.Error)) + panic(packs.G.ErrInvalidState.WrapWithCause(state.Error)) } if flags.Bin64() { - state.SetError(cjson.WriteBase64(state.Buffer,value)) + state.SetError(cjson.WriteBase64(state.ABuffer,value)) return } if flags.Bin32() { - state.SetError(cjson.WriteBase32(state.Buffer,value)) + state.SetError(cjson.WriteBase32(state.ABuffer,value)) return } - state.SetError(pkrs.G.ErrUnsupportedType) + state.SetError(packs.G.ErrUnsupportedType) } -func packBool (state *pkrs.State, value bool , flags pkrs.Flags) { +func packBool (state *packs.State, value bool , flags packs.Flags) { if state.Error != nil { - panic(pkrs.G.ErrInvalidState.WrapWithCause(state.Error)) + panic(packs.G.ErrInvalidState.WrapWithCause(state.Error)) } - cjson.WriteBool(state.Buffer,value,flags.Quote()) + cjson.WriteBool(state.ABuffer,value,flags.Quote()) } -func packInt (state *pkrs.State, value int64 , flags pkrs.Flags) { +func packInt (state *packs.State, value int64 , flags packs.Flags) { if state.Error != nil { - panic(pkrs.G.ErrInvalidState.WrapWithCause(state.Error)) + panic(packs.G.ErrInvalidState.WrapWithCause(state.Error)) } - cjson.WriteInt(state.Buffer,value,flags.Quote()) + cjson.WriteInt(state.ABuffer,value,flags.Quote()) } -func packUInt (state *pkrs.State, value uint64 , flags pkrs.Flags) { +func packUInt (state *packs.State, value uint64 , flags packs.Flags) { if state.Error != nil { - panic(pkrs.G.ErrInvalidState.WrapWithCause(state.Error)) + panic(packs.G.ErrInvalidState.WrapWithCause(state.Error)) } - cjson.WriteUint(state.Buffer,value,flags.Quote()) + cjson.WriteUint(state.ABuffer,value,flags.Quote()) } -func packFloat (state *pkrs.State, value float64, flags pkrs.Flags) { +func packFloat (state *packs.State, value float64, flags packs.Flags) { packFloatString(state, value, flags, 64) } -func packFloatString (state *pkrs.State, f float64, flags pkrs.Flags, bits int) { +func packFloatString (state *packs.State, f float64, flags packs.Flags, bits int) { if state.Error != nil { - panic(pkrs.G.ErrInvalidState.WrapWithCause(state.Error)) + panic(packs.G.ErrInvalidState.WrapWithCause(state.Error)) } - cjson.WriteFloat(state.Buffer,f,bits,flags.Quote()) + cjson.WriteFloat(state.ABuffer,f,bits,flags.Quote()) } -func packDate(state *pkrs.State, value time.Time, flags pkrs.Flags) { +func packDate(state *packs.State, value time.Time, flags packs.Flags) { if state.Error != nil { - panic(pkrs.G.ErrInvalidState.WrapWithCause(state.Error)) + panic(packs.G.ErrInvalidState.WrapWithCause(state.Error)) } - cjson.WriteDate(state.Buffer,value,flags.DateFormat(),true) + cjson.WriteDate(state.ABuffer,value,flags.DateFormat(),true) } @@ -347,7 +347,7 @@ func packDate(state *pkrs.State, value time.Time, flags pkrs.Flags) { -func packListString (state *pkrs.State, list []string, flags pkrs.Flags) { +func packListString (state *packs.State, list []string, flags packs.Flags) { if !checkList(state,list == nil, len(list) ==0) { return } @@ -365,7 +365,7 @@ func packListString (state *pkrs.State, list []string, flags pkrs.Flags) { } -func packListBool (state *pkrs.State, list []bool, flags pkrs.Flags) { +func packListBool (state *packs.State, list []bool, flags packs.Flags) { if !checkList(state,list == nil, len(list) ==0) { return } @@ -383,7 +383,7 @@ func packListBool (state *pkrs.State, list []bool, flags pkrs.Flags) { } -func packListInt [T int | int8 | int16 | int32 | int64](state *pkrs.State, list []T, flags pkrs.Flags) { +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 } @@ -401,7 +401,7 @@ func packListInt [T int | int8 | int16 | int32 | int64](state *pkrs.State, list } -func packListUInt [T uint | uint8 | uint16 | uint32 | uint64](state *pkrs.State, list []T, flags pkrs.Flags) { +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 } @@ -419,7 +419,7 @@ func packListUInt [T uint | uint8 | uint16 | uint32 | uint64](state *pkrs.State, } -func packListFloat[T float32 | float64](state *pkrs.State, list []T, flags pkrs.Flags, bits int) { +func packListFloat[T float32 | float64](state *packs.State, list []T, flags packs.Flags, bits int) { if !checkList(state,list == nil, len(list) ==0) { return } @@ -436,7 +436,7 @@ func packListFloat[T float32 | float64](state *pkrs.State, list []T, flags pkrs. state.WriteByte(']') } -func packListDate (state *pkrs.State, list []time.Time, flags pkrs.Flags) { +func packListDate (state *packs.State, list []time.Time, flags packs.Flags) { if !checkList(state,list == nil, len(list) ==0) { return } @@ -454,7 +454,7 @@ func packListDate (state *pkrs.State, list []time.Time, flags pkrs.Flags) { } -func checkList (state *pkrs.State, isNull, isEmpty bool) bool { +func checkList (state *packs.State, isNull, isEmpty bool) bool { if isNull { state.Write2Byte('"','"') return false diff --git a/packs/pjson/list_pack_builder.go b/packs/pjson/list_pack_builder.go new file mode 100644 index 0000000..332a8ff --- /dev/null +++ b/packs/pjson/list_pack_builder.go @@ -0,0 +1,80 @@ +// ------------------------------------------------------------------------ +// Project atila +// Active Thing (activething.com) git.activething.com/go +// +// File name builder_list.go +// Created by DEV +// Modified 06/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 pjson + +import ( + "packs" + "time" +) + +func (p *JSONPacker) ItemAny (value any, flags packs.Flags) { p.addItem(func(){ p.PackAny(value,flags) }) } + + +func (p *JSONPacker) ItemRaw (value []byte, flags packs.Flags) { p.addItem(func() { p.PackRaw(value,flags) }) } + +func (p *JSONPacker) ItemBinary (value []byte, flags packs.Flags) { p.addItem(func (){ p.PackBinary(value,flags) }) } + +func (p *JSONPacker) ItemString (value string, flags packs.Flags) { p.addItem(func (){ p.PackString(value,flags) }) } + + +func (p *JSONPacker) ItemBool (value bool, flags packs.Flags) { p.addItem(func (){ p.PackBool(value,flags) }) } + +func (p *JSONPacker) ItemInt8 (value int8 , flags packs.Flags) { p.addItem(func (){ packInt(p.state,int64(value),flags) }) } +func (p *JSONPacker) ItemInt16 (value int16, flags packs.Flags) { p.addItem(func (){ packInt(p.state,int64(value),flags) }) } +func (p *JSONPacker) ItemInt32 (value int32, flags packs.Flags) { p.addItem(func (){ packInt(p.state,int64(value),flags) }) } +func (p *JSONPacker) ItemInt64 (value int64, flags packs.Flags) { p.addItem(func (){ packInt(p.state,value,flags) }) } + +func (p *JSONPacker) ItemUInt8 (value uint8 , flags packs.Flags){ p.addItem(func (){ packUInt(p.state,uint64(value),flags) }) } +func (p *JSONPacker) ItemUInt16 (value uint16, flags packs.Flags){ p.addItem(func (){ packUInt(p.state,uint64(value),flags) }) } +func (p *JSONPacker) ItemUInt32 (value uint32, flags packs.Flags){ p.addItem(func (){ packUInt(p.state,uint64(value),flags) }) } +func (p *JSONPacker) ItemUInt64 (value uint64, flags packs.Flags){ p.addItem(func (){ packUInt(p.state,uint64(value),flags) }) } + +func (p *JSONPacker) ItemFloat32 (value float32, flags packs.Flags){ p.addItem(func (){ packFloatString(p.state,float64(value),flags,32)})} +func (p *JSONPacker) ItemFloat64 (value float64, flags packs.Flags){ p.addItem(func (){ packFloatString(p.state,value,flags,64) })} + +func (p *JSONPacker) ItemDate (value time.Time, flags packs.Flags) { p.addItem(func(){ packDate(p.state,value,flags); p.state.Inc() })} + + +func (p *JSONPacker) ItemList (builder func(packs.ListPackBuilder, packs.Flags), flags packs.Flags) { + p.addItem(func(){ p.PackList(builder,flags) }) } + +func (p *JSONPacker) ItemMap (builder func(packs.MapPackBuilder, packs.Flags), flags packs.Flags) { + p.addItem(func(){ p.PackMap(builder,flags) }) } + +func (p *JSONPacker) ItemObject(builder func(packs.ObjectPackBuilder, packs.Flags), flags packs.Flags) { + p.addItem(func(){ p.PackObject(builder,flags) }) } + + + +func (p *JSONPacker) addItem (caller func()) { + if p.state.Count() > 0 { + p.state.WriteByte(',') + } + caller() + if p.state != nil { + p.state.Inc() + } +} + + diff --git a/core/pkrs/pjson/map_pack_builder.go b/packs/pjson/map_pack_builder.go similarity index 69% rename from core/pkrs/pjson/map_pack_builder.go rename to packs/pjson/map_pack_builder.go index 161a678..0c3898d 100644 --- a/core/pkrs/pjson/map_pack_builder.go +++ b/packs/pjson/map_pack_builder.go @@ -29,51 +29,51 @@ import ( "time" ) -func (p *JSONPacker) KeyValueAny (key any, value any, flags pkrs.Flags) { +func (p *JSONPacker) KeyValueAny (key any, value any, flags packs.Flags) { p.addKeyValue(key, func(){ p.PackAny(value,flags)}) } -func (p *JSONPacker) KeyValueRaw (key any,value []byte, flags pkrs.Flags) { +func (p *JSONPacker) KeyValueRaw (key any,value []byte, flags packs.Flags) { p.addKeyValue(key, func(){ p.PackRaw(value,flags)}) } -func (p *JSONPacker) KeyValueBinary (key any, value []byte, flags pkrs.Flags) { +func (p *JSONPacker) KeyValueBinary (key any, value []byte, flags packs.Flags) { p.addKeyValue(key, func(){ p.PackBinary(value,flags)}) } -func (p *JSONPacker) KeyValueString (key any, value string, flags pkrs.Flags) { +func (p *JSONPacker) KeyValueString (key any, value string, flags packs.Flags) { p.addKeyValue(key, func(){ p.PackString(value,flags)}) } -func (p *JSONPacker) KeyValueBool (key any, value bool, flags pkrs.Flags) { +func (p *JSONPacker) KeyValueBool (key any, value bool, flags packs.Flags) { p.addKeyValue(key, func(){ p.PackBool(value,flags)}) } -func (p *JSONPacker) KeyValueInt8 (key any, value int8 , flags pkrs.Flags) { p.addKeyValue(key, func(){ p.PackInt64(int64(value),flags)}) } -func (p *JSONPacker) KeyValueInt16 (key any, value int16, flags pkrs.Flags) { p.addKeyValue(key, func(){ p.PackInt64(int64(value),flags)}) } -func (p *JSONPacker) KeyValueInt32 (key any, value int32, flags pkrs.Flags) { p.addKeyValue(key, func(){ p.PackInt64(int64(value),flags)}) } -func (p *JSONPacker) KeyValueInt64 (key any, value int64, flags pkrs.Flags) { p.addKeyValue(key, func(){ p.PackInt64(value,flags)}) } +func (p *JSONPacker) KeyValueInt8 (key any, value int8 , flags packs.Flags) { p.addKeyValue(key, func(){ p.PackInt64(int64(value),flags)}) } +func (p *JSONPacker) KeyValueInt16 (key any, value int16, flags packs.Flags) { p.addKeyValue(key, func(){ p.PackInt64(int64(value),flags)}) } +func (p *JSONPacker) KeyValueInt32 (key any, value int32, flags packs.Flags) { p.addKeyValue(key, func(){ p.PackInt64(int64(value),flags)}) } +func (p *JSONPacker) KeyValueInt64 (key any, value int64, flags packs.Flags) { p.addKeyValue(key, func(){ p.PackInt64(value,flags)}) } -func (p *JSONPacker) KeyValueUInt8 (key any, value uint8 , flags pkrs.Flags) { p.addKeyValue(key, func(){ p.PackUInt64(uint64(value),flags)}) } -func (p *JSONPacker) KeyValueUInt16 (key any, value uint16, flags pkrs.Flags) { p.addKeyValue(key, func(){ p.PackUInt64(uint64(value),flags)}) } -func (p *JSONPacker) KeyValueUInt32 (key any, value uint32, flags pkrs.Flags) { p.addKeyValue(key, func(){ p.PackUInt64(uint64(value),flags)}) } -func (p *JSONPacker) KeyValueUInt64 (key any, value uint64, flags pkrs.Flags) { p.addKeyValue(key, func(){ p.PackUInt64(value,flags)}) } +func (p *JSONPacker) KeyValueUInt8 (key any, value uint8 , flags packs.Flags) { p.addKeyValue(key, func(){ p.PackUInt64(uint64(value),flags)}) } +func (p *JSONPacker) KeyValueUInt16 (key any, value uint16, flags packs.Flags) { p.addKeyValue(key, func(){ p.PackUInt64(uint64(value),flags)}) } +func (p *JSONPacker) KeyValueUInt32 (key any, value uint32, flags packs.Flags) { p.addKeyValue(key, func(){ p.PackUInt64(uint64(value),flags)}) } +func (p *JSONPacker) KeyValueUInt64 (key any, value uint64, flags packs.Flags) { p.addKeyValue(key, func(){ p.PackUInt64(value,flags)}) } -func (p *JSONPacker) KeyValueFloat32(key any, value float32, flags pkrs.Flags){ +func (p *JSONPacker) KeyValueFloat32(key any, value float32, flags packs.Flags){ p.addKeyValue(key,func(){ p.PackFloat32(value, flags) }) } -func (p *JSONPacker) KeyValueFloat64(key any, value float64, flags pkrs.Flags){ +func (p *JSONPacker) KeyValueFloat64(key any, value float64, flags packs.Flags){ p.addKeyValue(key,func(){ p.PackFloat64(value, flags) }) } -func (p *JSONPacker) KeyValueDate (key any, value time.Time, flags pkrs.Flags){ +func (p *JSONPacker) KeyValueDate (key any, value time.Time, flags packs.Flags){ p.addKeyValue(key,func(){ p.PackDate(value, flags) }) } -func (p *JSONPacker) KeyValueList (key any, builder func(pkrs.ListPackBuilder, pkrs.Flags), flags pkrs.Flags) { +func (p *JSONPacker) KeyValueList (key any, builder func(packs.ListPackBuilder, packs.Flags), flags packs.Flags) { p.addKeyValue(key,func(){ p.PackList(builder, flags) }) } -func (p *JSONPacker) KeyValueMap (key any, builder func(pkrs.MapPackBuilder, pkrs.Flags), flags pkrs.Flags) { +func (p *JSONPacker) KeyValueMap (key any, builder func(packs.MapPackBuilder, packs.Flags), flags packs.Flags) { p.addKeyValue(key,func(){ p.PackMap(builder, flags) }) } -func (p *JSONPacker) KeyValueObject (key any, builder func(pkrs.ObjectPackBuilder, pkrs.Flags), flags pkrs.Flags) { +func (p *JSONPacker) KeyValueObject (key any, builder func(packs.ObjectPackBuilder, packs.Flags), flags packs.Flags) { p.addKeyValue(key,func(){ p.PackObject(builder, flags) }) } @@ -94,16 +94,16 @@ func (p *JSONPacker) addKeyValue(key any, caller func()) { func (p *JSONPacker) packStringifyKey(key any) { switch v := key.(type) { - case string : p.PackString(v, pkrs.FlagScapeHTML) - case float32: p.PackFloat32(v, pkrs.FlagScapeHTML|pkrs.FlagQuote) - case float64: p.PackFloat64(v, pkrs.FlagScapeHTML|pkrs.FlagQuote) + case string : p.PackString(v, packs.FlagScapeHTML) + case float32: p.PackFloat32(v, packs.FlagScapeHTML|packs.FlagQuote) + case float64: p.PackFloat64(v, packs.FlagScapeHTML|packs.FlagQuote) default: me := &rMapEntry{ v : reflect.ValueOf(key), } fn := stringifyRKey(me.v.Type()) if fn == nil { - p.state.SetError(pkrs.G.ErrInvalidKey) + p.state.SetError(packs.G.ErrInvalidKey) return } if er := fn(me,me.v); er != nil { diff --git a/core/pkrs/pjson/object_pack_builder.go b/packs/pjson/object_pack_builder.go similarity index 83% rename from core/pkrs/pjson/object_pack_builder.go rename to packs/pjson/object_pack_builder.go index 5f33c67..48439e2 100644 --- a/core/pkrs/pjson/object_pack_builder.go +++ b/packs/pjson/object_pack_builder.go @@ -28,71 +28,71 @@ import ( "time" ) -func (p *JSONPacker) FieldAny (name string, value any, flags pkrs.Flags) { +func (p *JSONPacker) FieldAny (name string, value any, flags packs.Flags) { p.addField(name, func() { p.PackAny(value, flags) }) } -func (p *JSONPacker) FieldRaw (name string, value []byte, flags pkrs.Flags){ +func (p *JSONPacker) FieldRaw (name string, value []byte, flags packs.Flags){ p.addField(name, func() { p.PackRaw(value, flags) }) } -func (p *JSONPacker) FieldBinary (name string, value []byte, flags pkrs.Flags) { +func (p *JSONPacker) FieldBinary (name string, value []byte, flags packs.Flags) { p.addField(name, func() { p.PackBinary(value, flags) }) } -func (p *JSONPacker) FieldString (name string, value string, flags pkrs.Flags) { +func (p *JSONPacker) FieldString (name string, value string, flags packs.Flags) { p.addField(name, func() { p.PackString(value, flags) }) } -func (p *JSONPacker) FieldBool (name string, value bool, flags pkrs.Flags) { +func (p *JSONPacker) FieldBool (name string, value bool, flags packs.Flags) { p.addField(name, func() { p.PackBool(value, flags) }) } -func (p *JSONPacker) FieldInt8 (name string, value int8 , flags pkrs.Flags) { +func (p *JSONPacker) FieldInt8 (name string, value int8 , flags packs.Flags) { p.addField(name, func() { p.PackInt64(int64(value), flags) })} -func (p *JSONPacker) FieldInt16 (name string, value int16, flags pkrs.Flags) { +func (p *JSONPacker) FieldInt16 (name string, value int16, flags packs.Flags) { p.addField(name, func() { p.PackInt64(int64(value), flags) })} -func (p *JSONPacker) FieldInt32 (name string, value int32, flags pkrs.Flags) { +func (p *JSONPacker) FieldInt32 (name string, value int32, flags packs.Flags) { p.addField(name, func() { p.PackInt64(int64(value), flags) }) } -func (p *JSONPacker) FieldInt64 (name string, value int64, flags pkrs.Flags) { +func (p *JSONPacker) FieldInt64 (name string, value int64, flags packs.Flags) { p.addField(name, func() { p.PackInt64(value, flags) }) } -func (p *JSONPacker) FieldUInt8 (name string, value uint8, flags pkrs.Flags) { +func (p *JSONPacker) FieldUInt8 (name string, value uint8, flags packs.Flags) { p.addField(name, func() { p.PackUInt64(uint64(value), flags) }) } -func (p *JSONPacker) FieldUInt16 (name string, value uint16, flags pkrs.Flags) { +func (p *JSONPacker) FieldUInt16 (name string, value uint16, flags packs.Flags) { p.addField(name,func(){ p.PackUInt64(uint64(value), flags) }) } -func (p *JSONPacker) FieldUInt32 (name string, value uint32, flags pkrs.Flags) { +func (p *JSONPacker) FieldUInt32 (name string, value uint32, flags packs.Flags) { p.addField(name,func(){ p.PackUInt64(uint64(value), flags) }) } -func (p *JSONPacker) FieldUInt64 (name string, value uint64, flags pkrs.Flags) { +func (p *JSONPacker) FieldUInt64 (name string, value uint64, flags packs.Flags) { p.addField(name,func(){ p.PackUInt64(value, flags) }) } -func (p *JSONPacker) FieldFloat32(name string, value float32,flags pkrs.Flags) { +func (p *JSONPacker) FieldFloat32(name string, value float32,flags packs.Flags) { p.addField(name,func(){ p.PackFloat32(value, flags) }) } -func (p *JSONPacker) FieldFloat64(name string, value float64,flags pkrs.Flags) { +func (p *JSONPacker) FieldFloat64(name string, value float64,flags packs.Flags) { p.addField(name,func(){ p.PackFloat64(value, flags) }) } -func (p *JSONPacker) FieldDate (name string, value time.Time,flags pkrs.Flags) { +func (p *JSONPacker) FieldDate (name string, value time.Time,flags packs.Flags) { p.addField(name,func(){ p.PackDate(value, flags) }) } -func (p *JSONPacker) FieldList (name string, builder func(pkrs.ListPackBuilder, pkrs.Flags), flags pkrs.Flags) { +func (p *JSONPacker) FieldList (name string, builder func(packs.ListPackBuilder, packs.Flags), flags packs.Flags) { p.addField(name,func(){ p.PackList(builder, flags) }) } -func (p *JSONPacker) FieldMap (name string, builder func(pkrs.MapPackBuilder, pkrs.Flags), flags pkrs.Flags) { +func (p *JSONPacker) FieldMap (name string, builder func(packs.MapPackBuilder, packs.Flags), flags packs.Flags) { p.addField(name,func(){ p.PackMap(builder, flags) }) } -func (p *JSONPacker) FieldObject (name string, builder func(pkrs.ObjectPackBuilder, pkrs.Flags), flags pkrs.Flags) { +func (p *JSONPacker) FieldObject (name string, builder func(packs.ObjectPackBuilder, packs.Flags), flags packs.Flags) { p.addField(name,func(){ p.PackObject(builder, flags) }) } @@ -102,7 +102,7 @@ func (p *JSONPacker) addField(name string, caller func()) { if p.state.Count() > 0 { p.state.WriteByte(',') } - packString(p.state,name, pkrs.FlagScapeHTML) + packString(p.state,name, packs.FlagScapeHTML) if p.state.Error != nil { return } diff --git a/core/pkrs/pjson/rpacker.go b/packs/pjson/rpacker.go similarity index 67% rename from core/pkrs/pjson/rpacker.go rename to packs/pjson/rpacker.go index 8a81e29..321d322 100644 --- a/core/pkrs/pjson/rpacker.go +++ b/packs/pjson/rpacker.go @@ -33,7 +33,7 @@ type ( - rPackerFnc func (state *pkrs.State, rvalue reflect.Value, flags pkrs.Flags) + rPackerFnc func (state *packs.State, rvalue reflect.Value, flags packs.Flags) ) @@ -49,7 +49,7 @@ func rTypePacker (rtype reflect.Type) rPackerFnc { wg.Add(1) - fi,ld := g.packersCache.LoadOrStore(rtype, rPackerFnc(func (e *pkrs.State, v reflect.Value, f pkrs.Flags) { + fi,ld := g.packersCache.LoadOrStore(rtype, rPackerFnc(func (e *packs.State, v reflect.Value, f packs.Flags) { wg.Wait() fn(e,v,f) })) @@ -68,20 +68,20 @@ func rTypePacker (rtype reflect.Type) rPackerFnc { func _rTypePacker(rtype reflect.Type) rPackerFnc { switch rtype.Kind() { - case reflect.Bool : return func(s *pkrs.State, v reflect.Value, f pkrs.Flags) { packBool (s,v.Bool (),f )} - case reflect.String : return func(s *pkrs.State, v reflect.Value, f pkrs.Flags) { packString(s,v.String(),f )} + case reflect.Bool : return func(s *packs.State, v reflect.Value, f packs.Flags) { packBool (s,v.Bool (),f )} + case reflect.String : return func(s *packs.State, v reflect.Value, f packs.Flags) { packString(s,v.String(),f )} case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, - reflect.Int64 : return func(s *pkrs.State, v reflect.Value, f pkrs.Flags) { packInt (s,v.Int (),f )} + reflect.Int64 : return func(s *packs.State, v reflect.Value, f packs.Flags) { packInt (s,v.Int (),f )} case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, - reflect.Uint64 : return func(s *pkrs.State, v reflect.Value, f pkrs.Flags) { packUInt (s,v.Uint (),f )} - case reflect.Float32: return func(s *pkrs.State, v reflect.Value, f pkrs.Flags) { packFloatString(s,v.Float(),f,32) } - case reflect.Float64: return func(s *pkrs.State, v reflect.Value, f pkrs.Flags) { packFloatString(s,v.Float(),f,64) } + reflect.Uint64 : return func(s *packs.State, v reflect.Value, f packs.Flags) { packUInt (s,v.Uint (),f )} + case reflect.Float32: return func(s *packs.State, v reflect.Value, f packs.Flags) { packFloatString(s,v.Float(),f,32) } + case reflect.Float64: return func(s *packs.State, v reflect.Value, f packs.Flags) { packFloatString(s,v.Float(),f,64) } case reflect.Pointer: return rPointerPacker(rtype) @@ -106,8 +106,8 @@ func _rTypePacker(rtype reflect.Type) rPackerFnc { } -func unsupportedTypePacker(state *pkrs.State, _ reflect.Value, _ pkrs.Flags) { - state.SetError(pkrs.G.ErrUnsupportedType) +func unsupportedTypePacker(state *packs.State, _ reflect.Value, _ packs.Flags) { + state.SetError(packs.G.ErrUnsupportedType) } diff --git a/core/pkrs/pjson/rpacker_interface.go b/packs/pjson/rpacker_interface.go similarity index 92% rename from core/pkrs/pjson/rpacker_interface.go rename to packs/pjson/rpacker_interface.go index 350534f..addee14 100644 --- a/core/pkrs/pjson/rpacker_interface.go +++ b/packs/pjson/rpacker_interface.go @@ -24,12 +24,12 @@ package pjson import ( - "cdcs/cjson" + "cdecs/cjson" "packs" "reflect" ) -func rInterfacePacker (s *pkrs.State, v reflect.Value, f pkrs.Flags) { +func rInterfacePacker (s *packs.State, v reflect.Value, f packs.Flags) { if v.IsNil() { s.W(cjson.G.NullValue) return diff --git a/core/pkrs/pjson/rpacker_key.go b/packs/pjson/rpacker_key.go similarity index 95% rename from core/pkrs/pjson/rpacker_key.go rename to packs/pjson/rpacker_key.go index 1b549a2..beb889e 100644 --- a/core/pkrs/pjson/rpacker_key.go +++ b/packs/pjson/rpacker_key.go @@ -45,7 +45,7 @@ func _stringifyRKey(rt reflect.Type) rMapEntryFnc { if rt.Kind() == reflect.String { return func(e *rMapEntry, k reflect.Value) error { e.k = k.String() - e.f = pkrs.FlagScapeHTML + e.f = packs.FlagScapeHTML return nil } } @@ -58,7 +58,7 @@ func _stringifyRKey(rt reflect.Type) rMapEntryFnc { bf, er := (k.Interface().(encoding.TextMarshaler)).MarshalText() if er == nil { e.k = string(bf) - e.f = pkrs.FlagScapeHTML + e.f = packs.FlagScapeHTML } return er } @@ -92,7 +92,7 @@ func _stringifyRKey(rt reflect.Type) rMapEntryFnc { if k.Type().Kind() == reflect.String { e.k = k.String() - e.f = pkrs.FlagScapeHTML + e.f = packs.FlagScapeHTML return nil } @@ -103,7 +103,7 @@ func _stringifyRKey(rt reflect.Type) rMapEntryFnc { bf, er := t.MarshalText() if er == nil { e.k = string(bf) - e.f = pkrs.FlagScapeHTML + e.f = packs.FlagScapeHTML } return er } @@ -128,7 +128,7 @@ func _stringifyRKey(rt reflect.Type) rMapEntryFnc { return nil default: - return pkrs.G.ErrInvalidKey + return packs.G.ErrInvalidKey } } diff --git a/core/pkrs/pjson/rpacker_list.go b/packs/pjson/rpacker_list.go similarity index 86% rename from core/pkrs/pjson/rpacker_list.go rename to packs/pjson/rpacker_list.go index 11a3ff9..c75c453 100644 --- a/core/pkrs/pjson/rpacker_list.go +++ b/packs/pjson/rpacker_list.go @@ -24,7 +24,7 @@ package pjson import ( - "cdcs/cjson" + "cdecs/cjson" "packs" "reflect" ) @@ -58,7 +58,7 @@ func newRList(rtype reflect.Type) *rList { -func (p rList) packBinary (s *pkrs.State, v reflect.Value, f pkrs.Flags) { +func (p rList) packBinary (s *packs.State, v reflect.Value, f packs.Flags) { if f.Binary() { packBinary(s, v.Interface().([]byte), f) return @@ -67,7 +67,7 @@ func (p rList) packBinary (s *pkrs.State, v reflect.Value, f pkrs.Flags) { } -func (p rList) packBinarySlice (s *pkrs.State, v reflect.Value, f pkrs.Flags) { +func (p rList) packBinarySlice (s *packs.State, v reflect.Value, f packs.Flags) { if f.Binary() { packBinary(s, v.Interface().([]byte), f) return @@ -78,7 +78,7 @@ func (p rList) packBinarySlice (s *pkrs.State, v reflect.Value, f pkrs.Flags) { -func (p rList) packSlice(s *pkrs.State, v reflect.Value, f pkrs.Flags) { +func (p rList) packSlice(s *packs.State, v reflect.Value, f packs.Flags) { if v.IsNil() { s.W(cjson.G.NullValue) return @@ -95,7 +95,7 @@ func (p rList) packSlice(s *pkrs.State, v reflect.Value, f pkrs.Flags) { if fn,ok := s.CheckCycle(cp); ok { defer fn() } else { - s.SetError(pkrs.G.ErrRedundantPack) + s.SetError(packs.G.ErrRedundantPack) return } } @@ -105,7 +105,7 @@ func (p rList) packSlice(s *pkrs.State, v reflect.Value, f pkrs.Flags) { -func (p rList) pack (s *pkrs.State, v reflect.Value, f pkrs.Flags) { +func (p rList) pack (s *packs.State, v reflect.Value, f packs.Flags) { if v.IsNil() { s.W(cjson.G.NullValue) return diff --git a/core/pkrs/pjson/rpacker_map.go b/packs/pjson/rpacker_map.go similarity index 92% rename from core/pkrs/pjson/rpacker_map.go rename to packs/pjson/rpacker_map.go index d54c48b..85ce778 100644 --- a/core/pkrs/pjson/rpacker_map.go +++ b/packs/pjson/rpacker_map.go @@ -24,7 +24,7 @@ package pjson import ( - "cdcs/cjson" + "cdecs/cjson" "packs" "reflect" "sort" @@ -53,9 +53,9 @@ func newRMap(rtype reflect.Type) *rMap { } -func (p *rMap) pack (s *pkrs.State, v reflect.Value, f pkrs.Flags) { +func (p *rMap) pack (s *packs.State, v reflect.Value, f packs.Flags) { if p.keyFn == nil { - s.SetError(pkrs.G.ErrInvalidKey) + s.SetError(packs.G.ErrInvalidKey) return } @@ -72,7 +72,7 @@ func (p *rMap) pack (s *pkrs.State, v reflect.Value, f pkrs.Flags) { if fn,ok := s.CheckCycle(v.UnsafePointer()); ok { defer fn() } else { - s.SetError(pkrs.G.ErrRedundantPack) + s.SetError(packs.G.ErrRedundantPack) return } } diff --git a/core/pkrs/pjson/rpacker_map_entry.go b/packs/pjson/rpacker_map_entry.go similarity index 98% rename from core/pkrs/pjson/rpacker_map_entry.go rename to packs/pjson/rpacker_map_entry.go index 7013668..75f3d56 100644 --- a/core/pkrs/pjson/rpacker_map_entry.go +++ b/packs/pjson/rpacker_map_entry.go @@ -32,7 +32,7 @@ type ( rMapEntry struct { - f pkrs.Flags // flags + f packs.Flags // flags v reflect.Value // value k string // Key } diff --git a/core/pkrs/pjson/rpacker_object.go b/packs/pjson/rpacker_object.go similarity index 90% rename from core/pkrs/pjson/rpacker_object.go rename to packs/pjson/rpacker_object.go index b0a74f0..f507b77 100644 --- a/core/pkrs/pjson/rpacker_object.go +++ b/packs/pjson/rpacker_object.go @@ -24,7 +24,7 @@ package pjson import ( - "bins/bfers" + "bins/mems" "packs" "reflect" "sort" @@ -46,7 +46,7 @@ func rObjectPacker (rtype reflect.Type) rPackerFnc { if !ok { op,_ = g.fieldsCache.LoadOrStore(rtype,*newRObject(rtype)) } - return func(s *pkrs.State, value reflect.Value, flags pkrs.Flags) { + return func(s *packs.State, value reflect.Value, flags packs.Flags) { op.(rObject).pack(s,value,flags) } //return (op.(rObject)).pack @@ -60,7 +60,7 @@ func newRObject(rtype reflect.Type) *rObject { var fls rFieldList var cnt, nxCnt map[reflect.Type]int vis := map[reflect.Type]bool{} - nms := bfers.NewBuffer() + nms := mems.NewABuffer() for len(nxt) > 0 { cur,nxt = nxt,cur[:0] @@ -85,7 +85,7 @@ func newRObject(rtype reflect.Type) *rObject { continue } - nm, fg, has := pkrs.FlagsFromPackTag(sf.Tag) + nm, fg, has := packs.FlagsFromPackTag(sf.Tag) if !has { nm, fg, has = jsonTags(sf.Tag) } @@ -93,7 +93,7 @@ func newRObject(rtype reflect.Type) *rObject { if nm == "-" || fg.Omit() { continue } - if !pkrs.CheckTag(nm) { + if !packs.CheckTag(nm) { nm = "" } } @@ -114,7 +114,7 @@ func newRObject(rtype reflect.Type) *rObject { reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.String: - fg = fg| pkrs.FlagQuote + fg = fg| packs.FlagQuote } } @@ -131,7 +131,7 @@ func newRObject(rtype reflect.Type) *rObject { flags : fg, } of.nameB = []byte(of.name) - of.foldFn= pkrs.GetFoldFunc(of.nameB) + of.foldFn= packs.GetFoldFunc(of.nameB) // Build nameEscHTML and nameNonEsc ahead of time. nms.Reset() @@ -211,7 +211,7 @@ func newRObject(rtype reflect.Type) *rObject { -func (o rObject) pack (s *pkrs.State, v reflect.Value, f pkrs.Flags) { +func (o rObject) pack (s *packs.State, v reflect.Value, f packs.Flags) { nx := byte('{') FieldLoop: for i:= range o.fields { @@ -248,11 +248,11 @@ FieldLoop: } -func jsonTags (tag reflect.StructTag) (string, pkrs.Flags,bool) { - return pkrs.FlagsFromTag(tag,jsonTag,func(n string) pkrs.Flags { +func jsonTags (tag reflect.StructTag) (string, packs.Flags,bool) { + return packs.FlagsFromTag(tag,jsonTag,func(n string) packs.Flags { switch n { - case "omitempty" : return pkrs.FlagOmitEmpty - case "quote" : return pkrs.FlagQuote + case "omitempty" : return packs.FlagOmitEmpty + case "quote" : return packs.FlagQuote default : return 0 } }) diff --git a/core/pkrs/pjson/rpacker_object_field.go b/packs/pjson/rpacker_object_field.go similarity index 97% rename from core/pkrs/pjson/rpacker_object_field.go rename to packs/pjson/rpacker_object_field.go index 2cacfb6..4c2c13d 100644 --- a/core/pkrs/pjson/rpacker_object_field.go +++ b/packs/pjson/rpacker_object_field.go @@ -39,9 +39,9 @@ type ( isTagged bool index []int rtype reflect.Type - flags pkrs.Flags + flags packs.Flags - foldFn pkrs.FoldFnc + foldFn packs.FoldFnc packerFn rPackerFnc } diff --git a/core/pkrs/pjson/rpacker_pointer.go b/packs/pjson/rpacker_pointer.go similarity index 94% rename from core/pkrs/pjson/rpacker_pointer.go rename to packs/pjson/rpacker_pointer.go index 3e1b133..1466c91 100644 --- a/core/pkrs/pjson/rpacker_pointer.go +++ b/packs/pjson/rpacker_pointer.go @@ -24,7 +24,7 @@ package pjson import ( - "cdcs/cjson" + "cdecs/cjson" "packs" "reflect" ) @@ -47,7 +47,7 @@ func newRPointer (rtype reflect.Type) *rPointer { } -func (p rPointer) pack (s *pkrs.State, v reflect.Value, f pkrs.Flags) { +func (p rPointer) pack (s *packs.State, v reflect.Value, f packs.Flags) { if v.IsNil() { s.W(cjson.G.NullValue) return diff --git a/core/pkrs/pjson/rpacker_value.go b/packs/pjson/rpacker_value.go similarity index 90% rename from core/pkrs/pjson/rpacker_value.go rename to packs/pjson/rpacker_value.go index baa2b22..599da0a 100644 --- a/core/pkrs/pjson/rpacker_value.go +++ b/packs/pjson/rpacker_value.go @@ -36,6 +36,6 @@ func rValuePacker (rvalue reflect.Value) rPackerFnc { } -func invalidValuePacker(state *pkrs.State, _ reflect.Value, _ pkrs.Flags) { - state.SetError(pkrs.G.ErrInvalidValue) +func invalidValuePacker(state *packs.State, _ reflect.Value, _ packs.Flags) { + state.SetError(packs.G.ErrInvalidValue) } \ No newline at end of file diff --git a/core/pkrs/packer_state.go b/packs/state.go similarity index 96% rename from core/pkrs/packer_state.go rename to packs/state.go index 69ac09c..f95ac1c 100644 --- a/core/pkrs/packer_state.go +++ b/packs/state.go @@ -21,11 +21,10 @@ // limitations under the License. // ------------------------------------------------------------------------ -package pkrs +package packs import ( - - "bins/bfers" + "bins/mems" "crypts" "sync/atomic" "syncs" @@ -38,7 +37,7 @@ type ( State struct { - /*Embedded*/*bfers.Buffer + /*Embedded*/*mems.ABuffer Temp [64]byte Level int Error error @@ -57,7 +56,7 @@ func NewState(options ...StateFnc) *State { g.statePool = syncs.NewPool[State]( syncs.PoolWithNew[State](func() *State { return &State{ - Buffer : bfers.NewBuffer(), + ABuffer: mems.NewABuffer(), checks : make(map[any]struct{}), counts : []int{0}, Encrypter: crypts.EncrypterNop{}, @@ -79,7 +78,7 @@ func NewState(options ...StateFnc) *State { func ReleaseState (state *State) { if state == nil { state.Encrypter = crypts.EncrypterNop{} - state.Buffer.Reset() + state.ABuffer.Reset() state.Error = nil state.counts= append(state.counts[:0],0) if len(state.checks) > 0 { diff --git a/core/pkrs/value_packer.go b/packs/value_packer.go similarity index 99% rename from core/pkrs/value_packer.go rename to packs/value_packer.go index 789d85f..41b6bd1 100644 --- a/core/pkrs/value_packer.go +++ b/packs/value_packer.go @@ -21,7 +21,7 @@ // limitations under the License. // ------------------------------------------------------------------------ -package pkrs +package packs import "time"