Skip to content

Commit

Permalink
Ensure a cursor can continue to iterate elements in reverse direction…
Browse files Browse the repository at this point in the history
… by call Next when it has already reached the beginning

Signed-off-by: Benjamin Wang <benjamin.ahrtr@gmail.com>
  • Loading branch information
ahrtr committed Apr 21, 2024
1 parent c9892a1 commit 7bbb813
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion cursor.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func (c *Cursor) Last() (key []byte, value []byte) {

// If this is an empty page (calling Delete may result in empty pages)
// we call prev to find the last page that is not empty
for len(c.stack) > 0 && c.stack[len(c.stack)-1].count() == 0 {
for len(c.stack) > 1 && c.stack[len(c.stack)-1].count() == 0 {
c.prev()
}

Expand Down Expand Up @@ -257,6 +257,15 @@ func (c *Cursor) prev() (key []byte, value []byte, flags uint32) {
elem.index--
break
}
// If we've hit the beginning, we should stop moving the cursor,
// and stay at the first element, so that users can continue to
// iterate over the elements in reverse direction by calling `Next`.
// We should return nil in such case.
// Refer to https://github.com/etcd-io/bbolt/issues/733
if len(c.stack) == 1 {
c.first()
return nil, nil, 0
}
c.stack = c.stack[:i]
}

Expand Down

0 comments on commit 7bbb813

Please sign in to comment.