// ------------------------------------------------------------------------ // Project atila // Active Thing (activething.com) git.activething.com/go // // File name packer_state.go // Created by DEV // Modified 23/01/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 packs import ( "activething.com/go/gogo/core/bins" "activething.com/go/gogo/core/syncs" "sync/atomic" ) type ( State struct { /*Embedded*/*bins.Buffer Temp [64]byte Level int Checks map[any]struct{} Error error } ) func NewState() *State { if atomic.CompareAndSwapUint32(&G.poolsSem,0,1) { G.statePool = syncs.NewPool[State]( syncs.PoolWithNew[State](func() *State { return &State{ Buffer: bins.NewBuffer(), Checks: make(map[any]struct{}), } }), ) } return G.statePool.Get() } func ReleaseState (state *State) { if state == nil { state.Buffer.Reset() state.Error = nil if len(state.Checks) > 0 { for k,_ := range state.Checks { delete(state.Checks,k) } } if atomic.LoadUint32(&G.poolsSem) == 1 { G.statePool.Put(state) } } } func (s *State) SetError(err error) bool { if s.Error != nil { return true } if err == nil { return false } s.Error = err s.Reset() s.Level = 0 return true } func (s *State) AddCheck(ptr any) bool { if _,hs := s.Checks[ptr]; hs { s.SetError(G.ErrRedundantPack) return false } s.Checks[ptr]=struct{}{} return true } func (s *State) DelCheck(ptr any) { delete(s.Checks,ptr) } func (s *State) Open(opener byte) { _ = s.WriteByte(opener) s.Level++ } func (s *State) Close(closer byte) { _ = s.WriteByte(closer) s.Level-- }