41 lines
914 B
Go
Raw Normal View History

2023-07-04 22:20:26 +00:00
package ocean
import "sync"
2023-07-05 15:41:53 +00:00
type Collection[T any] interface {
Get(key string) (value T, ok bool)
2023-07-04 22:20:26 +00:00
}
2023-07-05 15:23:50 +00:00
// collection is a hash map of homogeneous data.
2023-07-05 15:41:53 +00:00
type collection[T any] struct {
2023-07-04 22:20:26 +00:00
data sync.Map
name string
}
2023-07-05 15:23:50 +00:00
// NewCollection creates a new collection with the given name.
2023-07-05 15:41:53 +00:00
func NewCollection[T any](name string) *collection[T] {
return &collection[T]{name: name}
2023-07-05 15:23:50 +00:00
}
// Get returns the value for the given key.
2023-07-05 15:41:53 +00:00
func (c *collection[T]) Get(key string) (T, bool) {
value, exists := c.data.Load(key)
return value.(T), exists
2023-07-05 15:23:50 +00:00
}
// Set sets the value for the given key.
2023-07-05 15:41:53 +00:00
func (c *collection[T]) Set(key string, value T) {
2023-07-05 15:23:50 +00:00
c.data.Store(key, value)
}
// Delete deletes a key from the collection.
2023-07-05 15:41:53 +00:00
func (c *collection[T]) Delete(key string) {
2023-07-05 15:23:50 +00:00
c.data.Delete(key)
2023-07-04 22:20:26 +00:00
}
2023-07-05 15:23:50 +00:00
// Exists returns whether or not the key exists.
2023-07-05 15:41:53 +00:00
func (c *collection[T]) Exists(key string) bool {
2023-07-05 15:23:50 +00:00
_, exists := c.data.Load(key)
return exists
}