Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions btree.go
Original file line number Diff line number Diff line change
Expand Up @@ -353,3 +353,11 @@ func (iter *Iter) Prev() bool {
func (iter *Iter) Item() any {
return iter.base.Item()
}

// Pos returns the position of the current iterator item. Returns -1
// if the tree is empty or the iterator is at the beginning of the tree.
// Overall, the complexity will be O(log N⋅M) where stack height will
// follow the height of the btree, which is log N, and M as the degree.
func (iter *Iter) Pos() int {
return iter.base.Pos()
}
32 changes: 31 additions & 1 deletion btreeg.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
// license that can be found in the LICENSE file.
package btree

import "sync"
import (
"sync"
)

type BTreeG[T any] struct {
isoid uint64
Expand Down Expand Up @@ -1323,6 +1325,34 @@ func (iter *IterG[T]) Item() T {
return iter.item
}

// Pos returns the position of the current iterator item. Returns -1
// if the tree is empty or the iterator is at the beginning of the tree.
// Overall, the complexity will be O(log N⋅M) where stack height will
// follow the height of the btree, which is log N, and M as the degree.
func (iter *IterG[T]) Pos() int {
if iter.tr == nil {
return -1
}
if !iter.seeked {
return -1
}
count := 0
for i, s := range iter.stack {
count += s.i
if !s.n.leaf() {
c := *s.n.children
t := s.i
if i == len(iter.stack)-1 {
t++
}
for j := 0; j < t; j++ {
count += c[j].count
}
}
}
return count
}

// Items returns all the items in order.
func (tr *BTreeG[T]) Items() []T {
return tr.items(false)
Expand Down
23 changes: 23 additions & 0 deletions btreeg_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1343,3 +1343,26 @@ func TestGenericIterSeekPrefix(t *testing.T) {
iter.Release()
}
}

func TestGenericPos(t *testing.T) {
tr := NewBTreeG(func(a, b int) bool {
return a < b
})
count := 10_000
for i := 0; i < count; i++ {
tr.Set(i * 2)
}
iter := tr.Iter()
lastPos := iter.Pos()
assert(lastPos == -1)
iter.Release()
for i := 0; i < count; i++ {
iter = tr.Iter()
ret := iter.Seek(i*2 - 1)
assert(ret == true)
pos := iter.Pos()
assert(pos-lastPos == 1)
lastPos = pos
iter.Release()
}
}