Skip to content

Commit

Permalink
refactor: refact listpack
Browse files Browse the repository at this point in the history
  • Loading branch information
xgzlucario committed Jul 10, 2024
1 parent b76f75a commit 2c207ef
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 12 deletions.
31 changes: 23 additions & 8 deletions internal/list/bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,38 @@ func BenchmarkListPack(b *testing.B) {
const N = 1000
b.Run("next", func(b *testing.B) {
ls := genListPack(0, N)
it := ls.NewIterator()
b.ResetTimer()
for i := 0; i < b.N; i++ {
it := ls.NewIterator()
for i := 0; i < N; i++ {
it.Next()
}
it.SeekBegin()
it.Next()
}
})
b.Run("prev", func(b *testing.B) {
ls := genListPack(0, N)
it := ls.NewIterator()
b.ResetTimer()
for i := 0; i < b.N; i++ {
it := ls.NewIterator()
it.SeekEnd()
for i := 0; i < N; i++ {
it.Prev()
}
it.Prev()
}
})
b.Run("lpush", func(b *testing.B) {
ls := NewListPack()
it := ls.NewIterator()
b.ResetTimer()
for i := 0; i < b.N; i++ {
it.SeekBegin()
it.Insert(genKey(i))
}
})
b.Run("rpush", func(b *testing.B) {
ls := NewListPack()
it := ls.NewIterator()
b.ResetTimer()
for i := 0; i < b.N; i++ {
it.SeekEnd()
it.Insert(genKey(i))
}
})
}
14 changes: 12 additions & 2 deletions internal/list/listpack.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,16 +106,26 @@ func (it *lpIterator) Insert(data string) {
bpool.Put(alloc)
}

func (it *lpIterator) Remove() []byte {
func (it *lpIterator) RemoveNext() []byte {
before := it.index
data := slices.Clone(it.Next())
after := it.index
it.data = slices.Delete(it.data, before, after)
it.index -= (after - before)
it.size--
return data
}

func (it *lpIterator) RemovePrev() []byte {
after := it.index
data := slices.Clone(it.Prev())
before := it.index
it.data = slices.Delete(it.data, before, after)
it.index -= (after - before)
it.size--
return data
}

// encode data to [data_len, data, entry_len].
func appendEntry(dst []byte, data string) []byte {
if dst == nil {
dst = bpool.Get(maxListPackSize)[:0]
Expand Down
6 changes: 4 additions & 2 deletions internal/list/listpack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -266,13 +266,15 @@ func TestIterator(t *testing.T) {
data = it.Next()
assert.Equal(string(data), "004")

removed := it.Remove()
removed := it.RemoveNext()
assert.Equal(string(removed), "002")

removed = it.RemovePrev()
assert.Equal(string(removed), "004")

it.SeekEnd()

assert.Equal(string(it.Prev()), "003")
assert.Equal(string(it.Prev()), "004")
assert.Equal(string(it.Prev()), "001")
}

Expand Down

0 comments on commit 2c207ef

Please sign in to comment.