Search Apps Documentation Source Content File Folder Download Copy Actions Download

iterator.gno

1.44 Kb · 77 lines
 1package commondao
 2
 3import (
 4	"chain/runtime"
 5
 6	"gno.land/p/nt/avl/v0/rotree"
 7	"gno.land/p/nt/commondao/v0"
 8)
 9
10// NewIterator returns a SubDAO iterator.
11func NewIterator(rootID uint64, options ...IteratorOption) Iterator {
12	assertIsOwner(runtime.CurrentRealm().Address(), rootID)
13
14	tree := getTree(rootID)
15	if tree == nil {
16		return Iterator{}
17	}
18
19	it := Iterator{tree: tree}
20	for _, apply := range options {
21		apply(&it)
22	}
23
24	size := it.tree.Size()
25	if it.count > 0 {
26		it.maxIndex = it.current + it.count
27		if it.maxIndex > size {
28			it.maxIndex = size
29		}
30	} else {
31		it.maxIndex = size
32	}
33
34	it.count = it.maxIndex - it.current
35
36	return it
37}
38
39// Iterator defines an iterator of SubDAOs.
40type Iterator struct {
41	tree                     rotree.IReadOnlyTree
42	count, current, maxIndex int
43	path                     string
44	dao                      *commondao.CommonDAO
45}
46
47// Count returns the number of DAOs to iterate.
48func (it Iterator) Count() int {
49	return it.count
50}
51
52// Next returns true when a new DAO is available.
53func (it *Iterator) Next() bool {
54	if it.tree == nil || it.current == it.maxIndex {
55		return false
56	}
57
58	path, v := it.tree.GetByIndex(it.current)
59	if v == nil {
60		return false
61	}
62
63	it.dao = v.(*commondao.CommonDAO)
64	it.path = path
65	it.current++
66	return true
67}
68
69// DAO returns the current DAO.
70func (it Iterator) DAO() *commondao.CommonDAO {
71	return it.dao
72}
73
74// Path returns the current DAO path.
75func (it Iterator) Path() string {
76	return it.path
77}