From 2c207ef0bf3ce478543392cbeac6f3c693c0a9c7 Mon Sep 17 00:00:00 2001 From: xgzlucario <912156837@qq.com> Date: Thu, 11 Jul 2024 02:12:49 +0800 Subject: [PATCH] refactor: refact listpack --- internal/list/bench_test.go | 31 +++++++++++++++++++++++-------- internal/list/listpack.go | 14 ++++++++++++-- internal/list/listpack_test.go | 6 ++++-- 3 files changed, 39 insertions(+), 12 deletions(-) diff --git a/internal/list/bench_test.go b/internal/list/bench_test.go index 5741f05..46ae154 100644 --- a/internal/list/bench_test.go +++ b/internal/list/bench_test.go @@ -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)) } }) } diff --git a/internal/list/listpack.go b/internal/list/listpack.go index 1cb480f..7af0663 100644 --- a/internal/list/listpack.go +++ b/internal/list/listpack.go @@ -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] diff --git a/internal/list/listpack_test.go b/internal/list/listpack_test.go index 0d7b0fd..83ea28d 100644 --- a/internal/list/listpack_test.go +++ b/internal/list/listpack_test.go @@ -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") }