Skip to content

Commit

Permalink
Merge pull request #6 from villegasl/master
Browse files Browse the repository at this point in the history
Use Cursor().Seek() in LastN method of the List datatype instead of manually getting to the desired position
  • Loading branch information
xyproto committed Jan 1, 2020
2 parents 285993a + 53060ef commit dbcca43
Showing 1 changed file with 15 additions and 17 deletions.
32 changes: 15 additions & 17 deletions simplebolt.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,26 +174,24 @@ func (l *List) LastN(n int) (results []string, err error) {
if bucket == nil {
return ErrBucketNotFound
}
var size int64
bucket.ForEach(func(_, _ []byte) error {
size++
return nil // Continue ForEach
})
if size < int64(n) {
c := bucket.Cursor()
sizeBytes, _ := c.Last()
size := binary.BigEndian.Uint64(sizeBytes)
if size < uint64(n) {
return errors.New("Too few items in list")
}
// Ok, fetch the n last items. startPos is counting from 0.
var (
startPos = size - int64(n)
i int64
)
bucket.ForEach(func(_, value []byte) error {
if i >= startPos {
// Ok, fetch the n last items. startPos is counting from (size - n)+1.
// +1 because Seek() moves to a specific key.
// e.g. if the size of the list is, say, 50, and we want the last 4
// elements, say, from 47 to 50 inclusive, then the calculation would be like this:
// size = 50
// n = 4
// startPos = size - n // startPos = 46
// startPos += 1 // startPos = 47
startPos := byteID(size - uint64(n) + 1)
for key, value := c.Seek(startPos); key != nil; key, value = c.Next() {
results = append(results, string(value))
}
i++
return nil // Continue ForEach
})
}
return nil // Return from View function
})
}
Expand Down

0 comments on commit dbcca43

Please sign in to comment.