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

Playground

board.gno

package boards

import "time"

// Board defines a type for boards.
type Board struct {
	// ID is the unique identifier of the board.
	ID ID

	// Name is the current name of the board.
	Name string

	// Aliases contains a list of alternative names for the board.
	Aliases []string

	// Readonly indicates that the board is readonly.
	Readonly bool

	// Threads contains board threads.
	Threads PostStorage

	// ThreadsSequence generates sequential ID for new threads.
	ThreadsSequence IdentifierGenerator

	// Permissions enables support for permissioned boards.
	// This type of boards allows managing members with roles and permissions.
	// It also enables the implementation of permissioned execution of board related features.
	Permissions Permissions

	// Creator is the account address that created the board.
	Creator address

	// Meta allows storing board metadata.
	Meta any

	// CreatedAt is the board's creation time.
	CreatedAt time.Time

	// UpdatedAt is the board's update time.
	UpdatedAt time.Time
}

// New creates a new basic non permissioned board.
func New(id ID) *Board {
	return &Board{
		ID:              id,
		Threads:         NewPostStorage(),
		ThreadsSequence: NewIdentifierGenerator(),
		CreatedAt:       time.Now(),
	}
}

// SetID sets board ID value.
func (board *Board) SetID(v ID) {
	board.ID = v
}

// SetName sets name value.
func (board *Board) SetName(v string) {
	board.Name = v
}

// SetAliases sets board name aliases.
func (board *Board) SetAliases(v []string) {
	board.Aliases = v
}

// SetReadonly sets readonly value.
func (board *Board) SetReadonly(v bool) {
	board.Readonly = v
}

// SetThreadStorage sets the storage where board threads are stored.
func (board *Board) SetThreadStorage(v PostStorage) {
	board.Threads = v
}

// SetThreadsSequence sets the sequential thread ID generator.
func (board *Board) SetThreadsSequence(v IdentifierGenerator) {
	board.ThreadsSequence = v
}

// SetPermissions sets permissions value.
func (board *Board) SetPermissions(v Permissions) {
	board.Permissions = v
}

// SetCreator sets the address of the account that created the board.
func (board *Board) SetCreator(v address) {
	board.Creator = v
}

// SetCreatedAt sets the time when board was created.
func (board *Board) SetCreatedAt(v time.Time) {
	board.CreatedAt = v
}

// SetUpdatedAt sets the time when a board value was updated.
func (board *Board) SetUpdatedAt(v time.Time) {
	board.UpdatedAt = v
}

// SetMeta sets board metadata.
func (board *Board) SetMeta(v any) {
	board.Meta = v
}

board_test.gno

package boards_test

import (
	"testing"

	"gno.land/p/nt/urequire/v0"

	"gno.land/p/gnoland/boards/v0"
)

func TestNew(t *testing.T) {
	board := boards.New(42)

	urequire.Equal(t, 42, int(board.ID), "expect board ID to match")
	urequire.True(t, board.Threads != nil, "expect board to support threads")
	urequire.True(t, board.ThreadsSequence != nil, "expect board to initialize a thread ID generator")
	urequire.False(t, board.CreatedAt.IsZero(), "expect board to have a creation date")
}

flag_storage.gno

package boards

import (
	"strings"

	"gno.land/p/nt/bptree/v0"
	"gno.land/p/nt/ufmt/v0"
)

type (
	// Flag defines a type for post flags
	Flag struct {
		// User is the user that flagged the post.
		User address

		// Reason is the reason that describes why post is flagged.
		Reason string
	}

	// FlagIterFn defines a function type to iterate post flags.
	FlagIterFn func(Flag) bool

	// FlagStorage defines an interface for storing posts flagging information.
	FlagStorage interface {
		// Exists checks if a flag from a user exists
		Exists(address) bool

		// Add adds a new flag from a user.
		Add(Flag) error

		// Remove removes a user flag.
		Remove(address) (removed bool)

		// Size returns the number of flags in the storage.
		Size() int

		// Iterate iterates post flags.
		// To reverse iterate flags use a negative count.
		// If the callback returns true, the iteration is stopped.
		Iterate(start, count int, fn FlagIterFn) bool
	}
)

// NewFlagStorage creates a new storage for post flags.
// The new storage uses an AVL tree to store flagging info.
func NewFlagStorage() FlagStorage {
	return &flagStorage{bptree.NewBPTree32()}
}

type flagStorage struct {
	flags *bptree.BPTree // address -> string(reason)
}

// Exists checks if a flag from a user exists
func (s flagStorage) Exists(addr address) bool {
	return s.flags.Has(addr.String())
}

// Add adds a new flag from a user.
// It fails if a flag from the same user exists.
func (s *flagStorage) Add(f Flag) error {
	if !f.User.IsValid() {
		return ufmt.Errorf("post flagging error, invalid user address: %s", f.User)
	}

	k := f.User.String()
	if s.flags.Has(k) {
		return ufmt.Errorf("flag from user already exists: %s", f.User)
	}

	s.flags.Set(k, strings.TrimSpace(f.Reason))
	return nil
}

// Remove removes a user flag.
func (s *flagStorage) Remove(addr address) bool {
	_, removed := s.flags.Remove(addr.String())
	return removed
}

// Size returns the number of flags in the storage.
func (s flagStorage) Size() int {
	return s.flags.Size()
}

// Iterate iterates post flags.
// To reverse iterate flags use a negative count.
// If the callback returns true, the iteration is stopped.
func (s flagStorage) Iterate(start, count int, fn FlagIterFn) bool {
	if count < 0 {
		return s.flags.ReverseIterateByOffset(start, -count, func(k string, v any) bool {
			return fn(Flag{
				User:   address(k),
				Reason: v.(string),
			})
		})
	}

	return s.flags.IterateByOffset(start, count, func(k string, v any) bool {
		return fn(Flag{
			User:   address(k),
			Reason: v.(string),
		})
	})
}

flag_storage_test.gno

package boards_test

import (
	"testing"

	"gno.land/p/nt/urequire/v0"

	"gno.land/p/gnoland/boards/v0"
)

func TestFlagStorageExists(t *testing.T) {
	tests := []struct {
		name   string
		setup  func() boards.FlagStorage
		user   address
		exists bool
	}{
		{
			name: "found",
			setup: func() boards.FlagStorage {
				s := boards.NewFlagStorage()
				s.Add(boards.Flag{User: "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5"})
				return s
			},
			user:   "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5",
			exists: true,
		},
		{
			name: "not found",
			setup: func() boards.FlagStorage {
				return boards.NewFlagStorage()
			},
			user:   "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5",
			exists: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := tt.setup()

			urequire.Equal(t, tt.exists, s.Exists(tt.user))
		})
	}
}

func TestFlagStorageAdd(t *testing.T) {
	tests := []struct {
		name   string
		setup  func() boards.FlagStorage
		flag   boards.Flag
		errMsg string
	}{
		{
			name: "ok",
			setup: func() boards.FlagStorage {
				return boards.NewFlagStorage()
			},
			flag: boards.Flag{User: "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5"},
		},
		{
			name: "flag exists",
			setup: func() boards.FlagStorage {
				s := boards.NewFlagStorage()
				s.Add(boards.Flag{User: "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5"})
				return s
			},
			flag:   boards.Flag{User: "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5"},
			errMsg: "flag from user already exists: g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5",
		},
		{
			name: "invalid user address",
			setup: func() boards.FlagStorage {
				return boards.NewFlagStorage()
			},
			flag:   boards.Flag{User: "foo"},
			errMsg: "post flagging error, invalid user address: foo",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := tt.setup()

			err := s.Add(tt.flag)

			if tt.errMsg != "" {
				urequire.Error(t, err, "expect an error")
				urequire.ErrorContains(t, err, tt.errMsg, "expect error to match")
				return
			}

			urequire.NoError(t, err, "expect no error")
			urequire.True(t, s.Exists(tt.flag.User), "expect flag to be added")
		})
	}
}

func TestFlagStorageRemove(t *testing.T) {
	tests := []struct {
		name    string
		setup   func() boards.FlagStorage
		address address
		removed bool
	}{
		{
			name: "ok",
			setup: func() boards.FlagStorage {
				s := boards.NewFlagStorage()
				s.Add(boards.Flag{User: "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5"})
				return s
			},
			address: "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5",
			removed: true,
		},
		{
			name: "not found",
			setup: func() boards.FlagStorage {
				return boards.NewFlagStorage()
			},
			address: "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := tt.setup()

			urequire.Equal(t, tt.removed, s.Remove(tt.address))
		})
	}
}

func TestFlagStorageSize(t *testing.T) {
	tests := []struct {
		name  string
		setup func() boards.FlagStorage
		size  int
	}{
		{
			name: "empty",
			setup: func() boards.FlagStorage {
				return boards.NewFlagStorage()
			},
			size: 0,
		},
		{
			name: "one flag",
			setup: func() boards.FlagStorage {
				s := boards.NewFlagStorage()
				s.Add(boards.Flag{User: "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5"})
				return s
			},
			size: 1,
		},
		{
			name: "multiple flags",
			setup: func() boards.FlagStorage {
				s := boards.NewFlagStorage()
				s.Add(boards.Flag{User: "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5"})
				s.Add(boards.Flag{User: "g1skl80cuz8zq3lul9pgz5pc35l2pfzgxgfpsqkx"})
				return s
			},
			size: 2,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := tt.setup()

			urequire.Equal(t, tt.size, s.Size())
		})
	}
}

func TestFlagStorageIterate(t *testing.T) {
	// Listed in sorted (bech32-string) user order, which is the order
	// Iterate yields them in.
	flags := []boards.Flag{
		{
			User:   "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5",
			Reason: "a",
		},
		{
			User:   "g1skl80cuz8zq3lul9pgz5pc35l2pfzgxgfpsqkx",
			Reason: "b",
		},
	}
	tests := []struct {
		name    string
		setup   func() boards.FlagStorage
		reverse bool
		flags   []boards.Flag
	}{
		{
			name: "default",
			setup: func() boards.FlagStorage {
				s := boards.NewFlagStorage()
				s.Add(flags[0])
				s.Add(flags[1])
				return s
			},
			flags: flags,
		},
		{
			name: "reverse",
			setup: func() boards.FlagStorage {
				s := boards.NewFlagStorage()
				s.Add(flags[0])
				s.Add(flags[1])
				return s
			},
			reverse: true,
			flags:   []boards.Flag{flags[1], flags[0]},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := tt.setup()
			count := s.Size()
			if tt.reverse {
				count = -count
			}

			var i int
			s.Iterate(0, count, func(f boards.Flag) bool {
				urequire.Equal(t, tt.flags[i].User, f.User, "expect user to match")
				urequire.Equal(t, tt.flags[i].Reason, f.Reason, "expect reason to match")

				i++
				return false
			})
		})
	}
}

gnomod.toml

module = "gno.land/p/gnoland/boards/v0"
gno = "0.9"

[addpkg]
  creator = "g1edq4dugw0sgat4zxcw9xardvuydqf6cgleuc8p"

id.gno

package boards

import (
	"strconv"
	"strings"

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

const paddedStringLen = 10

// ID defines a type for unique identifiers.
type ID uint64

// String returns the ID as a string.
func (id ID) String() string {
	return strconv.FormatUint(uint64(id), 10)
}

// PaddedString returns the ID as a 10 character string padded with zeroes.
// This value can be used for indexing by ID.
func (id ID) PaddedString() string {
	s := id.String()
	return strings.Repeat("0", paddedStringLen-len(s)) + s
}

// Key returns the ID as a string which can be used to index by ID.
func (id ID) Key() string {
	return seqid.ID(id).String()
}

// IdentifierGenerator defines an interface for sequential unique identifier generators.
type IdentifierGenerator interface {
	// Current returns the last generated ID.
	Last() ID

	// Next generates a new ID or panics if increasing ID overflows.
	Next() ID
}

// NewIdentifierGenerator creates a new sequential unique identifier generator.
func NewIdentifierGenerator() IdentifierGenerator {
	return &idGenerator{}
}

type idGenerator struct {
	last seqid.ID
}

// Current returns the last generated ID.
func (g idGenerator) Last() ID {
	return ID(g.last)
}

// Next generates a new ID or panics if increasing ID overflows.
func (g *idGenerator) Next() ID {
	return ID(g.last.Next())
}

id_test.gno

package boards_test

import (
	"testing"

	"gno.land/p/nt/urequire/v0"

	"gno.land/p/gnoland/boards/v0"
)

func TestID(t *testing.T) {
	id := boards.ID(42)

	urequire.Equal(t, "42", id.String(), "expect string to match")
	urequire.Equal(t, "0000000042", id.PaddedString(), "expect padded string to match")
	urequire.Equal(t, "000001a", id.Key(), "expect key to match")
}

func TestIdentifierGenerator(t *testing.T) {
	g := boards.NewIdentifierGenerator()

	urequire.Equal(t, uint64(0), uint64(g.Last()), "expect default to be 0")
	urequire.Equal(t, uint64(1), uint64(g.Next()), "expect next to be 1")
	urequire.Equal(t, uint64(1), uint64(g.Last()), "expect last to be 1")
	urequire.Equal(t, uint64(2), uint64(g.Next()), "expect next to be 2")
	urequire.Equal(t, uint64(2), uint64(g.Last()), "expect last to be 2")
}

permission_set.gno

package boards

// PermissionSet defines a type to store any number of permissions.
type PermissionSet []uint64

// NewPermissionSet creates a new PermissionSet containing the given permissions.
func NewPermissionSet(perms ...Permission) PermissionSet {
	if len(perms) == 0 {
		return nil
	}

	// Find max permission value to calculate slice size.
	// This allows any number of permissions to be assigned in any order.
	var max Permission
	for _, p := range perms {
		if p > max {
			max = p
		}
	}

	s := make(PermissionSet, int(max)/64+1)
	for _, p := range perms {
		// Calculate the index within the set where the permission should be defined.
		// Each item in the set can contain 64 permissions, for example:
		// - Item 0: permissions 0 to 63
		// - Item 1: permissions 64 to 127
		idx := int(p) / 64

		// Turn on the bit that matches the permission, ranging from bit 0 to 63
		s[idx] |= 1 << (uint(p) % 64)
	}
	return s
}

// Has checks if a permission is in the set.
func (s PermissionSet) Has(p Permission) bool {
	idx := int(p) / 64
	if idx >= len(s) {
		return false
	}

	// Check if the bit for the current permission is on
	return s[idx]&(1<<(uint(p)%64)) != 0
}

// IsEmpty reports whether the set contains no permissions.
func (s PermissionSet) IsEmpty() bool {
	for _, v := range s {
		if v != 0 {
			return false
		}
	}
	return true
}

permission_set_test.gno

package boards

import (
	"testing"

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

func TestNewPermissionSet(t *testing.T) {
	cases := []struct {
		name  string
		perms []Permission
		check []Permission
		want  bool
	}{
		{
			name:  "empty",
			check: []Permission{0},
			want:  false,
		},
		{
			name:  "single permission",
			perms: []Permission{0},
			check: []Permission{0},
			want:  true,
		},
		{
			name:  "multiple permissions",
			perms: []Permission{1, 3, 5},
			check: []Permission{1, 3, 5},
			want:  true,
		},
		{
			name:  "high permission value",
			perms: []Permission{100},
			check: []Permission{100},
			want:  true,
		},
		{
			name:  "missing permission",
			perms: []Permission{100},
			check: []Permission{0},
			want:  false,
		},
		{
			name:  "multiple missing permissions",
			perms: []Permission{1, 3, 5},
			check: []Permission{0, 2, 4},
			want:  false,
		},
	}

	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			s := NewPermissionSet(tc.perms...)

			for _, p := range tc.check {
				uassert.Equal(t, tc.want, s.Has(p))
			}
		})
	}
}

func TestPermissionSetHas(t *testing.T) {
	cases := []struct {
		name  string
		set   PermissionSet
		check Permission
		want  bool
	}{
		{
			name:  "out of range",
			set:   NewPermissionSet(0),
			check: 100,
			want:  false,
		},
		{
			name:  "nil set",
			check: 0,
			want:  false,
		},
		{
			name:  "permission present",
			set:   NewPermissionSet(5),
			check: 5,
			want:  true,
		},
	}

	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			uassert.Equal(t, tc.want, tc.set.Has(tc.check))
		})
	}
}

func TestPermissionSetIsEmpty(t *testing.T) {
	cases := []struct {
		name string
		set  PermissionSet
		want bool
	}{
		{
			name: "nil set",
			want: true,
		},
		{
			name: "non-empty set",
			set:  NewPermissionSet(0),
			want: false,
		},
		{
			name: "empty allocated set",
			set:  make(PermissionSet, 1),
			want: true,
		},
	}

	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			uassert.Equal(t, tc.want, tc.set.IsEmpty())
		})
	}
}

permissions.gno

package boards

import "strconv"

type (
	// Role defines the type for user roles.
	Role string

	// Args is a list of generic arguments.
	Args []interface{}

	// User contains user info.
	User struct {
		Address address
		Roles   []Role
	}

	// UsersIterFn defines a function type to iterate users.
	UsersIterFn func(User) bool

	// Permissions define an interface to for permissioned execution.
	Permissions interface {
		// HasRole checks if a user has a specific role assigned.
		HasRole(address, Role) bool

		// HasPermission checks if a user has a specific permission.
		HasPermission(address, Permission) bool

		// WithPermission calls a callback when a user has a specific permission.
		// It panics on error.
		//
		// An inline crossing function call can be used by the implementation if
		// crossing is required to update its internal state, for example to create
		// proposals that when approved execute the callback:
		//
		//  func(realm) {
		//    // Update internal realm state
		//    // ...
		//  }(cross)
		WithPermission(address, Permission, Args, func())

		// SetUserRoles adds a new user when it doesn't exist and sets its roles.
		// Method can also be called to change the roles of an existing user.
		// It panics on error.
		SetUserRoles(address, ...Role)

		// RemoveUser removes a user from the permissioner.
		// It panics on error.
		RemoveUser(address) (removed bool)

		// HasUser checks if a user exists.
		HasUser(address) bool

		// UsersCount returns the total number of users the permissioner contains.
		UsersCount() int

		// IterateUsers iterates permissions' users.
		IterateUsers(start, count int, fn UsersIterFn) bool
	}
)

// Permission defines the type for permissions.
type Permission uint16

// String returns the string representation of a permission value.
func (p Permission) String() string {
	return strconv.FormatUint(uint64(p), 10)
}

post.gno

package boards

import (
	"strings"
	"time"
)

// Post defines a generic type for posts.
// A post can be either a thread or a reply.
type Post struct {
	// ID is the unique identifier of the post.
	ID ID

	// ParentID is the ID of the parent post.
	ParentID ID

	// ThreadID contains the post ID of the thread where current post is created.
	// If current post is a thread it contains post's ID.
	// It should be used when current post is a thread or reply.
	ThreadID ID

	// OriginalBoardID contains the board ID of the original post when current post is a repost.
	OriginalBoardID ID

	// Board contains the board where post is created.
	Board *Board

	// Title contains the post's title.
	Title string

	// Body contains content of the post.
	Body string

	// Hidden indicates that the post is hidden.
	Hidden bool

	// Readonly indicates that the post is readonly.
	Readonly bool

	// Replies stores post replies.
	Replies PostStorage

	// Reposts stores reposts of the current post.
	// It should be used when post is a thread.
	Reposts RepostStorage

	// Flags stores users flags for the current post.
	Flags FlagStorage

	// Creator is the account address that created the post.
	Creator address

	// Meta allows storing post metadata.
	Meta any

	// CreatedAt is the post's creation time.
	CreatedAt time.Time

	// UpdatedAt is the post's update time.
	UpdatedAt time.Time
}

// Summary return a summary of the post's body.
// It returns the body making sure that the length is limited to 80 characters.
func (post Post) Summary() string {
	return SummaryOf(post.Body, 80)
}

// SetID sets post ID value.
func (post *Post) SetID(v ID) {
	post.ID = v
}

// SetParentID sets post's parent ID value.
func (post *Post) SetParentID(v ID) {
	post.ParentID = v
}

// SetThreadID sets thread ID value.
func (post *Post) SetThreadID(v ID) {
	post.ThreadID = v
}

// SetOriginalBoardID sets the board ID of the original post when current post is a repost.
func (post *Post) SetOriginalBoardID(v ID) {
	post.OriginalBoardID = v
}

// SetBoard sets the board where post was created.
func (post *Post) SetBoard(v *Board) {
	post.Board = v
}

// SetTitle sets title value.
func (post *Post) SetTitle(v string) {
	post.Title = v
}

// SetBody sets post's content.
func (post *Post) SetBody(v string) {
	post.Body = v
}

// SetHidden sets hidden value.
func (post *Post) SetHidden(v bool) {
	post.Hidden = v
}

// SetReadonly sets readonly value.
func (post *Post) SetReadonly(v bool) {
	post.Readonly = v
}

// SetReplyStorage sets the storage where post replies are stored.
func (post *Post) SetReplyStorage(v PostStorage) {
	post.Replies = v
}

// SetRepostStorage sets the storage where thread reposts are stored.
func (post *Post) SetRepostStorage(v RepostStorage) {
	post.Reposts = v
}

// SetFlagStorage sets the storage where post flags are stored.
func (post *Post) SetFlagStorage(v FlagStorage) {
	post.Flags = v
}

// SetCreator sets the address of the account that created the post.
func (post *Post) SetCreator(v address) {
	post.Creator = v
}

// SetCreatedAt sets the time when post was created.
func (post *Post) SetCreatedAt(v time.Time) {
	post.CreatedAt = v
}

// SetUpdatedAt sets the time when a post value was updated.
func (post *Post) SetUpdatedAt(v time.Time) {
	post.UpdatedAt = v
}

// IsThread checks if a post is a thread.
// When a post is not a thread it's considered a thread's reply/comment.
func IsThread(p *Post) bool {
	if p == nil {
		return false
	}
	return p.ThreadID == p.ID
}

// IsRepost checks if a thread is a repost.
func IsRepost(thread *Post) bool {
	if thread == nil {
		return false
	}
	return thread.OriginalBoardID != 0
}

// SummaryOf returns a summary of a text.
func SummaryOf(text string, length int) string {
	text = strings.TrimSpace(text)
	if text == "" {
		return ""
	}

	lines := strings.SplitN(text, "\n", 2)
	line := lines[0]
	if len(line) > length {
		line = line[:(length-3)] + "..."
	} else if len(lines) > 1 {
		line = line + "..."
	}
	return line
}

post_storage.gno

package boards

import (
	"errors"

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

type (
	// PostIterFn defines a function type to iterate posts.
	PostIterFn func(*Post) bool

	// PostStorage defines an interface for posts storage.
	PostStorage interface {
		// Get retruns a post that matches an ID.
		Get(ID) (_ *Post, found bool)

		// Remove removes a post from the storage.
		Remove(ID) (_ *Post, removed bool)

		// Add adds a post in the storage.
		Add(*Post) error

		// Size returns the number of posts in the storage.
		Size() int

		// Iterate iterates posts.
		// To reverse iterate posts use a negative count.
		// If the callback returns true, the iteration is stopped.
		Iterate(start, count int, fn PostIterFn) bool
	}
)

// NewPostStorage creates a new storage for posts.
// The new storage uses an AVL tree to store posts.
func NewPostStorage() PostStorage {
	return &postStorage{bptree.NewBPTree32()}
}

type postStorage struct {
	posts *bptree.BPTree // string(Post.ID) -> *Post
}

// Get retruns a post that matches an ID.
func (s postStorage) Get(id ID) (*Post, bool) {
	k := makePostKey(id)
	v := s.posts.Get(k)
	if v == nil {
		return nil, false
	}
	return v.(*Post), true
}

// Remove removes a post from the storage.
func (s *postStorage) Remove(id ID) (*Post, bool) {
	k := makePostKey(id)
	v, removed := s.posts.Remove(k)
	if !removed {
		return nil, false
	}
	return v.(*Post), true
}

// Add adds a post in the storage.
// It updates existing posts when storage contains one with the same ID.
func (s *postStorage) Add(p *Post) error {
	if p == nil {
		return errors.New("saving nil posts is not allowed")
	}

	s.posts.Set(makePostKey(p.ID), p)
	return nil
}

// Size returns the number of posts in the storage.
func (s postStorage) Size() int {
	return s.posts.Size()
}

// Iterate iterates posts.
// To reverse iterate posts use a negative count.
// If the callback returns true, the iteration is stopped.
func (s postStorage) Iterate(start, count int, fn PostIterFn) bool {
	if count < 0 {
		return s.posts.ReverseIterateByOffset(start, -count, func(_ string, v any) bool {
			return fn(v.(*Post))
		})
	}

	return s.posts.IterateByOffset(start, count, func(_ string, v any) bool {
		return fn(v.(*Post))
	})
}

func makePostKey(postID ID) string {
	return postID.PaddedString()
}

post_storage_test.gno

package boards_test

import (
	"testing"

	"gno.land/p/nt/urequire/v0"

	"gno.land/p/gnoland/boards/v0"
)

func TestPostStorageGet(t *testing.T) {
	tests := []struct {
		name   string
		setup  func() boards.PostStorage
		postID boards.ID
		found  bool
	}{
		{
			name: "single post",
			setup: func() boards.PostStorage {
				s := boards.NewPostStorage()
				s.Add(&boards.Post{ID: 1})
				return s
			},
			postID: 1,
			found:  true,
		},
		{
			name: "multiple posts",
			setup: func() boards.PostStorage {
				s := boards.NewPostStorage()
				s.Add(&boards.Post{ID: 1})
				s.Add(&boards.Post{ID: 2})
				s.Add(&boards.Post{ID: 3})
				return s
			},
			postID: 2,
			found:  true,
		},
		{
			name: "not found",
			setup: func() boards.PostStorage {
				return boards.NewPostStorage()
			},
			postID: 404,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := tt.setup()

			post, found := s.Get(tt.postID)

			if !tt.found {
				urequire.False(t, found, "expect post not to be found")
				urequire.True(t, post == nil, "expect post to be nil")
				return
			}

			urequire.True(t, found, "expect post to be found")
			urequire.False(t, post == nil, "expect post not to be nil")
			urequire.Equal(t, tt.postID.String(), post.ID.String(), "expect post ID to match")
		})
	}
}

func TestPostStorageRemove(t *testing.T) {
	tests := []struct {
		name    string
		setup   func() boards.PostStorage
		postID  boards.ID
		removed bool
	}{
		{
			name: "ok",
			setup: func() boards.PostStorage {
				s := boards.NewPostStorage()
				s.Add(&boards.Post{ID: 1})
				s.Add(&boards.Post{ID: 2})
				return s
			},
			postID:  2,
			removed: true,
		},
		{
			name: "not found",
			setup: func() boards.PostStorage {
				return boards.NewPostStorage()
			},
			postID: 404,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := tt.setup()

			post, removed := s.Remove(tt.postID)

			if !tt.removed {
				urequire.False(t, removed, "expect post not to be removed")
				urequire.True(t, post == nil, "expect post to be nil")
				return
			}

			urequire.True(t, removed, "expect post to be removed")
			urequire.False(t, post == nil, "expect post not to be nil")
			urequire.Equal(t, tt.postID.String(), post.ID.String(), "expect post ID to match")

			_, found := s.Get(tt.postID)
			urequire.False(t, found, "expect post not to be found")
		})
	}
}

func TestPostStorageAdd(t *testing.T) {
	tests := []struct {
		name   string
		post   *boards.Post
		errMsg string
	}{
		{
			name: "ok",
			post: &boards.Post{ID: 1},
		},
		{
			name:   "nil post",
			post:   nil,
			errMsg: "saving nil posts is not allowed",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := boards.NewPostStorage()

			err := s.Add(tt.post)

			if tt.errMsg != "" {
				urequire.Error(t, err, "expect an error")
				urequire.ErrorContains(t, err, tt.errMsg, "expect error to match")
				return
			}

			urequire.NoError(t, err, "expect no error")

			_, found := s.Get(tt.post.ID)
			urequire.True(t, found, "expect post to be found")
		})
	}
}

func TestPostStorageSize(t *testing.T) {
	tests := []struct {
		name  string
		setup func() boards.PostStorage
		size  int
	}{
		{
			name: "empty",
			setup: func() boards.PostStorage {
				return boards.NewPostStorage()
			},
			size: 0,
		},
		{
			name: "one post",
			setup: func() boards.PostStorage {
				s := boards.NewPostStorage()
				s.Add(&boards.Post{ID: 1})
				return s
			},
			size: 1,
		},
		{
			name: "multiple posts",
			setup: func() boards.PostStorage {
				s := boards.NewPostStorage()
				s.Add(&boards.Post{ID: 1})
				s.Add(&boards.Post{ID: 2})
				return s
			},
			size: 2,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := tt.setup()

			urequire.Equal(t, tt.size, s.Size())
		})
	}
}

func TestPostStorageIterate(t *testing.T) {
	tests := []struct {
		name    string
		setup   func() boards.PostStorage
		reverse bool
		ids     []boards.ID
	}{
		{
			name: "default",
			setup: func() boards.PostStorage {
				s := boards.NewPostStorage()
				s.Add(&boards.Post{ID: 1})
				s.Add(&boards.Post{ID: 2})
				s.Add(&boards.Post{ID: 3})
				return s
			},
			ids: []boards.ID{1, 2, 3},
		},
		{
			name: "reverse",
			setup: func() boards.PostStorage {
				s := boards.NewPostStorage()
				s.Add(&boards.Post{ID: 1})
				s.Add(&boards.Post{ID: 2})
				s.Add(&boards.Post{ID: 3})
				return s
			},
			reverse: true,
			ids:     []boards.ID{3, 2, 1},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := tt.setup()
			count := s.Size()
			if tt.reverse {
				count = -count
			}

			var i int
			s.Iterate(0, count, func(p *boards.Post) bool {
				urequire.True(t, tt.ids[i] == p.ID, "expect post ID to match")

				i++
				return false
			})
		})
	}
}

post_test.gno

package boards_test

import (
	"strings"
	"testing"

	"gno.land/p/nt/urequire/v0"

	"gno.land/p/gnoland/boards/v0"
)

func TestPostSummary(t *testing.T) {
	post := &boards.Post{ID: 1, Body: strings.Repeat("X", 900)}
	summary := post.Summary()
	urequire.True(t, strings.HasSuffix(summary, "..."), "expect dotted suffix")
	urequire.True(t, len(summary) == 80, "expect summary length to match")
}

func TestIsThread(t *testing.T) {
	post := &boards.Post{ID: 1, ThreadID: 1} // IDs match
	urequire.True(t, boards.IsThread(post), "expect post to be a thread")
	urequire.False(t, boards.IsThread(nil), "expect nil not to be a thread")

	post = &boards.Post{ID: 2, ThreadID: 1} // IDs doesn't match
	urequire.False(t, boards.IsThread(post), "expect post not to be a thread")
}

func TestIsRepost(t *testing.T) {
	post := &boards.Post{ID: 1, OriginalBoardID: 1} // Original board ID available
	urequire.True(t, boards.IsRepost(post), "expect post to be a repost")
	urequire.False(t, boards.IsRepost(nil), "expect nil not to be a repost")

	post = &boards.Post{ID: 1} // Original board ID not available
	urequire.False(t, boards.IsRepost(post), "expect post not to be a repost")
}

func TestSummaryOf(t *testing.T) {
	summary := boards.SummaryOf(strings.Repeat("X", 90), 80)
	urequire.True(t, strings.HasSuffix(summary, "..."), "expect dotted suffix")
	urequire.True(t, len(summary) == 80, "expect summary length to match")

	summary = boards.SummaryOf(strings.Repeat(" ", 90), 80)
	urequire.Empty(t, summary, "expect summary to be empty")
}

reply.gno

package boards

import (
	"errors"
	"strings"
	"time"

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

// NewReply creates a new reply to a thread or another reply.
func NewReply(parent *Post, creator address, body string) (*Post, error) {
	if parent == nil {
		return nil, errors.New("reply requires a parent thread or reply")
	}

	if parent.ThreadID == 0 {
		return nil, errors.New("parent has no thread ID assigned")
	}

	if parent.Board == nil {
		return nil, errors.New("parent has no board assigned")
	}

	if !creator.IsValid() {
		return nil, ufmt.Errorf("invalid reply creator address: %s", creator)
	}

	body = strings.TrimSpace(body)
	if body == "" {
		return nil, errors.New("reply body is required")
	}

	id := parent.Board.ThreadsSequence.Next()
	return &Post{
		ID:        id,
		ParentID:  parent.ID,
		ThreadID:  parent.ThreadID,
		Board:     parent.Board,
		Body:      body,
		Replies:   NewPostStorage(),
		Flags:     NewFlagStorage(),
		Creator:   creator,
		CreatedAt: time.Now(),
	}, nil
}

// MustNewReply creates a new reply or panics on error.
func MustNewReply(parent *Post, creator address, body string) *Post {
	p, err := NewReply(parent, creator, body)
	if err != nil {
		panic(err)
	}
	return p
}

reply_test.gno

package boards_test

import (
	"testing"

	"gno.land/p/nt/urequire/v0"

	"gno.land/p/gnoland/boards/v0"
)

func TestNewReply(t *testing.T) {
	tests := []struct {
		name    string
		parent  func() *boards.Post
		creator address
		body    string
		errMsg  string
	}{
		{
			name: "ok",
			parent: func() *boards.Post {
				board := boards.New(1)
				id := board.ThreadsSequence.Next()
				return &boards.Post{
					ID:       id,
					ThreadID: id,
					Board:    board,
				}
			},
			creator: "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5",
			body:    "Foo",
		},
		{
			name:   "nil parent",
			parent: func() *boards.Post { return nil },
			errMsg: "reply requires a parent thread or reply",
		},
		{
			name: "parent without thread ID",
			parent: func() *boards.Post {
				return &boards.Post{ID: 1}
			},
			errMsg: "parent has no thread ID assigned",
		},
		{
			name: "parent without board",
			parent: func() *boards.Post {
				return &boards.Post{ID: 1, ThreadID: 1}
			},
			errMsg: "parent has no board assigned",
		},
		{
			name: "invalid creator",
			parent: func() *boards.Post {
				return &boards.Post{ID: 1, ThreadID: 1, Board: boards.New(1)}
			},
			creator: "foo",
			errMsg:  "invalid reply creator address: foo",
		},
		{
			name: "empty body",
			parent: func() *boards.Post {
				return &boards.Post{ID: 1, ThreadID: 1, Board: boards.New(1)}
			},
			creator: "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5",
			body:    "",
			errMsg:  "reply body is required",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			parent := tt.parent()

			reply, err := boards.NewReply(parent, tt.creator, tt.body)

			if tt.errMsg != "" {
				urequire.Error(t, err, "expect an error")
				urequire.ErrorContains(t, err, tt.errMsg, "expect error to match")
				return
			}

			urequire.NoError(t, err, "expect no error")
			urequire.True(t, parent.Board.ThreadsSequence.Last() == reply.ID, "expect ID to match")
			urequire.True(t, parent.ID == reply.ParentID, "expect parent ID to match")
			urequire.True(t, parent.ThreadID == reply.ThreadID, "expect thread ID to match")
			urequire.False(t, reply.Board == nil, "expect board to be assigned")
			urequire.True(t, parent.Board.ID == reply.Board.ID, "expect board ID to match")
			urequire.Equal(t, tt.body, reply.Body, "expect body to match")
			urequire.True(t, reply.Replies != nil, "expect reply to support sub-replies")
			urequire.True(t, reply.Flags != nil, "expect reply to support flagging")
			urequire.Equal(t, tt.creator, reply.Creator, "expect creator to match")
			urequire.False(t, reply.CreatedAt.IsZero(), "expect creation date to be assigned")
		})
	}
}

repost_storage.gno

package boards

import (
	"errors"

	"gno.land/p/nt/bptree/v0"
	"gno.land/p/nt/seqid/v0"
)

type (
	// RepostIterFn defines a function type to iterate reposts.
	RepostIterFn func(board, repost ID) bool

	// RepostStorage defines an interface for storing reposts.
	RepostStorage interface {
		// Get returns the repost ID for a board.
		Get(board ID) (repost ID, found bool)

		// Add adds a new repost to the storage.
		Add(repost *Post) error

		// Remove removes repost for a board.
		Remove(board ID) (removed bool)

		// Size returns the number of reposts in the storage.
		Size() int

		// Iterate iterates reposts.
		// To reverse iterate reposts use a negative count.
		// If the callback returns true, the iteration is stopped.
		Iterate(start, count int, fn RepostIterFn) bool
	}
)

// NewRepostStorage creates a new storage for reposts.
// The new storage uses an AVL tree to store reposts.
func NewRepostStorage() RepostStorage {
	return &repostStorage{bptree.NewBPTree32()}
}

type repostStorage struct {
	reposts *bptree.BPTree // string(Board.ID) -> Post.ID
}

// Get returns the repost ID for a board.
func (s repostStorage) Get(boardID ID) (ID, bool) {
	v := s.reposts.Get(boardID.Key())
	if v == nil {
		return 0, false
	}
	return v.(ID), true
}

// Add adds a new repost to the storage.
func (s *repostStorage) Add(repost *Post) error {
	if repost == nil {
		return errors.New("saving nil reposts is not allowed")
	}

	s.reposts.Set(repost.Board.ID.Key(), repost.ID)
	return nil
}

// Remove removes repost for a board.
func (s *repostStorage) Remove(boardID ID) bool {
	_, removed := s.reposts.Remove(boardID.Key())
	return removed
}

// Size returns the number of reposts in the storage.
func (s repostStorage) Size() int {
	return s.reposts.Size()
}

// Iterate iterates reposts.
// To reverse iterate reposts use a negative count.
// If the callback returns true, the iteration is stopped.
func (s repostStorage) Iterate(start, count int, fn RepostIterFn) bool {
	if count < 0 {
		return s.reposts.ReverseIterateByOffset(start, -count, func(k string, v any) bool {
			id, err := seqid.FromString(k)
			if err != nil {
				panic(err)
			}

			return fn(ID(id), v.(ID))
		})
	}

	return s.reposts.IterateByOffset(start, count, func(k string, v any) bool {
		id, err := seqid.FromString(k)
		if err != nil {
			panic(err)
		}

		return fn(ID(id), v.(ID))
	})
}

repost_storage_test.gno

package boards_test

import (
	"testing"

	"gno.land/p/nt/urequire/v0"

	"gno.land/p/gnoland/boards/v0"
)

func TestRepostStorageGet(t *testing.T) {
	tests := []struct {
		name              string
		setup             func() boards.RepostStorage
		boardID, repostID boards.ID
		found             bool
	}{
		{
			name: "single repost",
			setup: func() boards.RepostStorage {
				s := boards.NewRepostStorage()
				s.Add(&boards.Post{
					ID:    1,
					Board: &boards.Board{ID: 1},
				})
				return s
			},
			boardID:  1,
			repostID: 1,
			found:    true,
		},
		{
			name: "multiple reposts",
			setup: func() boards.RepostStorage {
				s := boards.NewRepostStorage()
				s.Add(&boards.Post{
					ID:    2,
					Board: &boards.Board{ID: 1},
				})
				s.Add(&boards.Post{
					ID:    5,
					Board: &boards.Board{ID: 2},
				})
				s.Add(&boards.Post{
					ID:    10,
					Board: &boards.Board{ID: 3},
				})
				return s
			},
			boardID:  1,
			repostID: 2,
			found:    true,
		},
		{
			name: "not found",
			setup: func() boards.RepostStorage {
				return boards.NewRepostStorage()
			},
			boardID: 404,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := tt.setup()

			repostID, found := s.Get(tt.boardID)

			if !tt.found {
				urequire.False(t, found, "expect repost not to be found")
				urequire.True(t, int(repostID) == 0, "expect repost ID to be 0")
				return
			}

			urequire.True(t, found, "expect post to be found")
			urequire.Equal(t, tt.repostID.String(), repostID.String(), "expect repost ID to match")
		})
	}
}

func TestRepostStorageAdd(t *testing.T) {
	tests := []struct {
		name   string
		repost *boards.Post
		errMsg string
	}{
		{
			name: "ok",
			repost: &boards.Post{
				ID:    1,
				Board: &boards.Board{ID: 1},
			},
		},
		{
			name:   "nil repost",
			repost: nil,
			errMsg: "saving nil reposts is not allowed",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := boards.NewRepostStorage()

			err := s.Add(tt.repost)

			if tt.errMsg != "" {
				urequire.Error(t, err, "expect an error")
				urequire.ErrorContains(t, err, tt.errMsg, "expect error to match")
				return
			}

			urequire.NoError(t, err, "expect no error")

			_, found := s.Get(tt.repost.ID)
			urequire.True(t, found, "expect repost to be found")
		})
	}
}

func TestRepostStorageRemove(t *testing.T) {
	tests := []struct {
		name    string
		setup   func() boards.RepostStorage
		boardID boards.ID
		removed bool
	}{
		{
			name: "ok",
			setup: func() boards.RepostStorage {
				s := boards.NewRepostStorage()
				s.Add(&boards.Post{
					ID:    100,
					Board: &boards.Board{ID: 1},
				})
				return s
			},
			boardID: 1,
			removed: true,
		},
		{
			name: "not found",
			setup: func() boards.RepostStorage {
				return boards.NewRepostStorage()
			},
			boardID: 404,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := tt.setup()

			removed := s.Remove(tt.boardID)

			if !tt.removed {
				urequire.False(t, removed, "expect repost not to be removed")
				return
			}

			urequire.True(t, removed, "expect repost to be removed")

			_, found := s.Get(tt.boardID)
			urequire.False(t, found, "expect repost not to be found")
		})
	}
}

func TestRepostStorageSize(t *testing.T) {
	tests := []struct {
		name  string
		setup func() boards.RepostStorage
		size  int
	}{
		{
			name: "empty",
			setup: func() boards.RepostStorage {
				return boards.NewRepostStorage()
			},
			size: 0,
		},
		{
			name: "one repost",
			setup: func() boards.RepostStorage {
				s := boards.NewRepostStorage()
				s.Add(&boards.Post{
					ID:    1,
					Board: &boards.Board{ID: 1},
				})
				return s
			},
			size: 1,
		},
		{
			name: "multiple reposts",
			setup: func() boards.RepostStorage {
				s := boards.NewRepostStorage()
				s.Add(&boards.Post{
					ID:    1,
					Board: &boards.Board{ID: 1},
				})
				s.Add(&boards.Post{
					ID:    1,
					Board: &boards.Board{ID: 2},
				})
				return s
			},
			size: 2,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := tt.setup()

			urequire.Equal(t, tt.size, s.Size())
		})
	}
}

func TestRepostStorageIterate(t *testing.T) {
	tests := []struct {
		name    string
		setup   func() boards.RepostStorage
		reverse bool
		ids     [][2]boards.ID
	}{
		{
			name: "default",
			setup: func() boards.RepostStorage {
				s := boards.NewRepostStorage()
				s.Add(&boards.Post{
					ID:    10,
					Board: &boards.Board{ID: 1},
				})
				s.Add(&boards.Post{
					ID:    20,
					Board: &boards.Board{ID: 2},
				})
				s.Add(&boards.Post{
					ID:    30,
					Board: &boards.Board{ID: 3},
				})
				return s
			},
			ids: [][2]boards.ID{
				{1, 10},
				{2, 20},
				{3, 30},
			},
		},
		{
			name: "reverse",
			setup: func() boards.RepostStorage {
				s := boards.NewRepostStorage()
				s.Add(&boards.Post{
					ID:    10,
					Board: &boards.Board{ID: 1},
				})
				s.Add(&boards.Post{
					ID:    20,
					Board: &boards.Board{ID: 2},
				})
				s.Add(&boards.Post{
					ID:    30,
					Board: &boards.Board{ID: 3},
				})
				return s
			},
			reverse: true,
			ids: [][2]boards.ID{
				{3, 30},
				{2, 20},
				{1, 10},
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := tt.setup()
			count := s.Size()
			if tt.reverse {
				count = -count
			}

			var i int
			s.Iterate(0, count, func(boardID, repostID boards.ID) bool {
				urequire.True(t, tt.ids[i][0] == boardID, "expect board ID to match")
				urequire.True(t, tt.ids[i][1] == repostID, "expect repost ID to match")

				i++
				return false
			})
		})
	}
}

storage.gno

package boards

import (
	"errors"
	"strings"

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

type (
	// BoardIterFn defines a function type to iterate boards.
	BoardIterFn func(*Board) bool

	// Storage defines an interface for boards storage.
	Storage interface {
		// Get retruns a boards that matches an ID.
		Get(ID) (_ *Board, found bool)

		// GetByName retruns a boards that matches a name.
		GetByName(name string) (_ *Board, found bool)

		// Remove removes a board from the storage.
		Remove(ID) (_ *Board, removed bool)

		// Add adds a board to the storage.
		Add(*Board) error

		// Size returns the number of boards in the storage.
		Size() int

		// Iterate iterates boards.
		// To reverse iterate boards use a negative count.
		// If the callback returns true, the iteration is stopped.
		Iterate(start, count int, fn BoardIterFn) bool
	}
)

// NewStorage creates a new boards storage.
func NewStorage() Storage {
	return &storage{
		byID:   bptree.NewBPTree32(),
		byName: bptree.NewBPTree32(),
	}
}

type storage struct {
	byID   *bptree.BPTree // string(Board.ID) -> *Board
	byName *bptree.BPTree // Board.Name -> Board.ID
}

// Get returns a board for a specific ID.
func (s storage) Get(boardID ID) (*Board, bool) {
	key := makeBoardKey(boardID)
	v := s.byID.Get(key)
	if v == nil {
		return nil, false
	}
	return v.(*Board), true
}

// Get returns a board for a specific name.
func (s storage) GetByName(name string) (*Board, bool) {
	key := makeBoardNameKey(name)
	v := s.byName.Get(key)
	if v == nil {
		return nil, false
	}
	return s.Get(v.(ID))
}

// Remove removes a board from the storage.
// It returns false when board is not found.
func (s *storage) Remove(boardID ID) (*Board, bool) {
	board, found := s.Get(boardID)
	if !found {
		return nil, false
	}

	// Remove indexes for current and previous board names
	names := append([]string{board.Name}, board.Aliases...)
	for _, name := range names {
		key := makeBoardNameKey(name)

		// Make sure that name is indexed to the board being removed
		v := s.byName.Get(key)
		if v != nil && v.(ID) == boardID {
			s.byName.Remove(key)
		}
	}

	key := makeBoardKey(board.ID)
	_, removed := s.byID.Remove(key)
	return board, removed
}

// Add adds a board to the storage.
// If board already exists it updates storage by reindexing the board by ID and name.
// When board name changes it's indexed so it can be found with the new and previous names.
func (s *storage) Add(board *Board) error {
	if board == nil {
		return errors.New("adding nil boards to the storage is not allowed")
	}

	key := makeBoardKey(board.ID)
	s.byID.Set(key, board)

	// Index by name when the optional board name is not empty
	if key = makeBoardNameKey(board.Name); key != "" {
		s.byName.Set(key, board.ID)
	}
	return nil
}

// Size returns the number of boards in the storage.
func (s storage) Size() int {
	return s.byID.Size()
}

// Iterate iterates boards.
// To reverse iterate boards use a negative count.
// If the callback returns true, the iteration is stopped.
func (s storage) Iterate(start, count int, fn BoardIterFn) bool {
	if count < 0 {
		return s.byID.ReverseIterateByOffset(start, -count, func(_ string, v any) bool {
			return fn(v.(*Board))
		})
	}

	return s.byID.IterateByOffset(start, count, func(_ string, v any) bool {
		return fn(v.(*Board))
	})
}

func makeBoardKey(boardID ID) string {
	return boardID.Key()
}

func makeBoardNameKey(name string) string {
	name = strings.TrimSpace(name)
	return strings.ToLower(name)
}

storage_test.gno

package boards_test

import (
	"testing"

	"gno.land/p/nt/urequire/v0"

	"gno.land/p/gnoland/boards/v0"
)

func TestStorageGet(t *testing.T) {
	tests := []struct {
		name    string
		setup   func() boards.Storage
		boardID boards.ID
		found   bool
	}{
		{
			name: "single board",
			setup: func() boards.Storage {
				s := boards.NewStorage()
				s.Add(&boards.Board{ID: 1})
				return s
			},
			boardID: 1,
			found:   true,
		},
		{
			name: "multiple boards",
			setup: func() boards.Storage {
				s := boards.NewStorage()
				s.Add(&boards.Board{ID: 1})
				s.Add(&boards.Board{ID: 2})
				s.Add(&boards.Board{ID: 3})
				return s
			},
			boardID: 2,
			found:   true,
		},
		{
			name: "not found",
			setup: func() boards.Storage {
				return boards.NewStorage()
			},
			boardID: 404,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := tt.setup()

			board, found := s.Get(tt.boardID)

			if !tt.found {
				urequire.False(t, found, "expect board not to be found")
				urequire.True(t, board == nil, "expect board to be nil")
				return
			}

			urequire.True(t, found, "expect board to be found")
			urequire.False(t, board == nil, "expect board not to be nil")
			urequire.Equal(t, tt.boardID.String(), board.ID.String(), "expect board ID to match")
		})
	}
}

func TestStorageGetByName(t *testing.T) {
	tests := []struct {
		name      string
		setup     func() boards.Storage
		boardName string
		found     bool
	}{
		{
			name: "single board",
			setup: func() boards.Storage {
				s := boards.NewStorage()
				s.Add(&boards.Board{ID: 1, Name: "A"})
				return s
			},
			boardName: "A",
			found:     true,
		},
		{
			name: "multiple boards",
			setup: func() boards.Storage {
				s := boards.NewStorage()
				s.Add(&boards.Board{ID: 1, Name: "A"})
				s.Add(&boards.Board{ID: 2, Name: "B"})
				s.Add(&boards.Board{ID: 3, Name: "C"})
				return s
			},
			boardName: "B",
			found:     true,
		},
		{
			name: "not found",
			setup: func() boards.Storage {
				return boards.NewStorage()
			},
			boardName: "foo",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := tt.setup()

			board, found := s.GetByName(tt.boardName)

			if !tt.found {
				urequire.False(t, found, "expect board not to be found")
				urequire.True(t, board == nil, "expect board to be nil")
				return
			}

			urequire.True(t, found, "expect board to be found")
			urequire.False(t, board == nil, "expect board not to be nil")
			urequire.Equal(t, tt.boardName, board.Name, "expect board name to match")
		})
	}
}

func TestStorageRemove(t *testing.T) {
	tests := []struct {
		name       string
		setup      func() boards.Storage
		boardID    boards.ID
		boardNames []string
		removed    bool
	}{
		{
			name: "ok",
			setup: func() boards.Storage {
				s := boards.NewStorage()
				s.Add(&boards.Board{ID: 1, Name: "A"})
				s.Add(&boards.Board{ID: 2, Name: "B"})
				return s
			},
			boardID:    2,
			boardNames: []string{"B"},
			removed:    true,
		},
		{
			name: "ok with aliases",
			setup: func() boards.Storage {
				s := boards.NewStorage()
				s.Add(&boards.Board{ID: 1, Name: "A"})

				b := &boards.Board{ID: 2, Name: "B"}
				s.Add(b)

				b.Aliases = []string{"A"}
				b.Name = "C"
				s.Add(b)

				return s
			},
			boardID:    2,
			boardNames: []string{"B", "C"},
			removed:    true,
		},
		{
			name: "not found",
			setup: func() boards.Storage {
				return boards.NewStorage()
			},
			boardID: 404,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := tt.setup()

			board, removed := s.Remove(tt.boardID)

			if !tt.removed {
				urequire.False(t, removed, "expect board not to be removed")
				urequire.True(t, board == nil, "expect board to be nil")
				return
			}

			urequire.True(t, removed, "expect board to be removed")
			urequire.False(t, board == nil, "expect board not to be nil")
			urequire.Equal(t, tt.boardID.String(), board.ID.String(), "expect board ID to match")

			_, found := s.Get(tt.boardID)
			urequire.False(t, found, "expect board not to be found by ID")

			for _, name := range tt.boardNames {
				_, found = s.GetByName(name)
				urequire.False(t, found, "expect board not to be found by name: "+name)
			}
		})
	}
}

func TestStorageAdd(t *testing.T) {
	tests := []struct {
		name   string
		setup  func() boards.Storage
		board  *boards.Board
		errMsg string
	}{
		{
			name:  "ok",
			board: &boards.Board{ID: 1, Name: "A"},
		},
		{
			name:   "nil board",
			board:  nil,
			errMsg: "adding nil boards to the storage is not allowed",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := boards.NewStorage()

			err := s.Add(tt.board)

			if tt.errMsg != "" {
				urequire.Error(t, err, "expect an error")
				urequire.ErrorContains(t, err, tt.errMsg, "expect error to match")
				return
			}

			urequire.NoError(t, err, "expect no error")

			_, found := s.Get(tt.board.ID)
			urequire.True(t, found, "expect board to be found by ID")

			_, found = s.GetByName(tt.board.Name)
			urequire.True(t, found, "expect board to be found by name")
		})
	}
}

func TestStorageSize(t *testing.T) {
	tests := []struct {
		name  string
		setup func() boards.Storage
		size  int
	}{
		{
			name: "empty",
			setup: func() boards.Storage {
				return boards.NewStorage()
			},
			size: 0,
		},
		{
			name: "one board",
			setup: func() boards.Storage {
				s := boards.NewStorage()
				s.Add(&boards.Board{ID: 1})
				return s
			},
			size: 1,
		},
		{
			name: "multiple boards",
			setup: func() boards.Storage {
				s := boards.NewStorage()
				s.Add(&boards.Board{ID: 1})
				s.Add(&boards.Board{ID: 2})
				return s
			},
			size: 2,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := tt.setup()

			urequire.Equal(t, tt.size, s.Size())
		})
	}
}

func TestStorageIterate(t *testing.T) {
	tests := []struct {
		name    string
		setup   func() boards.Storage
		reverse bool
		ids     []boards.ID
	}{
		{
			name: "default",
			setup: func() boards.Storage {
				s := boards.NewStorage()
				s.Add(&boards.Board{ID: 1})
				s.Add(&boards.Board{ID: 2})
				s.Add(&boards.Board{ID: 3})
				return s
			},
			ids: []boards.ID{1, 2, 3},
		},
		{
			name: "reverse",
			setup: func() boards.Storage {
				s := boards.NewStorage()
				s.Add(&boards.Board{ID: 1})
				s.Add(&boards.Board{ID: 2})
				s.Add(&boards.Board{ID: 3})
				return s
			},
			reverse: true,
			ids:     []boards.ID{3, 2, 1},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s := tt.setup()
			count := s.Size()
			if tt.reverse {
				count = -count
			}

			var i int
			s.Iterate(0, count, func(p *boards.Board) bool {
				urequire.True(t, tt.ids[i] == p.ID, "expect board ID to match")

				i++
				return false
			})
		})
	}
}

thread.gno

package boards

import (
	"errors"
	"strings"
	"time"

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

// NewThread creates a new board thread.
func NewThread(b *Board, creator address, title, body string) (*Post, error) {
	if b == nil {
		return nil, errors.New("thread requires a parent board")
	}

	if !creator.IsValid() {
		return nil, ufmt.Errorf("invalid thread creator address: %s", creator)
	}

	title = strings.TrimSpace(title)
	if title == "" {
		return nil, errors.New("thread title is required")
	}

	body = strings.TrimSpace(body)
	if body == "" {
		return nil, errors.New("thread body is required")
	}

	id := b.ThreadsSequence.Next()
	return &Post{
		ID:        id,
		ThreadID:  id,
		Board:     b,
		Title:     title,
		Body:      body,
		Replies:   NewPostStorage(),
		Reposts:   NewRepostStorage(),
		Flags:     NewFlagStorage(),
		Creator:   creator,
		CreatedAt: time.Now(),
	}, nil
}

// MustNewThread creates a new thread or panics on error.
func MustNewThread(b *Board, creator address, title, body string) *Post {
	t, err := NewThread(b, creator, title, body)
	if err != nil {
		panic(err)
	}
	return t
}

// NewRepost creates a new thread that is a repost of a thread from another board.
func NewRepost(thread *Post, dst *Board, creator address) (*Post, error) {
	if thread == nil {
		return nil, errors.New("thread to repost is required")
	}

	if thread.Board == nil {
		return nil, errors.New("original thread has no board assigned")
	}

	if dst == nil {
		return nil, errors.New("thread repost requires a destination board")
	}

	if IsRepost(thread) {
		return nil, errors.New("reposting a thread that is a repost is not allowed")
	}

	if !IsThread(thread) {
		return nil, errors.New("post must be a thread to be reposted to another board")
	}

	if !creator.IsValid() {
		return nil, ufmt.Errorf("invalid thread repost creator address: %s", creator)
	}

	id := dst.ThreadsSequence.Next()
	return &Post{
		ID:              id,
		ThreadID:        id,
		ParentID:        thread.ID,
		OriginalBoardID: thread.Board.ID,
		Board:           dst,
		Replies:         NewPostStorage(),
		Reposts:         NewRepostStorage(),
		Flags:           NewFlagStorage(),
		Creator:         creator,
		CreatedAt:       time.Now(),
	}, nil
}

// MustNewRepost creates a new thread that is a repost of a thread from another board or panics on error.
func MustNewRepost(thread *Post, dst *Board, creator address) *Post {
	r, err := NewRepost(thread, dst, creator)
	if err != nil {
		panic(err)
	}
	return r
}

thread_test.gno

package boards_test

import (
	"testing"

	"gno.land/p/nt/urequire/v0"

	"gno.land/p/gnoland/boards/v0"
)

func TestNewThread(t *testing.T) {
	tests := []struct {
		name        string
		board       *boards.Board
		creator     address
		title, body string
		errMsg      string
	}{
		{
			name:    "ok",
			board:   boards.New(1),
			creator: "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5",
			title:   "Test",
			body:    "Foo",
		},
		{
			name:   "nil board",
			board:  nil,
			errMsg: "thread requires a parent board",
		},
		{
			name:    "invalid creator",
			board:   boards.New(1),
			creator: "foo",
			errMsg:  "invalid thread creator address: foo",
		},
		{
			name:    "empty title",
			board:   boards.New(1),
			creator: "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5",
			title:   "",
			errMsg:  "thread title is required",
		},
		{
			name:    "empty body",
			board:   boards.New(1),
			creator: "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5",
			title:   "Test",
			body:    "",
			errMsg:  "thread body is required",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			thread, err := boards.NewThread(tt.board, tt.creator, tt.title, tt.body)

			if tt.errMsg != "" {
				urequire.Error(t, err, "expect an error")
				urequire.ErrorContains(t, err, tt.errMsg, "expect error to match")
				return
			}

			urequire.NoError(t, err, "expect no error")
			urequire.True(t, tt.board.ThreadsSequence.Last() == thread.ID, "expect ID to match")
			urequire.True(t, thread.ThreadID == thread.ID, "expect thread ID to match")
			urequire.False(t, thread.Board == nil, "expect board to be assigned")
			urequire.True(t, tt.board.ID == thread.Board.ID, "expect board ID to match")
			urequire.Equal(t, tt.title, thread.Title, "expect title to match")
			urequire.Equal(t, tt.body, thread.Body, "expect body to match")
			urequire.True(t, thread.Replies != nil, "expect thread to support sub-replies")
			urequire.True(t, thread.Reposts != nil, "expect thread to support reposts")
			urequire.True(t, thread.Flags != nil, "expect thread to support flagging")
			urequire.Equal(t, tt.creator, thread.Creator, "expect creator to match")
			urequire.False(t, thread.CreatedAt.IsZero(), "expect creation date to be assigned")
		})
	}
}

func TestNewRepost(t *testing.T) {
	tests := []struct {
		name       string
		origThread *boards.Post
		dstBoard   *boards.Board
		creator    address
		errMsg     string
	}{
		{
			name: "ok",
			origThread: boards.MustNewThread(
				boards.New(1),
				"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5",
				"Title",
				"Body",
			),
			dstBoard: boards.New(2),
			creator:  "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5",
		},
		{
			name:       "nil original thread",
			origThread: nil,
			errMsg:     "thread to repost is required",
		},
		{
			name:       "original thread without board",
			origThread: &boards.Post{ID: 1},
			errMsg:     "original thread has no board assigned",
		},
		{
			name: "nil destination board",
			origThread: boards.MustNewThread(
				boards.New(1),
				"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5",
				"Title",
				"Body",
			),
			dstBoard: nil,
			errMsg:   "thread repost requires a destination board",
		},
		{
			name: "original thread is not a thread",
			origThread: &boards.Post{
				ID:       1,
				ThreadID: 2,
				Board:    boards.New(1),
			},
			dstBoard: boards.New(2),
			errMsg:   "post must be a thread to be reposted to another board",
		},
		{
			name: "original thread is a repost",
			origThread: &boards.Post{
				ID:              1,
				ThreadID:        1,
				OriginalBoardID: 1,
				Board:           boards.New(1),
			},
			dstBoard: boards.New(2),
			errMsg:   "reposting a thread that is a repost is not allowed",
		},
		{
			name: "invalid creator",
			origThread: boards.MustNewThread(
				boards.New(1),
				"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5",
				"Title",
				"Body",
			),
			dstBoard: boards.New(2),
			creator:  "foo",
			errMsg:   "invalid thread repost creator address: foo",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			thread, err := boards.NewRepost(tt.origThread, tt.dstBoard, tt.creator)

			if tt.errMsg != "" {
				urequire.Error(t, err, "expect an error")
				urequire.ErrorContains(t, err, tt.errMsg, "expect error to match")
				return
			}

			urequire.NoError(t, err, "expect no error")
			urequire.True(t, thread.ID == tt.dstBoard.ThreadsSequence.Last(), "expect ID to match")
			urequire.True(t, thread.ThreadID == thread.ID, "expect thread ID to match")
			urequire.True(t, thread.ParentID == tt.origThread.ID, "expect parent ID to match")
			urequire.True(t, thread.OriginalBoardID == tt.origThread.Board.ID, "expect original board ID to match")
			urequire.False(t, thread.Board == nil, "expect board to be assigned")
			urequire.True(t, thread.Board.ID == tt.dstBoard.ID, "expect board ID to match")
			urequire.Empty(t, thread.Title, "expect title to be empty")
			urequire.Empty(t, thread.Body, "expect body to be empty")
			urequire.True(t, thread.Replies != nil, "expect thread to support sub-replies")
			urequire.True(t, thread.Reposts != nil, "expect thread to support reposts")
			urequire.True(t, thread.Flags != nil, "expect thread to support flagging")
			urequire.Equal(t, tt.creator, thread.Creator, "expect creator to match")
			urequire.False(t, thread.CreatedAt.IsZero(), "expect creation date to be assigned")
		})
	}
}