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

bitset.gno

// Package bitset is a dense, fixed-capacity bit vector as a pure, reusable
// package: a compact set of small non-negative integers with the usual
// set algebra (union, intersection, difference).
//
// Storage is a []uint64 of ceil(n/64) words, so 1024 bits cost 16 words rather
// than 1024 booleans — the reason to reach for this on chain, where every byte
// is paid for.
//
// Capacity is fixed at construction and every operation is bounds-checked
// rather than growing: an out-of-range index is a caller bug, and silently
// growing would make gas unpredictable.
//
// A live demo of this package is at
// [r/moul/x/daily/bitsetdemo](/r/nym-moultest123/x/daily/bitsetdemo/v0).
package bitset

import "strings"

// MaxBits bounds a BitSet so allocation and iteration stay predictable.
const MaxBits = 1 << 16 // 65536 bits = 1024 words = 8 KiB

// BitSet is a fixed-capacity set of integers in [0, n).
type BitSet struct {
	n     int
	words []uint64
}

// New returns a BitSet holding bits [0, n). n is clamped to [0, MaxBits].
func New(n int) *BitSet {
	if n < 0 {
		n = 0
	}
	if n > MaxBits {
		n = MaxBits
	}
	return &BitSet{n: n, words: make([]uint64, (n+63)/64)}
}

// Cap returns the capacity in bits.
func (b *BitSet) Cap() int { return b.n }

// InRange reports whether i is a valid index.
func (b *BitSet) InRange(i int) bool { return i >= 0 && i < b.n }

// Set turns bit i on and reports whether i was in range.
func (b *BitSet) Set(i int) bool {
	if !b.InRange(i) {
		return false
	}
	b.words[i/64] |= 1 << uint(i%64)
	return true
}

// Clear turns bit i off and reports whether i was in range.
func (b *BitSet) Clear(i int) bool {
	if !b.InRange(i) {
		return false
	}
	b.words[i/64] &^= 1 << uint(i%64)
	return true
}

// Flip inverts bit i and reports whether i was in range.
func (b *BitSet) Flip(i int) bool {
	if !b.InRange(i) {
		return false
	}
	b.words[i/64] ^= 1 << uint(i%64)
	return true
}

// Has reports whether bit i is set. Out of range is false, never a panic:
// membership of something that cannot be a member is simply false.
func (b *BitSet) Has(i int) bool {
	if !b.InRange(i) {
		return false
	}
	return b.words[i/64]&(1<<uint(i%64)) != 0
}

// Count returns the number of set bits (popcount).
func (b *BitSet) Count() int {
	total := 0
	for _, w := range b.words {
		total += popcount(w)
	}
	return total
}

// popcount counts set bits with the classic SWAR trick — no math/bits on gno.
func popcount(x uint64) int {
	n := 0
	for x != 0 {
		x &= x - 1 // clear the lowest set bit
		n++
	}
	return n
}

// Slice returns the set bits in ascending order.
func (b *BitSet) Slice() []int {
	out := []int{}
	for i := 0; i < b.n; i++ {
		if b.Has(i) {
			out = append(out, i)
		}
	}
	return out
}

// Clone returns an independent copy.
func (b *BitSet) Clone() *BitSet {
	c := New(b.n)
	copy(c.words, b.words)
	return c
}

// sameCap reports whether two sets can be combined word-wise.
func sameCap(a, b *BitSet) bool { return a != nil && b != nil && a.n == b.n }

// Union returns a ∪ b, or nil when the capacities differ. Mismatched capacities
// are a caller error rather than something to silently pad.
func Union(a, b *BitSet) *BitSet { return combine(a, b, "or") }

// Intersect returns a ∩ b, or nil when the capacities differ.
func Intersect(a, b *BitSet) *BitSet { return combine(a, b, "and") }

// Difference returns a \ b, or nil when the capacities differ.
func Difference(a, b *BitSet) *BitSet { return combine(a, b, "andnot") }

// SymmetricDifference returns a △ b, or nil when the capacities differ.
func SymmetricDifference(a, b *BitSet) *BitSet { return combine(a, b, "xor") }

func combine(a, b *BitSet, op string) *BitSet {
	if !sameCap(a, b) {
		return nil
	}
	out := New(a.n)
	for i := range a.words {
		switch op {
		case "or":
			out.words[i] = a.words[i] | b.words[i]
		case "and":
			out.words[i] = a.words[i] & b.words[i]
		case "andnot":
			out.words[i] = a.words[i] &^ b.words[i]
		case "xor":
			out.words[i] = a.words[i] ^ b.words[i]
		}
	}
	return out
}

// Equal reports whether two sets have the same capacity and the same bits.
func Equal(a, b *BitSet) bool {
	if !sameCap(a, b) {
		return false
	}
	for i := range a.words {
		if a.words[i] != b.words[i] {
			return false
		}
	}
	return true
}

// String renders the set as '0'/'1' from bit 0 upward, which reads left-to-right
// in index order (note this is the reverse of binary notation).
func (b *BitSet) String() string {
	var sb strings.Builder
	for i := 0; i < b.n; i++ {
		if b.Has(i) {
			sb.WriteByte('1')
		} else {
			sb.WriteByte('0')
		}
	}
	return sb.String()
}

// FromSlice builds a BitSet of capacity n containing the given indices.
// Out-of-range indices are ignored.
func FromSlice(n int, idx []int) *BitSet {
	b := New(n)
	for _, i := range idx {
		b.Set(i)
	}
	return b
}

bitset_test.gno

package bitset

import (
	"strings"
	"testing"

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

func TestSetHasClear(t *testing.T) {
	b := New(100)
	uassert.False(t, b.Has(7))
	uassert.True(t, b.Set(7))
	uassert.True(t, b.Has(7))
	uassert.True(t, b.Clear(7))
	uassert.False(t, b.Has(7))
}

// Out of range is reported, never a panic — and Has is simply false.
func TestOutOfRange(t *testing.T) {
	b := New(64)
	for _, i := range []int{-1, 64, 1000} {
		uassert.False(t, b.Set(i))
		uassert.False(t, b.Clear(i))
		uassert.False(t, b.Flip(i))
		uassert.False(t, b.Has(i))
	}
	uassert.Equal(t, 0, b.Count())
}

// Word boundaries are where an off-by-one lives: check either side of 64.
func TestWordBoundaries(t *testing.T) {
	b := New(200)
	for _, i := range []int{0, 63, 64, 65, 127, 128, 199} {
		uassert.True(t, b.Set(i))
	}
	uassert.Equal(t, 7, b.Count())
	for _, i := range []int{0, 63, 64, 65, 127, 128, 199} {
		uassert.True(t, b.Has(i))
	}
	uassert.False(t, b.Has(62))
	uassert.False(t, b.Has(129))
}

func TestFlip(t *testing.T) {
	b := New(10)
	b.Flip(3)
	uassert.True(t, b.Has(3))
	b.Flip(3)
	uassert.False(t, b.Has(3))
}

func TestCountAndSlice(t *testing.T) {
	b := FromSlice(50, []int{1, 5, 9, 49})
	uassert.Equal(t, 4, b.Count())
	uassert.Equal(t, "1,5,9,49", join(b.Slice()))
}

func TestFromSliceIgnoresOutOfRange(t *testing.T) {
	b := FromSlice(10, []int{1, -3, 10, 99, 4})
	uassert.Equal(t, "1,4", join(b.Slice()))
}

func TestSetAlgebra(t *testing.T) {
	a := FromSlice(20, []int{1, 2, 3})
	b := FromSlice(20, []int{3, 4})
	uassert.Equal(t, "1,2,3,4", join(Union(a, b).Slice()))
	uassert.Equal(t, "3", join(Intersect(a, b).Slice()))
	uassert.Equal(t, "1,2", join(Difference(a, b).Slice()))
	uassert.Equal(t, "1,2,4", join(SymmetricDifference(a, b).Slice()))
}

// Combining different capacities is a caller error: nil, not a silent pad.
func TestMismatchedCapacityIsNil(t *testing.T) {
	a := New(10)
	b := New(20)
	uassert.True(t, Union(a, b) == nil)
	uassert.True(t, Intersect(a, b) == nil)
	uassert.True(t, Difference(a, b) == nil)
	uassert.True(t, SymmetricDifference(a, b) == nil)
	uassert.False(t, Equal(a, b))
}

func TestCloneIsIndependent(t *testing.T) {
	a := FromSlice(30, []int{1, 2})
	c := a.Clone()
	c.Set(29)
	uassert.False(t, a.Has(29))
	uassert.True(t, Equal(a, FromSlice(30, []int{1, 2})))
}

func TestEqual(t *testing.T) {
	uassert.True(t, Equal(FromSlice(8, []int{1, 3}), FromSlice(8, []int{3, 1})))
	uassert.False(t, Equal(FromSlice(8, []int{1}), FromSlice(8, []int{2})))
}

func TestString(t *testing.T) {
	uassert.Equal(t, "01010", FromSlice(5, []int{1, 3}).String())
}

func TestCapClamped(t *testing.T) {
	uassert.Equal(t, 0, New(-5).Cap())
	uassert.Equal(t, MaxBits, New(MaxBits+1000).Cap())
}

func TestPopcount(t *testing.T) {
	uassert.Equal(t, 0, popcount(0))
	uassert.Equal(t, 1, popcount(1))
	uassert.Equal(t, 64, popcount(^uint64(0)))
}

func join(xs []int) string {
	parts := []string{}
	for _, x := range xs {
		parts = append(parts, itoa(x))
	}
	return strings.Join(parts, ",")
}

func itoa(i int) string {
	if i == 0 {
		return "0"
	}
	neg := i < 0
	if neg {
		i = -i
	}
	var b []byte
	for i > 0 {
		b = append([]byte{byte('0' + i%10)}, b...)
		i /= 10
	}
	if neg {
		return "-" + string(b)
	}
	return string(b)
}

gnomod.toml

module = "gno.land/p/nym-moultest123/x/daily/bitset/v0"
gno = "0.9"

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