util/context/attributes.go

106 lines
1.8 KiB
Go
Raw Normal View History

2017-11-27 05:53:04 +00:00
package context
2017-11-27 09:41:29 +00:00
import "sync"
2017-11-27 05:53:04 +00:00
type AttributeManager interface {
Init()
SetAttribute(key string, value interface{})
GetAttribute(key string) (value interface{})
RemoveAttribute(key string)
Contains(key string) (exist bool)
Destroy()
}
type AttributeManagers struct {
2017-11-27 09:41:29 +00:00
Parent AttributeManager
2017-11-27 05:53:04 +00:00
attributes map[string]interface{}
2017-11-27 09:41:29 +00:00
mtx sync.RWMutex
2017-11-27 05:53:04 +00:00
}
func (am *AttributeManagers) Init() {
2017-11-27 09:41:29 +00:00
if nil != am.Parent {
am.Parent.Init()
}
2017-11-27 05:53:04 +00:00
if nil == am.attributes {
2017-11-27 05:57:26 +00:00
am.Destroy()
2017-11-27 05:53:04 +00:00
}
2017-11-27 05:57:26 +00:00
am.attributes = make(map[string]interface{})
2017-11-27 05:53:04 +00:00
}
func (am *AttributeManagers) SetAttribute(key string, value interface{}) {
2017-11-27 09:41:29 +00:00
am.checkInitialized()
am.mtx.Lock()
defer am.mtx.Unlock()
2017-11-27 05:53:04 +00:00
am.attributes[key] = value
}
func (am *AttributeManagers) GetAttribute(key string) (value interface{}) {
2017-11-27 09:41:29 +00:00
am.checkInitialized()
am.mtx.RLock()
defer am.mtx.RUnlock()
if _, ok := am.attributes[key]; ok {
return am.attributes[key]
2017-11-27 05:53:04 +00:00
}
2017-11-27 09:41:29 +00:00
if nil == am.Parent {
2017-11-27 05:53:04 +00:00
return nil
}
2017-11-27 09:41:29 +00:00
return am.Parent.GetAttribute(key)
2017-11-27 05:53:04 +00:00
}
func (am *AttributeManagers) RemoveAttribute(key string) {
2017-11-27 09:41:29 +00:00
am.checkInitialized()
am.mtx.Lock()
defer am.mtx.Unlock()
if _, ok := am.attributes[key]; ok {
delete(am.attributes, key)
return
}
if nil == am.Parent {
2017-11-27 05:53:04 +00:00
return
}
2017-11-27 09:41:29 +00:00
am.Parent.RemoveAttribute(key)
2017-11-27 05:53:04 +00:00
}
func (am *AttributeManagers) Contains(key string) (exist bool) {
2017-11-27 09:41:29 +00:00
am.checkInitialized()
am.mtx.RLock()
defer am.mtx.RUnlock()
if _, ok := am.attributes[key]; ok {
return true
}
if nil == am.Parent {
2017-11-27 05:53:04 +00:00
return false
}
2017-11-27 09:41:29 +00:00
return am.Parent.Contains(key)
2017-11-27 05:53:04 +00:00
}
func (am *AttributeManagers) Destroy() {
2017-11-27 05:57:26 +00:00
if nil != am.attributes {
2017-11-27 05:53:04 +00:00
am.attributes = nil
}
2017-11-27 09:41:29 +00:00
if nil != am.Parent {
am.Parent.Destroy()
}
}
func (am *AttributeManagers) checkInitialized() {
if nil == am.attributes {
panic("Attribute Manager: must be initialized")
}
2017-11-27 05:53:04 +00:00
}