Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

gnomod.toml

module = "gno.land/r/nym-moultest123/x/daily/lru/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186407
  max_deposit = "5000000ugnot"

lru.gno

package lru

import (
	"strconv"
	"strings"

	"chain"
)

// capacity is the fixed maximum number of entries the cache holds.
const capacity = 8

// node is a doubly-linked-list node holding a key/value pair.
// The list is ordered MRU (head) -> LRU (tail).
type node struct {
	key   string
	value string
	prev  *node
	next  *node
}

// cache is a fixed-capacity LRU cache backed by a doubly-linked list and
// an index from key -> node for O(1) lookups.
type cache struct {
	index map[string]*node
	head  *node // most-recently-used
	tail  *node // least-recently-used
	size  int
	hits  int
	miss  int
}

var c = &cache{index: make(map[string]*node)}

// detach removes n from the linked list (does not touch the index).
func (ca *cache) detach(n *node) {
	if n.prev != nil {
		n.prev.next = n.next
	} else {
		ca.head = n.next
	}
	if n.next != nil {
		n.next.prev = n.prev
	} else {
		ca.tail = n.prev
	}
	n.prev = nil
	n.next = nil
}

// pushFront inserts n at the head (MRU position).
func (ca *cache) pushFront(n *node) {
	n.prev = nil
	n.next = ca.head
	if ca.head != nil {
		ca.head.prev = n
	}
	ca.head = n
	if ca.tail == nil {
		ca.tail = n
	}
}

// touch moves an existing node to the MRU position.
func (ca *cache) touch(n *node) {
	ca.detach(n)
	ca.pushFront(n)
}

// evict removes the LRU entry (tail) and returns its key.
func (ca *cache) evict() string {
	n := ca.tail
	if n == nil {
		return ""
	}
	ca.detach(n)
	delete(ca.index, n.key)
	ca.size--
	return n.key
}

// Put inserts or updates key with value and marks it most-recently-used.
// Evicts the least-recently-used entry if capacity is exceeded.
func Put(cur realm, key string, value string) {
	if n, ok := c.index[key]; ok {
		n.value = value
		c.touch(n)
		chain.Emit("Put", "key", key, "op", "update")
		return
	}
	n := &node{key: key, value: value}
	c.index[key] = n
	c.pushFront(n)
	c.size++
	evicted := ""
	if c.size > capacity {
		evicted = c.evict()
	}
	if evicted != "" {
		chain.Emit("Put", "key", key, "op", "insert", "evicted", evicted)
	} else {
		chain.Emit("Put", "key", key, "op", "insert")
	}
}

// Get returns the value for key and marks it most-recently-used.
// It records a hit or a miss. The returned bool reports whether the key
// was present.
func Get(cur realm, key string) (string, bool) {
	if n, ok := c.index[key]; ok {
		c.touch(n)
		c.hits++
		chain.Emit("Get", "key", key, "result", "hit")
		return n.value, true
	}
	c.miss++
	chain.Emit("Get", "key", key, "result", "miss")
	return "", false
}

// Reset clears the cache and stats.
func Reset(cur realm) {
	c = &cache{index: make(map[string]*node)}
	chain.Emit("Reset")
}

// peek returns the value without affecting recency or stats (read helper).
func peek(key string) (string, bool) {
	if n, ok := c.index[key]; ok {
		return n.value, true
	}
	return "", false
}

// Render displays the cache contents in MRU->LRU order with stats.
func Render(path string) string {
	var b strings.Builder
	b.WriteString("# LRU Cache\n\n")
	b.WriteString("A fixed-capacity least-recently-used cache.\n\n")

	b.WriteString("## Stats\n\n")
	b.WriteString("- Capacity: " + strconv.Itoa(capacity) + "\n")
	b.WriteString("- Size: " + strconv.Itoa(c.size) + "\n")
	b.WriteString("- Hits: " + strconv.Itoa(c.hits) + "\n")
	b.WriteString("- Misses: " + strconv.Itoa(c.miss) + "\n")
	total := c.hits + c.miss
	if total > 0 {
		// integer-percent hit rate, deterministic
		rate := (c.hits * 100) / total
		b.WriteString("- Hit rate: " + strconv.Itoa(rate) + "%\n")
	} else {
		b.WriteString("- Hit rate: n/a\n")
	}
	b.WriteString("\n")

	b.WriteString("## Entries (MRU → LRU)\n\n")
	if c.head == nil {
		b.WriteString("_empty_\n")
		return b.String()
	}
	b.WriteString("| # | Key | Value |\n")
	b.WriteString("|---|-----|-------|\n")
	i := 1
	for n := c.head; n != nil; n = n.next {
		b.WriteString("| " + strconv.Itoa(i) + " | " + n.key + " | " + n.value + " |\n")
		i++
	}
	return b.String()
}

lru_test.gno

package lru

import (
	"strconv"
	"testing"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
)

func reset(cur realm) {
	Reset(cross(cur))
}

func TestPutGetAndRecency(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("alice")))
	reset(cur)

	Put(cross(cur), "a", "1")
	Put(cross(cur), "b", "2")

	v, ok := Get(cross(cur), "a")
	uassert.True(t, ok, "a should be present")
	uassert.Equal(t, "1", v)

	// miss
	_, ok = Get(cross(cur), "zzz")
	uassert.False(t, ok, "zzz should be absent")

	// after Get("a"), a is MRU -> head
	uassert.Equal(t, "a", c.head.key)
	uassert.Equal(t, "b", c.tail.key)

	// stats: 1 hit, 1 miss
	uassert.Equal(t, 1, c.hits)
	uassert.Equal(t, 1, c.miss)

	// update existing key
	Put(cross(cur), "b", "22")
	v, _ = peek("b")
	uassert.Equal(t, "22", v)
	uassert.Equal(t, "b", c.head.key) // update marks MRU
	uassert.Equal(t, 2, c.size)
}

func TestEviction(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("bob")))
	reset(cur)

	// fill beyond capacity (8): insert k0..k9
	for i := 0; i < 10; i++ {
		Put(cross(cur), "k"+strconv.Itoa(i), strconv.Itoa(i))
	}

	uassert.Equal(t, capacity, c.size)

	// k0 and k1 should have been evicted (oldest inserts, never touched)
	_, ok := peek("k0")
	uassert.False(t, ok, "k0 should be evicted")
	_, ok = peek("k1")
	uassert.False(t, ok, "k1 should be evicted")

	// newest is MRU head, k2 is now the LRU tail
	uassert.Equal(t, "k9", c.head.key)
	uassert.Equal(t, "k2", c.tail.key)

	// touching k2 protects it; next insert evicts k3 instead
	_, ok = Get(cross(cur), "k2")
	uassert.True(t, ok, "k2 present")
	Put(cross(cur), "k10", "10")
	_, ok = peek("k2")
	uassert.True(t, ok, "k2 protected after Get")
	_, ok = peek("k3")
	uassert.False(t, ok, "k3 evicted instead")
	uassert.Equal(t, capacity, c.size)
}

render_test.gno

package lru

import (
	"strconv"
	"strings"
	"testing"

	"gno.land/p/nt/uassert/v0"
)

// clear empties the cache without needing a realm argument, so examples (which
// take no `cur`) can start from a known state. Examples run after all tests.
func clear() {
	c = &cache{index: make(map[string]*node)}
}

// ExampleRender pins the empty-cache view.
func ExampleRender() {
	clear()
	print(Render(""))
	// Output:
	// # LRU Cache
	//
	// A fixed-capacity least-recently-used cache.
	//
	// ## Stats
	//
	// - Capacity: 8
	// - Size: 0
	// - Hits: 0
	// - Misses: 0
	// - Hit rate: n/a
	//
	// ## Entries (MRU → LRU)
	//
	// _empty_
}

// TestRenderListsEntriesMRUFirst checks the table is ordered most-recently-used
// first and renumbered from 1.
func TestRenderListsEntriesMRUFirst(cur realm, t *testing.T) {
	reset(cur)
	Put(cross(cur), "a", "1")
	Put(cross(cur), "b", "2")
	Put(cross(cur), "c", "3")
	Get(cross(cur), "a") // a becomes MRU

	out := Render("")
	uassert.True(t, strings.Contains(out, "| 1 | a | 1 |\n| 2 | c | 3 |\n| 3 | b | 2 |\n"),
		"entries should be listed MRU->LRU: a, c, b")
	uassert.True(t, strings.Contains(out, "- Size: 3\n"), "size should be 3")
}

// TestRenderHitRate covers the integer-percent branch and the n/a branch.
func TestRenderHitRate(cur realm, t *testing.T) {
	reset(cur)
	uassert.True(t, strings.Contains(Render(""), "- Hit rate: n/a\n"),
		"no lookups yet should render n/a")

	Put(cross(cur), "a", "1")
	Get(cross(cur), "a")   // hit
	Get(cross(cur), "nope") // miss

	out := Render("")
	uassert.True(t, strings.Contains(out, "- Hits: 1\n"), "one hit")
	uassert.True(t, strings.Contains(out, "- Misses: 1\n"), "one miss")
	uassert.True(t, strings.Contains(out, "- Hit rate: 50%\n"), "1/2 should be 50%")
}

// TestRenderCapacityMatchesConst guards the header against a capacity change
// that the pinned example would otherwise silently disagree with.
func TestRenderCapacityMatchesConst(cur realm, t *testing.T) {
	reset(cur)
	uassert.True(t, strings.Contains(Render(""), "- Capacity: "+strconv.Itoa(capacity)+"\n"),
		"rendered capacity should match the constant")
}

// TestRenderIgnoresPath documents that Render has no sub-routes.
func TestRenderIgnoresPath(cur realm, t *testing.T) {
	reset(cur)
	Put(cross(cur), "k", "v")
	uassert.Equal(t, Render(""), Render("/whatever"))
}