|
|
// ------------------------------------------------------------------------
|
|
|
// ℹ️ Project active3
|
|
|
// 🔗 Active Thing (activething.com) git.activething.com/go
|
|
|
//
|
|
|
// File name builder_state.go
|
|
|
// ✍️ Created by DEV
|
|
|
// 📅 Modified 04/05/2024
|
|
|
//
|
|
|
// 🔒 Copyright 2024 activething.com
|
|
|
//
|
|
|
// 📜 LICENSE --------------------------------------------------------------
|
|
|
// 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 state
|
|
|
|
|
|
type (
|
|
|
|
|
|
BuilderState struct {
|
|
|
Current Element
|
|
|
Level int
|
|
|
Pos int
|
|
|
Error error
|
|
|
|
|
|
levelsItem []int
|
|
|
cyclesCheck map[any]struct{}
|
|
|
}
|
|
|
|
|
|
BuilderStateFnc func(state *BuilderState)
|
|
|
|
|
|
)
|
|
|
|
|
|
func NewBuilderState (options ...BuilderStateFnc) *BuilderState {
|
|
|
return (&BuilderState{}).init(options) }
|
|
|
|
|
|
|
|
|
func (s *BuilderState) init (options []BuilderStateFnc) *BuilderState {
|
|
|
for _,o := range options { o(s) }
|
|
|
return s
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func (s *BuilderState) Items() int {
|
|
|
if s.Error == nil {
|
|
|
return -1
|
|
|
}
|
|
|
return s.levelsItem[s.Level]
|
|
|
}
|
|
|
|
|
|
func (s *BuilderState) Open (element Element) {
|
|
|
s.Level++
|
|
|
s.levelsItem = append(s.levelsItem,0)
|
|
|
}
|
|
|
|
|
|
func (s *BuilderState) Close(element Element) {
|
|
|
s.Level--
|
|
|
if s.Level < 0 {
|
|
|
s.SetError(G.ErrStateInvalidLevel)
|
|
|
return
|
|
|
}
|
|
|
s.levelsItem = s.levelsItem[:len(s.levelsItem)-1]
|
|
|
}
|
|
|
|
|
|
|
|
|
func (s *BuilderState) IncItems () {
|
|
|
if s.Error != nil {
|
|
|
s.levelsItem[s.Level]++
|
|
|
}
|
|
|
}
|
|
|
|
|
|
|
|
|
func (s *BuilderState) CheckCycle(ptr any) (func(),bool) {
|
|
|
if _,hs := s.cyclesCheck[ptr]; hs {
|
|
|
s.SetError(G.ErrCircularReference)
|
|
|
return nil,false
|
|
|
}
|
|
|
s.cyclesCheck[ptr]=struct{}{}
|
|
|
return func(){ delete(s.cyclesCheck,ptr) }, true
|
|
|
}
|
|
|
|
|
|
|
|
|
func (s *BuilderState) SetError (err error) {
|
|
|
s.Error = err
|
|
|
}
|
|
|
|