Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement method to get first index in amt #11

Merged
merged 2 commits into from
Apr 24, 2020
Merged
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
43 changes: 43 additions & 0 deletions amt.go
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,49 @@ func (n *Node) forEachAt(ctx context.Context, bs cbor.IpldStore, height int, sta

}

func (r *Root) FirstSetIndex(ctx context.Context) (uint64, error) {
return r.Node.firstSetIndex(ctx, r.store, int(r.Height))
}

var errNoVals = fmt.Errorf("no values")

func (n *Node) firstSetIndex(ctx context.Context, bs cbor.IpldStore, height int) (uint64, error) {
if height == 0 {
n.expandValues()
for i, v := range n.expVals {
if v != nil {
return uint64(i), nil
}
}
// Would be really weird if we ever actually hit this
return 0, errNoVals
}

if n.cache == nil {
n.expandLinks()
}

for i := 0; i < width; i++ {
ok, _ := n.getBit(uint64(i))
if ok {
subn, err := n.loadNode(ctx, bs, uint64(i), false)
if err != nil {
return 0, err
}

ix, err := subn.firstSetIndex(ctx, bs, height-1)
if err != nil {
return 0, err
}

subCount := nodesForHeight(width, height)
return ix + (uint64(i) * subCount), nil
}
}

return 0, errNoVals
}

func (n *Node) expandValues() {
if len(n.expVals) == 0 {
n.expVals = make([]*cbg.Deferred, width)
Expand Down
42 changes: 42 additions & 0 deletions amt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -651,3 +651,45 @@ func TestForEachAt(t *testing.T) {
}
}
}

func TestFirstSetIndex(t *testing.T) {
bs := cbor.NewCborStore(newMockBlocks())
ctx := context.Background()

vals := []uint64{0, 1, 5, width, width + 1, 276, 1234, 62881923}
for _, v := range vals {
a := NewAMT(bs)
if err := a.Set(ctx, v, fmt.Sprint(v)); err != nil {
t.Fatal(err)
}

fsi, err := a.FirstSetIndex(ctx)
if err != nil {
t.Fatal(err)
}

if fsi != v {
t.Fatal("got wrong index out", fsi, v)
}

rc, err := a.Flush(ctx)
if err != nil {
t.Fatal(err)
}

after, err := LoadAMT(ctx, bs, rc)
if err != nil {
t.Fatal(err)
}

fsi, err = after.FirstSetIndex(ctx)
if err != nil {
t.Fatal(err)
}

if fsi != v {
t.Fatal("got wrong index out after serialization")
}
}

}