planner/plan/storage/memory/memory.go

65 lines
1020 B
Go
Raw Normal View History

2024-10-05 10:12:45 +02:00
package memory
import (
"sync"
"github.com/google/uuid"
"go-mod.ewintr.nl/planner/plan/storage"
)
type MemoryLocalID struct {
ids map[string]int
mutex sync.RWMutex
}
func NewMemoryLocalID() *MemoryLocalID {
return &MemoryLocalID{
ids: make(map[string]int),
}
}
func (ml *MemoryLocalID) FindAll() (map[string]int, error) {
ml.mutex.RLock()
defer ml.mutex.RUnlock()
return ml.ids, nil
}
func (ml *MemoryLocalID) Next() (string, int, error) {
ml.mutex.RLock()
defer ml.mutex.RUnlock()
id := uuid.New().String()
cur := make([]int, 0, len(ml.ids))
for _, i := range ml.ids {
cur = append(cur, i)
}
localID := storage.NextLocalID(cur)
return id, localID, nil
}
func (ml *MemoryLocalID) Store(id string, localID int) error {
ml.mutex.Lock()
defer ml.mutex.Unlock()
ml.ids[id] = localID
return nil
}
func (ml *MemoryLocalID) Delete(id string) error {
ml.mutex.Lock()
defer ml.mutex.Unlock()
if _, ok := ml.ids[id]; !ok {
return ErrNotFound
}
delete(ml.ids, id)
return nil
}