Playground
gnomod.toml
module = "gno.land/p/nym-moultest123/kit/store/v0" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186404 max_deposit = "12000000ugnot"
store.gno
// Package store is the auto-id ordered collection every r/moul realm was
// building by hand: an avl.Tree, an int counter, and a private function that
// zero-pads the counter into a key so the tree iterates in the order a human
// expects.
//
// Sixteen realm files in this repo carry that third piece. They do not agree:
//
// padID width 6 for len(s) < 6 { s = "0" + s } asciiart
// pad width 12 for len(s) < 12 { s = "0" + s } tictactoe
// key width 12 the same loop, a different name blog, crowdfund,
// englishauction,
// erc721, splitter
// idKey width 12 the same loop, a third name connect4
// idKey width 12 strings.Repeat, guarded by len(s) >= 12 governor, todos
// idKey width 12 strings.Repeat, UNGUARDED timecapsule
// seqKey width 16 strings.Repeat, guarded guestbook
//
// Every one of them is a silent ceiling. Past the width, the padding stops and
// the tree starts ordering "1000000000000" before "999999999999", so the list
// a realm renders is simply wrong from that entry on. The unguarded variant is
// worse: strings.Repeat panics on a negative count, so the realm stops
// accepting writes rather than merely mis-sorting them. asciiart's width of 6
// puts that ceiling at one million entries.
//
// The ceiling exists because the key is a decimal string, and decimal strings
// do not sort numerically. This package removes the ceiling by removing the
// decision: keys are the big-endian bytes of a [gno.land/p/nt/seqid/v0] ID, a
// fixed 8 bytes whose lexicographic order IS numeric order, for every value a
// uint64 can hold. There is no width to pick and no width to outgrow.
//
// # Usage
//
// var games store.Store // the zero value is an empty store
//
// func NewGame(cur realm) int64 {
// id := games.Add(&Game{...})
// return int64(id)
// }
//
// func Move(cur realm, gameID int64, cell int) {
// g := games.MustGet(store.ID(gameID)).(*Game)
// ...
// }
//
// func Render(path string) string {
// for _, e := range games.PageReverse(1, 20) { // newest first
// g := e.Value.(*Game)
// ... e.ID ...
// }
// }
//
// # Identifiers
//
// An ID is a uint64 that renders as a plain decimal number, so a realm ported
// to this package keeps showing "#7" exactly as it did before. Only the avl
// key changes, and the key was never user-visible.
//
// IDs start at 1. The zero ID is never assigned, so it is usable as "absent",
// and [Store.Get] on it always misses.
//
// Removing an entry does not free its ID. IDs are a history, not a dense
// index: reusing one would silently repoint an old link at a new object.
package store
import (
"strconv"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/seqid/v0"
)
// ID identifies one entry. It is a plain integer to the outside world and an
// ordered fixed-width key inside the tree.
type ID uint64
// String renders the ID in decimal, which is how realms show it and how it
// arrives back in a Render path.
func (id ID) String() string { return strconv.FormatUint(uint64(id), 10) }
// Key is the avl key for the ID: the 8 big-endian bytes of the underlying
// seqid, whose byte order is its numeric order.
//
// Exposed because a realm that keeps a secondary index keyed by the same ID
// needs the identical key, and because it is the one place the encoding is
// decided.
func (id ID) Key() string { return seqid.ID(id).Binary() }
// ParseID reads an ID from its decimal form, the shape it has in a Render
// path or a function argument.
//
// It returns false for anything that is not a plain unsigned decimal, which
// includes "", "-1", "1.0", a value past uint64, and the zero ID (never
// assigned, so accepting it would only produce a lookup that cannot hit).
// Leading zeros are accepted: "007" is the ID 7.
func ParseID(s string) (ID, bool) {
n, err := strconv.ParseUint(s, 10, 64)
if err != nil || n == 0 {
return 0, false
}
return ID(n), true
}
// Entry is one ID/value pair, as returned by the paging methods.
type Entry struct {
ID ID
Value any
}
// Store is an ordered collection of values under auto-assigned IDs.
//
// The zero Store is an empty store and is ready to use, so a realm can declare
// one as a package-level var without an initializer. [New] exists for the
// pointer form.
type Store struct {
tree avl.Tree
last seqid.ID
label string
}
// New returns an empty store.
func New() *Store { return &Store{} }
// Named is [New] with a noun for what the store holds, used in the panic
// [Store.MustGet] raises: store.Named("game") makes it "game #7 not found"
// instead of "store: no entry #7".
//
// It exists so porting a realm to this package does not have to trade its own
// error wording for one shared implementation. The realms being replaced here
// panic "game not found", "proposal not found", "capsule not found"; the label
// keeps that and adds the id they all omitted.
func Named(label string) *Store { return &Store{label: label} }
// Add stores v under the next ID and returns it.
//
// It panics if the ID space is exhausted, which is [seqid.ID.Next]'s behaviour
// and requires 2^64 insertions to reach.
func (s *Store) Add(v any) ID {
id := ID(s.last.Next())
s.tree.Set(id.Key(), v)
return id
}
// Set writes v at an existing or explicit ID, and reports whether it replaced
// a value.
//
// Use it to update an entry in place. It does not move the ID counter, so
// setting an ID above [Store.LastID] leaves a gap that [Store.Add] will later
// walk into and overwrite. Prefer [Store.Add] to create.
func (s *Store) Set(id ID, v any) (replaced bool) {
return s.tree.Set(id.Key(), v)
}
// Get returns the value at id, and whether it was there.
//
// Unlike avl.Tree.Get, a nil value stored at a live ID is distinguishable from
// an absent one, because the second result comes from Has rather than from the
// value being nil.
func (s *Store) Get(id ID) (any, bool) {
k := id.Key()
if !s.tree.Has(k) {
return nil, false
}
return s.tree.Get(k), true
}
// MustGet returns the value at id, or panics.
//
// This is the "get or panic" the realms wrote eighteen times, with one
// implementation instead of eighteen. The panic names the id, which none of
// them did: "store: no entry #7", or "game #7 not found" for a store built
// with [Named].
func (s *Store) MustGet(id ID) any {
v, ok := s.Get(id)
if !ok {
panic(s.missing(id))
}
return v
}
func (s *Store) missing(id ID) string {
if s.label == "" {
return "store: no entry #" + id.String()
}
return s.label + " #" + id.String() + " not found"
}
// Has reports whether id is present.
func (s *Store) Has(id ID) bool { return s.tree.Has(id.Key()) }
// Remove deletes the entry at id and returns the value it held.
//
// The ID is not recycled: see the package doc.
func (s *Store) Remove(id ID) (any, bool) { return s.tree.Remove(id.Key()) }
// Len reports how many entries are present. Removals lower it; [Store.LastID]
// does not move.
func (s *Store) Len() int { return s.tree.Size() }
// LastID is the highest ID ever assigned, or 0 when nothing has been added.
// It is the count of insertions, not of live entries.
func (s *Store) LastID() ID { return ID(s.last) }
// Each visits every entry in ascending ID order.
//
// It takes no stop signal on purpose: this is the common case, and a callback
// whose bool means "stop" reads identically to one whose bool means
// "continue". When iteration has to end early, say so in the name and use
// [Store.EachUntil].
func (s *Store) Each(fn func(id ID, v any)) {
s.tree.Iterate("", "", func(k string, v any) bool {
fn(keyID(k), v)
return false
})
}
// EachReverse is [Store.Each] in descending ID order, which is what a
// newest-first list wants.
func (s *Store) EachReverse(fn func(id ID, v any)) {
s.tree.ReverseIterate("", "", func(k string, v any) bool {
fn(keyID(k), v)
return false
})
}
// EachUntil visits entries in ascending ID order and stops when fn returns
// true. It reports whether it stopped early.
//
// True means stop, matching avl.IterCbFn exactly, so a callback moved between
// this package and a raw tree keeps its meaning.
func (s *Store) EachUntil(fn func(id ID, v any) bool) bool {
return s.tree.Iterate("", "", func(k string, v any) bool {
return fn(keyID(k), v)
})
}
// EachReverseUntil is [Store.EachUntil] in descending ID order.
func (s *Store) EachReverseUntil(fn func(id ID, v any) bool) bool {
return s.tree.ReverseIterate("", "", func(k string, v any) bool {
return fn(keyID(k), v)
})
}
// Page returns page number page of size entries, in ascending ID order.
//
// Pages are 1-based, because they are shown to a reader ("page 1 of 4") and an
// off-by-one between the URL and the label is the bug this saves. A page past
// the end, or a page or size below 1, returns an empty slice rather than
// panicking: the page number usually comes from a Render path, which is user
// input.
//
// It walks only the requested window, not the whole tree.
func (s *Store) Page(page, size int) []Entry {
return s.slice(page, size, false)
}
// PageReverse is [Store.Page] in descending ID order: page 1 holds the newest
// entries.
func (s *Store) PageReverse(page, size int) []Entry {
return s.slice(page, size, true)
}
func (s *Store) slice(page, size int, reverse bool) []Entry {
if page < 1 || size < 1 {
return nil
}
offset := (page - 1) * size
out := make([]Entry, 0, size)
cb := func(k string, v any) bool {
out = append(out, Entry{ID: keyID(k), Value: v})
return false
}
if reverse {
s.tree.ReverseIterateByOffset(offset, size, cb)
} else {
s.tree.IterateByOffset(offset, size, cb)
}
return out
}
// Pages reports how many pages of the given size the store holds, which is
// what a pager footer needs. A size below 1 gives 0.
func (s *Store) Pages(size int) int {
if size < 1 {
return 0
}
n := s.Len()
return (n + size - 1) / size
}
// keyID decodes an avl key back to its ID. The keys in this tree are always
// written by ID.Key, so a short or malformed key means the tree was written by
// something other than this package.
func keyID(k string) ID {
if len(k) != 8 {
panic("store: foreign key in tree")
}
var n uint64
for i := 0; i < 8; i++ {
n = n<<8 | uint64(k[i])
}
return ID(n)
}
store_test.gno
package store
import (
"strconv"
"strings"
"testing"
"gno.land/p/nt/uassert/v0"
)
func TestZeroValueIsUsable(t *testing.T) {
var s Store
uassert.Equal(t, 0, s.Len())
uassert.Equal(t, uint64(0), uint64(s.LastID()))
uassert.Equal(t, uint64(1), uint64(s.Add("first")))
uassert.Equal(t, 1, s.Len())
}
func TestAddAssignsSequentialIDsFromOne(t *testing.T) {
s := New()
for want := uint64(1); want <= 5; want++ {
uassert.Equal(t, want, uint64(s.Add("v"+strconv.FormatUint(want, 10))))
}
uassert.Equal(t, 5, s.Len())
uassert.Equal(t, uint64(5), uint64(s.LastID()))
}
func TestGetHasMustGet(t *testing.T) {
s := New()
id := s.Add("hello")
got, ok := s.Get(id)
uassert.True(t, ok, "live id is found")
uassert.Equal(t, "hello", got.(string))
uassert.True(t, s.Has(id), "Has agrees with Get")
uassert.Equal(t, "hello", s.MustGet(id).(string))
_, ok = s.Get(ID(2))
uassert.False(t, ok, "unassigned id misses")
_, ok = s.Get(ID(0))
uassert.False(t, ok, "the zero id always misses")
uassert.False(t, s.Has(ID(0)), "the zero id is never present")
}
// A nil value at a live id must still read as present. avl.Tree.Get alone
// cannot tell those apart, which is why Get consults Has.
func TestNilValueIsDistinguishableFromAbsent(t *testing.T) {
s := New()
id := s.Add(nil)
v, ok := s.Get(id)
uassert.True(t, ok, "a stored nil is present")
uassert.Nil(t, v, "and reads back as nil")
uassert.Equal(t, 1, s.Len())
}
func TestMustGetPanicsNamingTheEntry(cur realm, t *testing.T) {
s := New()
s.Add("only")
uassert.PanicsWithMessage(t, cur, "store: no entry #7", func() { s.MustGet(ID(7)) })
uassert.NotPanics(t, cur, func() { s.MustGet(ID(1)) })
}
// A labelled store keeps the realm's own wording, so porting one does not
// trade "game not found" for a generic message.
func TestNamedStoreUsesItsLabelInThePanic(cur realm, t *testing.T) {
s := Named("game")
s.Add("only")
uassert.PanicsWithMessage(t, cur, "game #7 not found", func() { s.MustGet(ID(7)) })
uassert.NotPanics(t, cur, func() { s.MustGet(ID(1)) })
// The label changes nothing else.
uassert.Equal(t, uint64(1), uint64(s.LastID()))
uassert.Equal(t, 1, s.Len())
}
func TestSetReplacesInPlace(t *testing.T) {
s := New()
id := s.Add("before")
uassert.True(t, s.Set(id, "after"), "Set reports the replacement")
uassert.Equal(t, "after", s.MustGet(id).(string))
uassert.Equal(t, 1, s.Len(), "replacing does not grow the store")
uassert.Equal(t, uint64(1), uint64(s.LastID()), "replacing does not move the counter")
}
func TestRemoveDoesNotRecycleIDs(t *testing.T) {
s := New()
a := s.Add("a")
s.Add("b")
v, ok := s.Remove(a)
uassert.True(t, ok, "removing a live id succeeds")
uassert.Equal(t, "a", v.(string))
uassert.Equal(t, 1, s.Len())
_, ok = s.Remove(a)
uassert.False(t, ok, "removing twice is a miss, not a panic")
// The next Add continues the history rather than refilling the hole.
uassert.Equal(t, uint64(3), uint64(s.Add("c")))
}
func TestParseID(t *testing.T) {
cases := []struct {
name string
in string
want ID
ok bool
}{
{"plain", "7", 7, true},
{"leading zeros", "007", 7, true},
{"max uint64", "18446744073709551615", ID(18446744073709551615), true},
{"empty", "", 0, false},
{"zero is never assigned", "0", 0, false},
{"negative", "-1", 0, false},
{"signed positive", "+1", 0, false},
{"decimal point", "1.0", 0, false},
{"not a number", "abc", 0, false},
{"trailing space", "7 ", 0, false},
{"overflows uint64", "18446744073709551616", 0, false},
}
for _, tc := range cases {
got, ok := ParseID(tc.in)
uassert.Equal(t, tc.ok, ok, tc.name+": ok")
uassert.Equal(t, uint64(tc.want), uint64(got), tc.name+": value")
}
}
// The round trip a realm actually performs: render an id into a path, take it
// back off the path, look the entry up.
func TestIDRoundTripsThroughAPath(t *testing.T) {
s := New()
id := s.Add("entry")
for i := 0; i < 20; i++ {
id = s.Add("entry")
}
parsed, ok := ParseID(id.String())
uassert.True(t, ok, "the rendered id parses back")
uassert.Equal(t, uint64(id), uint64(parsed))
uassert.Equal(t, "entry", s.MustGet(parsed).(string))
}
func TestKeyIsFixedWidthAndOrdered(t *testing.T) {
uassert.Equal(t, 8, len(ID(1).Key()), "every key is 8 bytes")
uassert.Equal(t, 8, len(ID(18446744073709551615).Key()), "including the largest")
// Byte order is numeric order, which is the whole point.
prev := ID(0).Key()
for _, n := range []uint64{1, 9, 10, 99, 100, 999999, 1000000, 999999999999, 1000000000000, 18446744073709551615} {
k := ID(n).Key()
uassert.True(t, prev < k, "keys ascend at "+strconv.FormatUint(n, 10))
prev = k
}
}
// padWidth is the shape sixteen realm files carry, reproduced so the defect it
// causes is asserted rather than described. The widths in the tree are 6
// (asciiart), 12 (most) and 16 (guestbook).
func padWidth(n uint64, width int) string {
s := strconv.FormatUint(n, 10)
if len(s) >= width {
return s
}
return strings.Repeat("0", width-len(s)) + s
}
// The ceiling: one entry past the chosen width, decimal keys stop sorting
// numerically. store's keys do not have a width to outgrow.
func TestOrderSurvivesThePaddingCeiling(t *testing.T) {
cases := []struct {
name string
width int
lo, hi uint64
}{
{"asciiart, width 6", 6, 999999, 1000000},
{"the width 12 majority", 12, 999999999999, 1000000000000},
{"guestbook, width 16", 16, 9999999999999999, 10000000000000000},
}
for _, tc := range cases {
// The hand-rolled key inverts: the larger id sorts first.
uassert.True(t, padWidth(tc.hi, tc.width) < padWidth(tc.lo, tc.width),
tc.name+": the padded key is expected to invert here")
// The store key does not.
uassert.True(t, ID(tc.lo).Key() < ID(tc.hi).Key(), tc.name+": store keys stay ordered")
// And iteration follows.
s := New()
s.Set(ID(tc.hi), "hi")
s.Set(ID(tc.lo), "lo")
var order []string
s.Each(func(id ID, v any) { order = append(order, v.(string)) })
uassert.Equal(t, "lo,hi", strings.Join(order, ","), tc.name+": iteration is numeric")
}
}
// timecapsule's variant calls strings.Repeat without the len guard, so past
// the width it panics instead of mis-sorting: the realm stops accepting
// writes. Asserted here because it is the reason this is a correctness fix and
// not a tidy-up.
func TestUnguardedPadPanicsPastItsWidth(cur realm, t *testing.T) {
unguarded := func(n uint64) string {
return strings.Repeat("0", 12-len(strconv.FormatUint(n, 10))) + strconv.FormatUint(n, 10)
}
uassert.NotPanics(t, cur, func() { unguarded(999999999999) })
uassert.PanicsContains(t, cur, "negative", func() { unguarded(1000000000000) })
uassert.NotPanics(t, cur, func() { ID(1000000000000).Key() })
}
func TestEachVisitsEverythingInOrder(t *testing.T) {
s := New()
for i := 1; i <= 5; i++ {
s.Add(strconv.Itoa(i))
}
var fwd, rev []string
s.Each(func(id ID, v any) { fwd = append(fwd, id.String()+"="+v.(string)) })
s.EachReverse(func(id ID, v any) { rev = append(rev, id.String()+"="+v.(string)) })
uassert.Equal(t, "1=1,2=2,3=3,4=4,5=5", strings.Join(fwd, ","))
uassert.Equal(t, "5=5,4=4,3=3,2=2,1=1", strings.Join(rev, ","))
}
func TestEachOnAnEmptyStoreIsANoOp(t *testing.T) {
s := New()
calls := 0
s.Each(func(id ID, v any) { calls++ })
s.EachReverse(func(id ID, v any) { calls++ })
uassert.Equal(t, 0, calls)
uassert.Equal(t, 0, len(s.Page(1, 10)))
uassert.Equal(t, 0, s.Pages(10))
}
// True means stop, the same as avl.IterCbFn, so a callback keeps its meaning
// when it moves between this package and a raw tree.
func TestEachUntilStopsOnTrue(t *testing.T) {
s := New()
for i := 1; i <= 5; i++ {
s.Add(strconv.Itoa(i))
}
var seen []string
stopped := s.EachUntil(func(id ID, v any) bool {
seen = append(seen, v.(string))
return id == 3
})
uassert.True(t, stopped, "it reports stopping early")
uassert.Equal(t, "1,2,3", strings.Join(seen, ","))
seen = nil
stopped = s.EachReverseUntil(func(id ID, v any) bool {
seen = append(seen, v.(string))
return id == 4
})
uassert.True(t, stopped)
uassert.Equal(t, "5,4", strings.Join(seen, ","))
stopped = s.EachUntil(func(id ID, v any) bool { return false })
uassert.False(t, stopped, "running to the end is not stopping early")
}
func TestPageIsOneBased(t *testing.T) {
s := New()
for i := 1; i <= 7; i++ {
s.Add(strconv.Itoa(i))
}
cases := []struct {
name string
page, size int
want string
}{
{"first page", 1, 3, "1,2,3"},
{"second page", 2, 3, "4,5,6"},
{"short last page", 3, 3, "7"},
{"past the end", 4, 3, ""},
{"far past the end", 99, 3, ""},
{"whole store in one page", 1, 100, "1,2,3,4,5,6,7"},
{"page 0 is not page 1", 0, 3, ""},
{"negative page", -1, 3, ""},
{"size 0", 1, 0, ""},
{"negative size", 1, -3, ""},
}
for _, tc := range cases {
var got []string
for _, e := range s.Page(tc.page, tc.size) {
got = append(got, e.Value.(string))
}
uassert.Equal(t, tc.want, strings.Join(got, ","), tc.name)
}
}
func TestPageReverseStartsWithTheNewest(t *testing.T) {
s := New()
for i := 1; i <= 7; i++ {
s.Add(strconv.Itoa(i))
}
cases := []struct {
name string
page, size int
want string
}{
{"newest first", 1, 3, "7,6,5"},
{"second page", 2, 3, "4,3,2"},
{"short last page", 3, 3, "1"},
{"past the end", 4, 3, ""},
}
for _, tc := range cases {
var got []string
for _, e := range s.PageReverse(tc.page, tc.size) {
got = append(got, e.Value.(string))
}
uassert.Equal(t, tc.want, strings.Join(got, ","), tc.name)
}
}
func TestPageCarriesTheID(t *testing.T) {
s := New()
s.Add("a")
s.Add("b")
p := s.Page(1, 10)
uassert.Equal(t, 2, len(p))
uassert.Equal(t, uint64(1), uint64(p[0].ID))
uassert.Equal(t, uint64(2), uint64(p[1].ID))
r := s.PageReverse(1, 10)
uassert.Equal(t, uint64(2), uint64(r[0].ID))
uassert.Equal(t, uint64(1), uint64(r[1].ID))
}
func TestPages(t *testing.T) {
s := New()
uassert.Equal(t, 0, s.Pages(10), "an empty store has no pages")
for i := 1; i <= 10; i++ {
s.Add("v")
}
uassert.Equal(t, 1, s.Pages(10), "an exact fit is one page")
uassert.Equal(t, 2, s.Pages(9), "a remainder adds a page")
uassert.Equal(t, 10, s.Pages(1))
uassert.Equal(t, 0, s.Pages(0), "a size below 1 has no pages")
uassert.Equal(t, 0, s.Pages(-1))
}
// Paging and iteration must stay consistent after entries are removed from the
// middle, which is where a dense-index assumption would break.
func TestPagingAfterRemovals(t *testing.T) {
s := New()
for i := 1; i <= 6; i++ {
s.Add(strconv.Itoa(i))
}
s.Remove(ID(2))
s.Remove(ID(5))
uassert.Equal(t, 4, s.Len())
uassert.Equal(t, uint64(6), uint64(s.LastID()), "the counter does not rewind")
var got []string
s.Each(func(id ID, v any) { got = append(got, id.String()) })
uassert.Equal(t, "1,3,4,6", strings.Join(got, ","))
got = nil
for _, e := range s.Page(2, 2) {
got = append(got, e.ID.String())
}
uassert.Equal(t, "4,6", strings.Join(got, ","), "page 2 of the survivors")
uassert.Equal(t, 2, s.Pages(2))
}