Documentation
¶
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ErrCacheMiss = errors.New("cache miss")
ErrCacheMiss is returned by Cache.Get if item is not found in cache.
Functions ¶
This section is empty.
Types ¶
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache is a simple rotating cache that maintains byte slices in memory up to the defined storage limit, both in memory size and entry count.
The cache is safe for concurrent access.
func NewCache ¶
NewCache returns a new cache with the given memory usage limit in bytes and maximum entry count.
Arguments:
- memLimit: The maximum memory usage of the cache in bytes.
- itemLimit: The maximum number of items that can be stored in the cache.
Returns:
- A pointer to a new Cache instance.
Example:
cache := NewCache(1024*1024, 100) // 1MB limit, 100 items max
func (*Cache) Delete ¶
Delete deletes entry under key from cache if it exists and returns true if it was found and deleted, false otherwise.
Arguments:
- key: The key of the item to delete.
Returns:
- exists: True if the item was found and deleted, false otherwise.
Example:
deleted := cache.Delete("my_item")
if deleted {
fmt.Println("Item deleted from cache")
} else {
fmt.Println("Item not found in cache")
}
func (*Cache) Exists ¶
Exists returns true if an entry under key exists in cache, false otherwise.
Arguments:
- key: The key of the item to check for.
Returns:
- exists: True if the item exists in the cache, false otherwise.
Example:
exists := cache.Exists("my_item")
if exists {
fmt.Println("Item exists in cache")
} else {
fmt.Println("Item does not exist in cache")
}
func (*Cache) Get ¶
Get retrieves an item from cache by key.
Arguments:
- key: The key of the item to retrieve.
Returns:
- out: The byte slice stored under the given key, if found.
- err: An error. ErrCacheMiss if the item was not found.
Example:
data, err := cache.Get("my_item")
if err != nil {
if errors.Is(err, ErrCacheMiss) {
fmt.Println("Item not found in cache")
} else {
fmt.Println("Error getting item:", err)
}
return
}
fmt.Println("Item found:", string(data))
func (*Cache) Put ¶
Put stores data into cache under key and rotates the cache if storage limit has been reached. If an item with the same key already exists, it will be overwritten.
Arguments:
- key: The key under which to store the data.
- data: The byte slice to store in the cache.
Example:
data := []byte("some data to cache")
cache.Put("my_item", data)