ringcache

package module
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 13, 2024 License: MIT Imports: 1 Imported by: 0

README

Go Go Report Card codecov

A non-thread-safe ring cache, also known as a circular buffer, is a fixed-size data structure designed to efficiently handle a continuous stream of data by overwriting the oldest entries when new data is added and the buffer is full. This implementation ensures constant memory usage and provides O(1) time complexity for both adding and retrieving elements. However, it is not safe for concurrent use and should be used in single-threaded environments where predictable performance and efficient memory management are required.

Here's a complete usage example:

package main

import (
	"fmt"
	"ringcache"
)

// evictionHandler is a callback function that gets called when an item is evicted from the cache.
func evictionHandler(key interface{}, value interface{}) {
	fmt.Printf("Evicted key: %v, value: %v\n", key, value)
}

func main() {
	// Create a new ring cache with a maximum size of 3 and an eviction callback
	cache, err := ringcache.NewWithEvict(3, evictionHandler)
	if err != nil {
		fmt.Println("Error creating cache:", err)
		return
	}

	// Add some items to the cache
	cache.Add("key1", "value1")
	cache.Add("key2", "value2")
	cache.Add("key3", "value3")

	// Print the current cache contents
	fmt.Println("Cache after adding 3 items:")
	for _, key := range []string{"key1", "key2", "key3"} {
		if value, ok := cache.Get(key); ok {
			fmt.Printf("%s: %v\n", key, value)
		} else {
			fmt.Printf("%s not found\n", key)
		}
	}

	// Add another item, causing the first item to be evicted
	cache.Add("key4", "value4")

	// Print the current cache contents again
	fmt.Println("\nCache after adding 4th item (key1 should be evicted):")
	for _, key := range []string{"key1", "key2", "key3", "key4"} {
		if value, ok := cache.Get(key); ok {
			fmt.Printf("%s: %v\n", key, value)
		} else {
			fmt.Printf("%s not found\n", key)
		}
	}

	// Remove an item from the cache
	cache.Remove("key3")
	fmt.Println("\nCache after removing key3:")
	for _, key := range []string{"key2", "key3", "key4"} {
		if value, ok := cache.Get(key); ok {
			fmt.Printf("%s: %v\n", key, value)
		} else {
			fmt.Printf("%s not found\n", key)
		}
	}

	// Clear the cache
	cache.Purge()
	fmt.Println("\nCache after purge:")
	for _, key := range []string{"key2", "key3", "key4"} {
		if value, ok := cache.Get(key); ok {
			fmt.Printf("%s: %v\n", key, value)
		} else {
			fmt.Printf("%s not found\n", key)
		}
	}
}

Output:

Cache after adding 3 items:
key1: value1
key2: value2
key3: value3

Evicted key: key1, value: value1
Cache after adding 4th item (key1 should be evicted):
key1 not found
key2: value2
key3: value3
key4: value4

Evicted key: key3, value: value3
Cache after removing key3:
key2: value2
key3 not found
key4: value4

Evicted key: key2, value: value2
Evicted key: key4, value: value4
Cache after purge:
key2 not found
key3 not found
key4 not found

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a pull request or open an issue if you encounter any problems or have any suggestions for improvements.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type EvictCallback

type EvictCallback func(key interface{}, value interface{})

EvictCallback is used to get a callback when a cache entry is evicted

type RingCache

type RingCache struct {
	// contains filtered or unexported fields
}

RingCache, often known as a circular buffer or ring buffer, is a data structure that uses a single, fixed-size buffer as if it were connected end-to-end. It is particularly useful for applications that require a buffer with a consistent and predictable size, such as in real-time data processing systems or network packet buffering.

func New

func New(maxSize int) (*RingCache, error)

New creates a ring cache of the given size.

func NewWithEvict

func NewWithEvict(maxSize int, onEvict EvictCallback) (*RingCache, error)

NewWithEvict constructs ring cache of the given size with callback

func (*RingCache) Add

func (c *RingCache) Add(key, value interface{}) (evicted bool)

Add adds a value to the cache. Returns true if an eviction occurred.

func (*RingCache) Cap

func (c *RingCache) Cap() int

Cap returns the capacity of the cache.

func (*RingCache) Contains

func (c *RingCache) Contains(key interface{}) bool

Contains checks if a key is in the cache, without updating the recent-ness or deleting it for being stale.

func (*RingCache) Get

func (c *RingCache) Get(key interface{}) (interface{}, bool)

Get looks up a key's value from the cache.

func (*RingCache) Len

func (c *RingCache) Len() int

Len returns the number of items in the cache.

func (*RingCache) Purge

func (c *RingCache) Purge()

Purge is used to completely clear the cache.

func (*RingCache) Remove

func (c *RingCache) Remove(key interface{}) bool

Remove removes the provided key from the cache, returning if the key was contained.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL