loci.gno
1.30 Kb ยท 44 lines
1// loci is a single purpose datastore keyed by the caller's address. It has two
2// functions: Set and Get. loci is plural for locus, which is a central or core
3// place where something is found or from which it originates. In this case,
4// it's a simple key-value store where an address (the key) can store exactly
5// one value (in the form of a byte slice). Only the caller can set the value
6// for their address, but anyone can retrieve the value for any address.
7package loci
8
9import (
10 "std"
11
12 "gno.land/p/demo/avl"
13)
14
15// LociStore is a simple key-value store that uses
16// an AVL tree to store the data.
17type LociStore struct {
18 internal *avl.Tree
19}
20
21// New creates a reference to a new LociStore.
22func New() *LociStore {
23 return &LociStore{
24 internal: avl.NewTree(),
25 }
26}
27
28// Set stores a byte slice in the AVL tree using the `std.PreviousRealm().Address()`
29// string as the key.
30func (s *LociStore) Set(value []byte) {
31 key := string(std.PreviousRealm().Address())
32 s.internal.Set(key, value)
33}
34
35// Get retrieves a byte slice from the AVL tree using the provided address.
36// The return values are the byte slice value and a boolean indicating
37// whether the value exists.
38func (s *LociStore) Get(addr std.Address) []byte {
39 value, exists := s.internal.Get(string(addr))
40 if !exists {
41 return nil
42 }
43 return value.([]byte)
44}