package int64int64collection import ( "slices" "sync" ) // Collection is a sync.Map that stores in64 keys and int64 values. type Collection struct { items sync.Map close chan struct{} keys []int64 } // Item is interface to store int64 data. type item struct { data int64 } // NewCollection creates collection instance. func NewCollection() *Collection { c := &Collection{ close: make(chan struct{}), } c.keys = make([]int64, 0) return c } // Get gets value by given key. Returns value int64, isExist bool. func (collection *Collection) Get(key int64) (int64, bool) { obj, exists := collection.items.Load(key) if !exists { return 0, false } item := obj.(item) return item.data, true } // Set stores given value in collection. func (collection *Collection) Set(key int64, value int64) { collection.items.Store(key, item{ data: value, }) collection.keys = append(collection.keys, key) slices.Sort(collection.keys) collection.keys = slices.Compact(collection.keys) } // Delete deletes value from collection by given key. func (collection *Collection) Delete(key int64) { collection.items.Delete(key) for index, k := range collection.keys { if k == key { collection.keys = slices.Delete(collection.keys, index, index) } } } // ListKeys returns slice with keys in collection. func (collection *Collection) ListKeys() []int64 { return collection.keys } // Close frees resources used by collection. func (collection *Collection) Close() { collection.close <- struct{}{} collection.items = sync.Map{} collection.keys = []int64{} } /* vim: set ft=go noet ai ts=4 sw=4 sts=4: */