avlhelpers.gno

1.24 Kb ยท 41 lines
 1package avlhelpers
 2
 3import (
 4	"gno.land/p/demo/avl"
 5)
 6
 7// Iterate the keys in-order starting from the given prefix.
 8// It calls the provided callback function for each key-value pair encountered.
 9// If the callback returns true, the iteration is stopped.
10// The prefix and keys are treated as byte strings, ignoring possible multi-byte Unicode runes.
11func IterateByteStringKeysByPrefix(tree avl.ITree, prefix string, cb avl.IterCbFn) {
12	end := ""
13	n := len(prefix)
14	// To make the end of the search, increment the final character ASCII by one.
15	for n > 0 {
16		if ascii := int(prefix[n-1]); ascii < 0xff {
17			end = prefix[0:n-1] + string(ascii+1)
18			break
19		}
20
21		// The last character is 0xff. Try the previous character.
22		n--
23	}
24
25	tree.Iterate(prefix, end, cb)
26}
27
28// Get a list of keys starting from the given prefix. Limit the
29// number of results to maxResults.
30// The prefix and keys are treated as byte strings, ignoring possible multi-byte Unicode runes.
31func ListByteStringKeysByPrefix(tree avl.ITree, prefix string, maxResults int) []string {
32	result := []string{}
33	IterateByteStringKeysByPrefix(tree, prefix, func(key string, value any) bool {
34		result = append(result, key)
35		if len(result) >= maxResults {
36			return true
37		}
38		return false
39	})
40	return result
41}