Playground
gnomod.toml
module = "gno.land/p/nym-moultest123/ulist/lplist/v0" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186409 max_deposit = "7000000ugnot"
lplist.gno
// Package lplist provides a layered proxy implementation for lists that allows transparent
// migration of data between different schema versions.
//
// LayeredProxyList wraps an existing list (source) with a new list (target) and optionally
// applies migrations to source data when it's accessed. This enables schema evolution without
// requiring upfront migration of all data, making it ideal for large datasets or when
// preserving original data is important.
//
// Key features:
// - Lazy migration: Data is only transformed when accessed, not stored in migrated form
// - Append-only source: Source data is treated as immutable to preserve original data
// - Chaining: Multiple LayeredProxyLists can be stacked for multi-step migrations
//
// Example usage:
//
// // Define data types for different schema versions
// type UserV1 struct {
// Name string
// Age int
// }
//
// type UserV2 struct {
// FullName string
// Age int
// Active bool
// }
//
// // Create source list with old schema
// sourceList := ulist.New()
// sourceList.Append(
// UserV1{Name: "Alice", Age: 30},
// UserV1{Name: "Bob", Age: 25},
// )
//
// // Define migration function from V1 to V2
// migrateUserV1ToV2 := func(v any) any {
// user := v.(UserV1)
// return UserV2{
// FullName: user.Name, // Name field renamed to FullName
// Age: user.Age,
// Active: true, // New field with default value
// }
// }
//
// // Create layered proxy with migration
// proxy := NewLayeredProxyList(sourceList, migrateUserV1ToV2)
//
// // Add new data directly in V2 format
// proxy.Append(UserV2{FullName: "Charlie", Age: 40, Active: false})
//
// // All access through proxy returns data in V2 format
// for i := 0; i < proxy.Size(); i++ {
// user := proxy.Get(i).(UserV2)
// fmt.Printf("User: %s, Age: %d, Active: %t\n", user.FullName, user.Age, user.Active)
// }
package lplist
import (
"errors"
"gno.land/p/nym-moultest123/ulist/v0"
)
// MigratorFn is a function type that lazily converts values from source to target
type MigratorFn func(any) any
// LayeredProxyList represents a wrapper around an existing List that handles migration
type LayeredProxyList struct {
source ulist.IList
target *ulist.List
migrator MigratorFn
sourceHeight int // Store initial source size to optimize lookups
}
// NewLayeredProxyList creates a new LayeredProxyList instance that wraps an existing List
func NewLayeredProxyList(source ulist.IList, migrator MigratorFn) *LayeredProxyList {
sourceHeight := source.TotalSize()
target := ulist.New()
return &LayeredProxyList{
source: source,
target: target,
migrator: migrator,
sourceHeight: sourceHeight,
}
}
// Get retrieves the value at the specified index
// Uses sourceHeight to efficiently route requests
func (l *LayeredProxyList) Get(index int) any {
if index < l.sourceHeight {
// Direct access to source for indices below sourceHeight
val := l.source.Get(index)
if val == nil {
return nil
}
// Only apply migrator if it exists
if l.migrator != nil {
return l.migrator(val)
}
return val
}
// For indices >= sourceHeight, adjust index to be relative to target list starting at 0
targetIndex := index - l.sourceHeight
return l.target.Get(targetIndex)
}
// Append adds one or more values to the target list
func (l *LayeredProxyList) Append(values ...any) {
l.target.Append(values...)
}
// Delete marks elements as deleted in the appropriate list
func (l *LayeredProxyList) Delete(indices ...int) error {
for _, index := range indices {
if index < l.sourceHeight {
err := l.source.Delete(index)
if err != nil {
return err
}
}
}
for _, index := range indices {
targetIndex := index - l.sourceHeight
err := l.target.Delete(targetIndex)
if err != nil {
return err
}
}
return nil
}
// Size returns the total number of active elements
func (l *LayeredProxyList) Size() int {
return l.source.Size() + l.target.Size()
}
// TotalSize returns the total number of elements in the list
func (l *LayeredProxyList) TotalSize() int {
return l.sourceHeight + l.target.TotalSize()
}
// MustDelete deletes elements, panicking on error
func (l *LayeredProxyList) MustDelete(indices ...int) {
if err := l.Delete(indices...); err != nil {
panic(err)
}
}
// MustGet retrieves a value, panicking if not found
func (l *LayeredProxyList) MustGet(index int) any {
val := l.Get(index)
if val == nil {
panic(ulist.ErrDeleted)
}
return val
}
// GetRange returns elements between start and end indices
func (l *LayeredProxyList) GetRange(start, end int) []ulist.Entry {
var entries []ulist.Entry
l.Iterator(start, end, func(index int, value any) bool {
entries = append(entries, ulist.Entry{Index: index, Value: value})
return false
})
return entries
}
// GetRangeByOffset returns elements starting from offset
func (l *LayeredProxyList) GetRangeByOffset(offset int, count int) []ulist.Entry {
var entries []ulist.Entry
l.IteratorByOffset(offset, count, func(index int, value any) bool {
entries = append(entries, ulist.Entry{Index: index, Value: value})
return false
})
return entries
}
// Iterator performs iteration between start and end indices
func (l *LayeredProxyList) Iterator(start, end int, cb ulist.IterCbFn) bool {
// For empty list or invalid range
if start < 0 && end < 0 {
return false
}
// Normalize indices
if start < 0 {
start = 0
}
if end < 0 {
end = 0
}
totalSize := l.TotalSize()
if end >= totalSize {
end = totalSize - 1
}
if start >= totalSize {
start = totalSize - 1
}
// Handle reverse iteration
if start > end {
for i := start; i >= end; i-- {
val := l.Get(i)
if val != nil {
if cb(i, val) {
return true
}
}
}
return false
}
// Handle forward iteration
for i := start; i <= end; i++ {
val := l.Get(i)
if val != nil {
if cb(i, val) {
return true
}
}
}
return false
}
// IteratorByOffset performs iteration starting from offset
func (l *LayeredProxyList) IteratorByOffset(offset int, count int, cb ulist.IterCbFn) bool {
if count == 0 {
return false
}
// Normalize offset
if offset < 0 {
offset = 0
}
totalSize := l.TotalSize()
if offset >= totalSize {
offset = totalSize - 1
}
// Determine end based on count direction
var end int
if count > 0 {
end = totalSize - 1
} else {
end = 0
}
wrapperReturned := false
// Calculate absolute value manually instead of using abs function
remaining := count
if remaining < 0 {
remaining = -remaining
}
wrapper := func(index int, value any) bool {
if remaining <= 0 {
wrapperReturned = true
return true
}
remaining--
return cb(index, value)
}
ret := l.Iterator(offset, end, wrapper)
if wrapperReturned {
return false
}
return ret
}
// Set updates the value at the specified index
func (l *LayeredProxyList) Set(index int, value any) error {
if index < l.sourceHeight {
// Cannot modify source list directly
return errors.New("cannot modify source list directly")
}
// Adjust index to be relative to target list starting at 0
targetIndex := index - l.sourceHeight
return l.target.Set(targetIndex, value)
}
// MustSet updates the value at the specified index, panicking on error
func (l *LayeredProxyList) MustSet(index int, value any) {
if err := l.Set(index, value); err != nil {
panic(err)
}
}
// GetByOffset returns elements starting from offset with count determining direction
func (l *LayeredProxyList) GetByOffset(offset int, count int) []ulist.Entry {
var entries []ulist.Entry
l.IteratorByOffset(offset, count, func(index int, value any) bool {
entries = append(entries, ulist.Entry{Index: index, Value: value})
return false
})
return entries
}
// Verify that LayeredProxyList implements IList
var _ ulist.IList = (*LayeredProxyList)(nil)
lplist_test.gno
package lplist
import (
"testing"
"gno.land/p/nym-moultest123/ulist/v0"
)
// TestLayeredProxyListBasicOperations tests the basic operations of LayeredProxyList
func TestLayeredProxyListBasicOperations(t *testing.T) {
// Create source list with initial data
source := ulist.New()
source.Append(1, 2, 3)
// Create proxy list with a simple multiplier migrator
migrator := func(v any) any {
return v.(int) * 2
}
proxy := NewLayeredProxyList(source, migrator)
// Test initial state
if got := proxy.Size(); got != 3 {
t.Errorf("initial Size() = %v, want %v", got, 3)
}
if got := proxy.TotalSize(); got != 3 {
t.Errorf("initial TotalSize() = %v, want %v", got, 3)
}
// Test Get with migration
tests := []struct {
index int
want any
}{
{0, 2}, // 1 * 2
{1, 4}, // 2 * 2
{2, 6}, // 3 * 2
}
for _, tt := range tests {
if got := proxy.Get(tt.index); got != tt.want {
t.Errorf("Get(%v) = %v, want %v", tt.index, got, tt.want)
}
}
// Test Append to target
proxy.Append(7, 8)
if got := proxy.Size(); got != 5 {
t.Errorf("Size() after append = %v, want %v", got, 5)
}
// Test Get from target (no migration)
if got := proxy.Get(3); got != 7 {
t.Errorf("Get(3) = %v, want %v", got, 7)
}
}
// TestLayeredProxyListDelete tests delete operations
func TestLayeredProxyListDelete(t *testing.T) {
source := ulist.New()
source.Append(1, 2, 3)
proxy := NewLayeredProxyList(source, nil)
proxy.Append(4, 5)
// Test deleting from source (should fail)
if err := proxy.Delete(1); err == nil {
t.Error("Delete from source should return error")
}
// Test deleting from target (should succeed)
if err := proxy.Delete(3); err != nil {
t.Errorf("Delete from target failed: %s", err.Error())
}
// After deletion, the value might be undefined rather than nil
// Check that it's not equal to the original value
if got := proxy.Get(3); got == 5 {
t.Errorf("Get(3) after delete = %v, want it to be deleted", got)
}
}
// TestLayeredProxyListIteration tests iteration methods
func TestLayeredProxyListIteration(t *testing.T) {
source := ulist.New()
source.Append(1, 2, 3)
proxy := NewLayeredProxyList(source, nil)
proxy.Append(4, 5)
// Test GetRange
entries := proxy.GetRange(0, 4)
if len(entries) != 5 {
t.Errorf("GetRange returned %v entries, want 5", len(entries))
}
// Test reverse iteration
entries = proxy.GetRange(4, 0)
if len(entries) != 5 {
t.Errorf("Reverse GetRange returned %v entries, want 5", len(entries))
}
// Test IteratorByOffset with positive count
var values []any
proxy.IteratorByOffset(1, 3, func(index int, value any) bool {
values = append(values, value)
return false
})
if len(values) != 3 {
t.Errorf("IteratorByOffset returned %v values, want 3", len(values))
}
}
// TestLayeredProxyListMustOperations tests must operations
func TestLayeredProxyListMustOperations(t *testing.T) {
source := ulist.New()
source.Append(1, 2)
proxy := NewLayeredProxyList(source, nil)
// Test MustGet success
defer func() {
if r := recover(); r != nil {
t.Errorf("MustGet panicked unexpectedly: %v", r)
}
}()
if got := proxy.MustGet(1); got != 2 {
t.Errorf("MustGet(1) = %v, want 2", got)
}
// Test MustGet panic
defer func() {
if r := recover(); r == nil {
t.Error("MustGet should have panicked")
}
}()
proxy.MustGet(99) // Should panic
}
// TestLayeredProxyListWithNilMigrator tests behavior without a migrator
func TestLayeredProxyListWithNilMigrator(t *testing.T) {
source := ulist.New()
source.Append(1, 2)
proxy := NewLayeredProxyList(source, nil)
if got := proxy.Get(0); got != 1 {
t.Errorf("Get(0) with nil migrator = %v, want 1", got)
}
}
// TestLayeredProxyListEmpty tests operations on empty lists
func TestLayeredProxyListEmpty(t *testing.T) {
source := ulist.New()
proxy := NewLayeredProxyList(source, nil)
if got := proxy.Size(); got != 0 {
t.Errorf("Size() of empty list = %v, want 0", got)
}
if got := proxy.Get(0); got != nil {
t.Errorf("Get(0) of empty list = %v, want nil", got)
}
entries := proxy.GetRange(0, 10)
if len(entries) != 0 {
t.Errorf("GetRange on empty list returned %v entries, want 0", len(entries))
}
}
// TestLayeredProxyListChaining tests chaining of layered proxies with struct migrations
func TestLayeredProxyListChaining(t *testing.T) {
// Define struct types for different versions
type v1 struct {
namev1 string
}
type v2 struct {
namev2 string
}
type v3 struct {
namev3 string
}
// Create source list with v1 objects
source := ulist.New()
source.Append(v1{namev1: "object1"}, v1{namev1: "object2"})
// Migration function from v1 to v2
v1Tov2 := func(v any) any {
obj := v.(v1)
return v2{namev2: obj.namev1 + "_v2"}
}
// Create first proxy with v1->v2 migration
proxyV2 := NewLayeredProxyList(source, v1Tov2)
proxyV2.Append(v2{namev2: "direct_v2"})
// Migration function from v2 to v3
v2Tov3 := func(v any) any {
obj := v.(v2)
return v3{namev3: obj.namev2 + "_v3"}
}
// Create second proxy with v2->v3 migration, using the first proxy as source
proxyV3 := NewLayeredProxyList(proxyV2, v2Tov3)
proxyV3.Append(v3{namev3: "direct_v3"})
// Verify sizes
if got := proxyV3.Size(); got != 4 {
t.Errorf("proxyV3.Size() = %v, want 4", got)
}
// Test that all objects are correctly migrated when accessed through proxyV3
expected := []struct {
index int
name string
}{
{0, "object1_v2_v3"}, // v1 -> v2 -> v3
{1, "object2_v2_v3"}, // v1 -> v2 -> v3
{2, "direct_v2_v3"}, // v2 -> v3
{3, "direct_v3"}, // v3 (no migration)
}
for _, tt := range expected {
obj := proxyV3.Get(tt.index).(v3)
if obj.namev3 != tt.name {
t.Errorf("proxyV3.Get(%d).namev3 = %v, want %v", tt.index, obj.namev3, tt.name)
}
}
// Verify getting items from middle layer (proxyV2)
middleExpected := []struct {
index int
name string
}{
{0, "object1_v2"}, // v1 -> v2
{1, "object2_v2"}, // v1 -> v2
{2, "direct_v2"}, // v2 (no migration)
}
for _, tt := range middleExpected {
obj := proxyV2.Get(tt.index).(v2)
if obj.namev2 != tt.name {
t.Errorf("proxyV2.Get(%d).namev2 = %v, want %v", tt.index, obj.namev2, tt.name)
}
}
}