diff --git a/.gitignore b/.gitignore index 35ad056..94c0bf4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .cursor .DS_Store -.vscode \ No newline at end of file +.vscode +.windsurf \ No newline at end of file diff --git a/syncmap.go b/syncmap.go new file mode 100644 index 0000000..84e739a --- /dev/null +++ b/syncmap.go @@ -0,0 +1,38 @@ +package cachex + +import ( + "context" + "sync" + + "github.com/pkg/errors" +) + +// SyncMap is a cache implementation using sync.Map +type SyncMap[T any] struct { + sync.Map +} + +var _ Cache[any] = &SyncMap[any]{} + +func NewSyncMap[T any]() *SyncMap[T] { + return &SyncMap[T]{} +} + +func (s *SyncMap[T]) Set(_ context.Context, key string, value T) error { + s.Store(key, value) + return nil +} + +func (s *SyncMap[T]) Get(_ context.Context, key string) (T, error) { + var zero T + v, ok := s.Load(key) + if !ok { + return zero, errors.Wrapf(&ErrKeyNotFound{}, "key not found in syncmap for key: %s", key) + } + return v.(T), nil +} + +func (s *SyncMap[T]) Del(_ context.Context, key string) error { + s.Delete(key) + return nil +} diff --git a/syncmap_test.go b/syncmap_test.go new file mode 100644 index 0000000..aaad940 --- /dev/null +++ b/syncmap_test.go @@ -0,0 +1,43 @@ +package cachex + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSyncMapBasics(t *testing.T) { + ctx := context.Background() + cache := NewSyncMap[string]() + + require.NoError(t, cache.Set(ctx, "key1", "value1")) + + value, err := cache.Get(ctx, "key1") + require.NoError(t, err) + assert.Equal(t, "value1", value) + + require.NoError(t, cache.Del(ctx, "key1")) + + _, err = cache.Get(ctx, "key1") + assert.True(t, IsErrKeyNotFound(err)) +} + +func TestSyncMapEmbeddedMethods(t *testing.T) { + cache := NewSyncMap[int]() + + cache.Store("a", 1) + cache.Store("b", 2) + + v, ok := cache.Load("a") + require.True(t, ok) + assert.Equal(t, 1, v) + + count := 0 + cache.Range(func(k, v any) bool { + count++ + return true + }) + assert.Equal(t, 2, count) +}