Playground
flatmap.gno
// Package flatmap is a sorted-vector map — the STL flat_map / Abseil
// btree_map trade — as a pure, reusable package.
//
// Keys and values live in two parallel sorted slices instead of a hash table or
// a tree of nodes. Lookup is a binary search, O(log n) rather than O(1), but it
// touches contiguous memory instead of chasing pointers, iteration is already
// in key order with nothing to sort, and there is no per-entry node overhead.
// Insertion in the middle is O(n) because it shifts the tail. That is the whole
// bargain: cheap reads and cheap ordered iteration, paid for at write time.
//
// On chain the ordering is the real draw. A built-in gno map iterates in an
// unspecified order, so a Render built from one can differ between nodes — a
// consensus bug rather than a cosmetic one. A flat map is sorted by
// construction, so iteration is deterministic without a sort on every read.
//
// Appending in ascending key order is the fast path: it hits the end of the
// slice and shifts nothing.
//
// A live demo of this package is at
// [r/moul/x/daily/flatmapdemo](/r/nym-moultest123/x/daily/flatmapdemo/v0).
package flatmap
import "sort"
// MaxEntries bounds the map so gas stays predictable.
const MaxEntries = 4096
// FlatMap is a string->string map backed by parallel sorted slices.
type FlatMap struct {
keys []string
vals []string
}
// New returns an empty FlatMap.
func New() *FlatMap { return &FlatMap{} }
// Len returns the number of entries.
func (f *FlatMap) Len() int { return len(f.keys) }
// IsEmpty reports whether the map holds nothing.
func (f *FlatMap) IsEmpty() bool { return len(f.keys) == 0 }
// search returns the index where key is, or would be inserted, plus whether it
// is actually present.
func (f *FlatMap) search(key string) (int, bool) {
i := sort.SearchStrings(f.keys, key)
return i, i < len(f.keys) && f.keys[i] == key
}
// Get returns the value for key.
func (f *FlatMap) Get(key string) (string, bool) {
i, found := f.search(key)
if !found {
return "", false
}
return f.vals[i], true
}
// Has reports whether key is present.
func (f *FlatMap) Has(key string) bool { _, found := f.search(key); return found }
// Set inserts or updates key. Returns false only when the map is full and key
// is new — updating an existing key always succeeds.
func (f *FlatMap) Set(key, value string) bool {
i, found := f.search(key)
if found {
f.vals[i] = value
return true
}
if len(f.keys) >= MaxEntries {
return false
}
// Grow by one, then shift the tail right to open a slot at i.
f.keys = append(f.keys, "")
f.vals = append(f.vals, "")
copy(f.keys[i+1:], f.keys[i:])
copy(f.vals[i+1:], f.vals[i:])
f.keys[i] = key
f.vals[i] = value
return true
}
// Delete removes key. Returns false when absent.
func (f *FlatMap) Delete(key string) bool {
i, found := f.search(key)
if !found {
return false
}
copy(f.keys[i:], f.keys[i+1:])
copy(f.vals[i:], f.vals[i+1:])
f.keys = f.keys[:len(f.keys)-1]
f.vals = f.vals[:len(f.vals)-1]
return true
}
// Keys returns the keys in sorted order, as a copy.
func (f *FlatMap) Keys() []string {
out := make([]string, len(f.keys))
copy(out, f.keys)
return out
}
// Values returns the values ordered by their keys, as a copy.
func (f *FlatMap) Values() []string {
out := make([]string, len(f.vals))
copy(out, f.vals)
return out
}
// At returns the i-th entry in key order — the indexed access a hash map cannot
// offer, and one reason to pay for sorted storage.
func (f *FlatMap) At(i int) (key, value string, ok bool) {
if i < 0 || i >= len(f.keys) {
return "", "", false
}
return f.keys[i], f.vals[i], true
}
// Iterate calls fn for each entry in key order. Returning true stops.
func (f *FlatMap) Iterate(fn func(key, value string) bool) {
for i := range f.keys {
if fn(f.keys[i], f.vals[i]) {
return
}
}
}
// Range calls fn for entries with lo <= key < hi, in key order. An empty hi
// means "to the end". This is the other thing sorted storage buys: a range
// query is two binary searches and a walk.
func (f *FlatMap) Range(lo, hi string, fn func(key, value string) bool) {
start := sort.SearchStrings(f.keys, lo)
for i := start; i < len(f.keys); i++ {
if hi != "" && f.keys[i] >= hi {
return
}
if fn(f.keys[i], f.vals[i]) {
return
}
}
}
// Clone returns an independent copy.
func (f *FlatMap) Clone() *FlatMap {
return &FlatMap{keys: f.Keys(), vals: f.Values()}
}
// Sorted reports whether the backing slice is in strictly ascending order.
// Always true through the public API; exported so callers can assert it.
func (f *FlatMap) Sorted() bool {
for i := 1; i < len(f.keys); i++ {
if f.keys[i-1] >= f.keys[i] {
return false
}
}
return len(f.keys) == len(f.vals)
}
flatmap_test.gno
package flatmap
import (
"strconv"
"strings"
"testing"
"gno.land/p/nt/uassert/v0"
)
func TestEmpty(t *testing.T) {
f := New()
uassert.Equal(t, 0, f.Len())
uassert.True(t, f.IsEmpty())
uassert.False(t, f.Has("a"))
uassert.True(t, f.Sorted(), "an empty map is trivially sorted")
_, ok := f.Get("a")
uassert.False(t, ok)
_, _, ok = f.At(0)
uassert.False(t, ok)
}
// TestStaysSortedRegardlessOfInsertionOrder is the core invariant.
func TestStaysSortedRegardlessOfInsertionOrder(t *testing.T) {
f := New()
for _, k := range []string{"delta", "alpha", "echo", "bravo", "charlie"} {
f.Set(k, "v-"+k)
}
uassert.Equal(t, "alpha,bravo,charlie,delta,echo", strings.Join(f.Keys(), ","))
uassert.True(t, f.Sorted())
}
func TestGetSet(t *testing.T) {
f := New()
uassert.True(t, f.Set("b", "2"))
uassert.True(t, f.Set("a", "1"))
v, ok := f.Get("a")
uassert.True(t, ok)
uassert.Equal(t, "1", v)
_, ok = f.Get("zzz")
uassert.False(t, ok)
}
func TestSetUpdatesInPlace(t *testing.T) {
f := New()
f.Set("a", "1")
f.Set("b", "2")
uassert.True(t, f.Set("a", "99"))
uassert.Equal(t, 2, f.Len(), "updating must not add an entry")
v, _ := f.Get("a")
uassert.Equal(t, "99", v)
uassert.True(t, f.Sorted())
}
func TestValuesFollowKeyOrder(t *testing.T) {
f := New()
f.Set("c", "3")
f.Set("a", "1")
f.Set("b", "2")
uassert.Equal(t, "1,2,3", strings.Join(f.Values(), ","))
}
func TestDelete(t *testing.T) {
f := New()
for _, k := range []string{"a", "b", "c", "d"} {
f.Set(k, k)
}
uassert.True(t, f.Delete("b"))
uassert.Equal(t, "a,c,d", strings.Join(f.Keys(), ","), "the gap must close")
uassert.Equal(t, "a,c,d", strings.Join(f.Values(), ","), "values shift with keys")
uassert.Equal(t, 3, f.Len())
uassert.True(t, f.Sorted())
uassert.False(t, f.Delete("b"), "deleting twice reports false")
}
func TestDeleteEnds(t *testing.T) {
f := New()
for _, k := range []string{"a", "b", "c"} {
f.Set(k, k)
}
uassert.True(t, f.Delete("a"))
uassert.True(t, f.Delete("c"))
uassert.Equal(t, "b", strings.Join(f.Keys(), ","))
uassert.True(t, f.Delete("b"))
uassert.True(t, f.IsEmpty())
}
func TestAt(t *testing.T) {
f := New()
f.Set("b", "2")
f.Set("a", "1")
k, v, ok := f.At(0)
uassert.True(t, ok)
uassert.Equal(t, "a", k)
uassert.Equal(t, "1", v)
_, _, ok = f.At(-1)
uassert.False(t, ok)
_, _, ok = f.At(2)
uassert.False(t, ok)
}
func TestIterateAndStop(t *testing.T) {
f := New()
for _, k := range []string{"c", "a", "b"} {
f.Set(k, strings.ToUpper(k))
}
var seen []string
f.Iterate(func(k, v string) bool {
seen = append(seen, k+"="+v)
return false
})
uassert.Equal(t, "a=A,b=B,c=C", strings.Join(seen, ","))
count := 0
f.Iterate(func(k, v string) bool { count++; return true })
uassert.Equal(t, 1, count, "returning true stops iteration")
}
// TestRange is the query sorted storage makes cheap.
func TestRange(t *testing.T) {
f := New()
for _, k := range []string{"a", "b", "c", "d", "e"} {
f.Set(k, k)
}
uassert.Equal(t, "b,c,d", collect(f, "b", "e"), "lo inclusive, hi exclusive")
uassert.Equal(t, "c,d,e", collect(f, "c", ""), "empty hi runs to the end")
uassert.Equal(t, "a,b,c,d,e", collect(f, "", ""), "empty bounds cover everything")
uassert.Equal(t, "", collect(f, "x", "z"), "a range past the end yields nothing")
uassert.Equal(t, "", collect(f, "c", "c"), "an empty half-open range yields nothing")
}
func TestRangeStops(t *testing.T) {
f := New()
for _, k := range []string{"a", "b", "c"} {
f.Set(k, k)
}
n := 0
f.Range("", "", func(k, v string) bool { n++; return true })
uassert.Equal(t, 1, n)
}
func TestRangeOnAbsentBoundary(t *testing.T) {
f := New()
for _, k := range []string{"a", "c", "e"} {
f.Set(k, k)
}
// "b" and "d" are not present; the range still lands correctly.
uassert.Equal(t, "c", collect(f, "b", "d"))
}
func TestKeysAndValuesAreCopies(t *testing.T) {
f := New()
f.Set("a", "1")
f.Set("b", "2")
ks := f.Keys()
ks[0] = "mutated"
vs := f.Values()
vs[0] = "mutated"
uassert.Equal(t, "a,b", strings.Join(f.Keys(), ","), "callers cannot reorder the map through Keys")
uassert.Equal(t, "1,2", strings.Join(f.Values(), ","))
}
func TestClone(t *testing.T) {
f := New()
f.Set("a", "1")
cp := f.Clone()
cp.Set("b", "2")
uassert.Equal(t, 1, f.Len(), "clone must not share storage")
uassert.Equal(t, 2, cp.Len())
uassert.True(t, cp.Sorted())
}
func TestMaxEntries(t *testing.T) {
f := New()
for i := 0; i < MaxEntries; i++ {
uassert.True(t, f.Set(pad(i), "v"), "should accept up to MaxEntries")
}
uassert.Equal(t, MaxEntries, f.Len())
uassert.False(t, f.Set("zzz-overflow", "v"), "a full map refuses a new key")
uassert.Equal(t, MaxEntries, f.Len())
uassert.True(t, f.Set(pad(0), "updated"), "a full map still accepts updates")
v, _ := f.Get(pad(0))
uassert.Equal(t, "updated", v)
}
// TestDescendingInsertionIsTheSlowPath exercises the worst case for a sorted
// vector — every insert shifts the whole tail — and checks it stays correct.
func TestDescendingInsertionIsTheSlowPath(t *testing.T) {
f := New()
for i := 200; i > 0; i-- {
f.Set(pad(i), strconv.Itoa(i))
}
uassert.Equal(t, 200, f.Len())
uassert.True(t, f.Sorted(), "still sorted after 200 head insertions")
k, v, _ := f.At(0)
uassert.Equal(t, pad(1), k)
uassert.Equal(t, "1", v, "keys and values must stay in step through every shift")
}
func collect(f *FlatMap, lo, hi string) string {
var out []string
f.Range(lo, hi, func(k, v string) bool {
out = append(out, k)
return false
})
return strings.Join(out, ",")
}
// pad zero-pads so string order matches numeric order. ufmt has no width
// flags in gno, so this is done by hand.
func pad(i int) string {
s := strconv.Itoa(i)
for len(s) < 6 {
s = "0" + s
}
return s
}
gnomod.toml
module = "gno.land/p/nym-moultest123/x/daily/flatmap/v0" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186405 max_deposit = "6000000ugnot"