You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

134 lines
2.6 KiB

// ------------------------------------------------------------------------
// Project atila
// Active Thing (activething.com) git.activething.com/go
//
// File name scope.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 values
import (
"activething.com/go/gogo/core/opts"
"activething.com/go/gogo/core/syncs"
)
type (
Scope struct {
locker syncs.LockerRW
atts ScopeAtt
parent ValueProvider
valuers map[any]Valuer
}
ScopeWalkFnc func (key, value any) bool
)
func NewScope (options ...opts.OptionErrFnc[Scope]) (*Scope,error) {
return opts.ApplyAndCheck[Scope](&Scope {
valuers : make(map[any]Valuer),
})
}
func (s *Scope) Reset () {
s.locker.Lock()
s.parent = nil
for k,_ := range s.valuers {
delete(s.valuers,k)
}
s.locker.Unlock()
}
func (s *Scope) Attach (parent ValueProvider) {
s.locker.Lock()
s.parent = parent
s.locker.Unlock()
}
func (s *Scope) Detach() {
s.locker.Lock()
s.parent = nil
s.locker.Unlock()
}
func (s *Scope) Parent () ValueProvider {
s.locker.RLock()
p := s.parent
s.locker.RUnlock()
return p
}
func (s *Scope) Has (key any) bool {
s.locker.RLock()
_,h := s.valuers[key]
s.locker.RUnlock()
return h
}
func (s *Scope) Value (key any) (any,bool) {
if key == nil {
return nil,false
}
s.locker.RLock()
v,h := s.valuers[key]
s.locker.RUnlock()
if h {
return v,true
}
if s.parent != nil {
return s.parent.Value(key)
}
return nil,false
}
func (s *Scope) SetValue(key any, value any) error {
if key == nil {
return G.ErrInvalidScopeKey
}
s.locker.Lock()
if s.atts.IsReadOnly() {
s.locker.Unlock()
return G.ErrReadOnlyScope
}
s.valuers[key]= AsValuer(value)
s.locker.Unlock()
return nil
}
func (s *Scope) DelValue (key any) {
s.locker.Lock()
delete (s.valuers,key)
s.locker.Unlock()
}
func (s *Scope) Walk (walker ScopeWalkFnc) {
for k,v := range s.valuers {
if !walker(k,v.Value()) {
return
}
}
}

Powered by TurnKey Linux.