mirror of
https://github.com/hanzozt/foundation.git
synced 2026-10-30 14:42:04 +00:00
* move util up a level * rename common to versions * remove pfxlog from versions * remove neatcat and echo server * move udp code to transport * remove agent, identity and metrics, which have been split out * remove config which was unused
56 lines
1.1 KiB
Go
56 lines
1.1 KiB
Go
package cowslice
|
|
|
|
import (
|
|
"reflect"
|
|
"sync"
|
|
"sync/atomic"
|
|
)
|
|
|
|
type CowSlice struct {
|
|
value atomic.Value
|
|
lock sync.Mutex
|
|
}
|
|
|
|
func NewCowSlice(initialValue interface{}) *CowSlice {
|
|
result := &CowSlice{}
|
|
result.value.Store(initialValue)
|
|
return result
|
|
}
|
|
|
|
func (slice *CowSlice) Value() interface{} {
|
|
return slice.value.Load()
|
|
}
|
|
|
|
func Append(registry *CowSlice, listener interface{}) {
|
|
registry.lock.Lock()
|
|
defer registry.lock.Unlock()
|
|
|
|
currentSlice := registry.value.Load()
|
|
newSlice := reflect.Append(reflect.ValueOf(currentSlice), reflect.ValueOf(listener))
|
|
registry.value.Store(newSlice.Interface())
|
|
}
|
|
|
|
func Delete(registry *CowSlice, listener interface{}) {
|
|
registry.lock.Lock()
|
|
defer registry.lock.Unlock()
|
|
|
|
currentSlice := registry.value.Load()
|
|
t := reflect.TypeOf(currentSlice)
|
|
val := reflect.ValueOf(currentSlice)
|
|
|
|
cap := val.Len() - 1
|
|
|
|
if cap < 0 {
|
|
cap = 0
|
|
}
|
|
|
|
newSlice := reflect.MakeSlice(t, 0, cap)
|
|
for i := 0; i < val.Len(); i++ {
|
|
next := val.Index(i)
|
|
if next.Interface() != listener {
|
|
newSlice = reflect.Append(newSlice, next)
|
|
}
|
|
}
|
|
registry.value.Store(newSlice.Interface())
|
|
}
|