101 lines
1.8 KiB
Go
Raw Normal View History

2023-07-04 22:20:26 +00:00
package ocean
2023-07-05 21:59:49 +00:00
import (
"encoding/json"
"os"
"path"
"sync"
)
2023-07-04 22:20:26 +00:00
2023-07-05 15:41:53 +00:00
type Collection[T any] interface {
2023-07-05 20:02:16 +00:00
All() <-chan T
Delete(key string)
Exists(key string) bool
2023-07-05 15:41:53 +00:00
Get(key string) (value T, ok bool)
2023-07-05 20:02:16 +00:00
Set(key string, value T)
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-05 21:59:49 +00:00
data sync.Map
name string
directory string
2023-07-04 22:20:26 +00:00
}
2023-07-05 15:23:50 +00:00
// NewCollection creates a new collection with the given name.
2023-07-05 21:59:49 +00:00
func NewCollection[T any](namespace string, name string) (*collection[T], error) {
home, err := os.UserHomeDir()
if err != nil {
return nil, err
}
directory := path.Join(home, ".ocean", namespace, name)
err = os.MkdirAll(directory, 0700)
if err != nil {
return nil, err
}
c := &collection[T]{
name: name,
directory: directory,
}
return c, err
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)
2023-07-05 21:59:49 +00:00
fileName := path.Join(c.directory, key+".json")
file, err := os.Create(fileName)
if err != nil {
panic(err)
}
encoder := json.NewEncoder(file)
encoder.Encode(value)
err = file.Close()
if err != nil {
panic(err)
}
2023-07-05 15:23:50 +00:00
}
// 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
}
2023-07-05 20:02:16 +00:00
// All returns a channel of all objects in the collection.
func (c *collection[T]) All() <-chan T {
channel := make(chan T)
go func() {
c.data.Range(func(key, value any) bool {
channel <- value.(T)
return true
})
close(channel)
}()
return channel
}