text/cache.go

Functions Structs

Functions

func Clear

Clear removes all entries from the cache.

func (c *Cache[K, V]) Clear() {
	c.mu.Lock()
	defer c.mu.Unlock()

	c.entries = make(map[K]*cacheEntry[V])
	c.tick = 0
}

func Get

Get retrieves a value from the cache.

Returns (value, true) if found, (zero, false) otherwise.

func (c *Cache[K, V]) Get(key K) (V, bool) {
	c.mu.Lock()
	defer c.mu.Unlock()

	entry, ok := c.entries[key]
	if !ok {
		var zero V
		return zero, false
	}

	// Update access time
	c.tick++
	entry.atime = c.tick

	return entry.value, true
}

func GetOrCreate

GetOrCreate returns cached value or creates it.

Thread-safe: create is called under lock to prevent duplicate creation.

func (c *Cache[K, V]) GetOrCreate(key K, create func() V) V {
	c.mu.Lock()
	defer c.mu.Unlock()

	// Check if already in cache
	if entry, ok := c.entries[key]; ok {
		// Update access time
		c.tick++
		entry.atime = c.tick
		return entry.value
	}

	// Create new value (under lock)
	value := create()

	// Store in cache
	c.tick++
	c.entries[key] = &cacheEntry[V]{
		value:	value,
		atime:	c.tick,
	}

	// Evict if over soft limit
	if c.softLimit > 0 && len(c.entries) > c.softLimit {
		c.evictOldest()
	}

	return value
}

func Len

Len returns the number of entries in the cache.

func (c *Cache[K, V]) Len() int {
	c.mu.Lock()
	defer c.mu.Unlock()

	return len(c.entries)
}

func NewCache

NewCache creates a new cache with the given soft limit.

A softLimit of 0 means unlimited.

func NewCache[K comparable, V any](softLimit int) *Cache[K, V] {
	return &Cache[K, V]{
		entries:	make(map[K]*cacheEntry[V]),
		softLimit:	softLimit,
		tick:		0,
	}
}

func Set

Set stores a value in the cache.

If the cache exceeds softLimit after insertion, oldest entries are evicted.

func (c *Cache[K, V]) Set(key K, value V) {
	c.mu.Lock()
	defer c.mu.Unlock()

	c.tick++
	c.entries[key] = &cacheEntry[V]{
		value:	value,
		atime:	c.tick,
	}

	// Evict if over soft limit
	if c.softLimit > 0 && len(c.entries) > c.softLimit {
		c.evictOldest()
	}
}

Structs

type Cache struct

Cache is a generic thread-safe LRU cache with soft limit.

 

Deprecated: For new code, use github.com/gogpu/gg/internal/cache.Cache or

cache.ShardedCache which offer better performance and more features.

When the cache exceeds softLimit, oldest entries are evicted.

 

Cache is safe for concurrent use.

Cache must not be copied after creation (has mutex).

type Cache[K comparable, V any] struct {
	mu		sync.Mutex
	entries		map[K]*cacheEntry[V]
	softLimit	int
	tick		int64	// Monotonic access counter
}

type ShapingKey struct

ShapingKey identifies shaped text in the shaping cache.

type ShapingKey struct {
	Text		string
	Size		float64
	Direction	Direction
}

type GlyphKey struct

GlyphKey identifies a rasterized glyph in the glyph cache.

type GlyphKey struct {
	GID	GlyphID
	Size	float64
}