48 lines
934 B
Go
48 lines
934 B
Go
package cache
|
|
|
|
import (
|
|
"sync"
|
|
)
|
|
|
|
// Cache represents an in-memory key-value store.
|
|
type Cache struct {
|
|
data map[string]any
|
|
mu sync.RWMutex
|
|
}
|
|
|
|
// NewCache creates and initializes a new Cache instance.
|
|
func NewCache() *Cache {
|
|
return &Cache{
|
|
data: make(map[string]any),
|
|
}
|
|
}
|
|
|
|
// Set adds or updates a key-value pair in the cache.
|
|
func (c *Cache) Set(key string, value any) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
c.data[key] = value
|
|
}
|
|
|
|
// Get retrieves the value associated with the given key from the cache.
|
|
func (c *Cache) Get(key string) (any, bool) {
|
|
c.mu.RLock()
|
|
defer c.mu.RUnlock()
|
|
value, ok := c.data[key]
|
|
return value, ok
|
|
}
|
|
|
|
// Delete removes a key-value pair from the cache.
|
|
func (c *Cache) Delete(key string) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
delete(c.data, key)
|
|
}
|
|
|
|
// Clear removes all key-value pairs from the cache.
|
|
func (c *Cache) Clear() {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
c.data = make(map[string]any)
|
|
}
|