From 9ce1f9ea18b423ff7c096b9b6450546e770e93a0 Mon Sep 17 00:00:00 2001 From: zenbal Date: Tue, 7 May 2024 04:44:52 +0200 Subject: [PATCH] fix: adjust arraylist slice capacity after unmarshalling --- lists/arraylist/arraylist_test.go | 25 +++++++++++++++++++++++++ lists/arraylist/serialization.go | 1 + 2 files changed, 26 insertions(+) diff --git a/lists/arraylist/arraylist_test.go b/lists/arraylist/arraylist_test.go index 614b436d..f3b9e27f 100644 --- a/lists/arraylist/arraylist_test.go +++ b/lists/arraylist/arraylist_test.go @@ -642,6 +642,31 @@ func TestListSerialization(t *testing.T) { assert() } +func TestListSerializationCapacity(t *testing.T) { + nums := make([]int, 100) + for i := 0; i < 100; i++ { + nums[i] = i + } + list := New(nums...) + + var err error + assert := func() { + if actualCapacity, expectedCapacity := cap(list.elements), 100; actualCapacity != expectedCapacity { + t.Errorf("Got cap=%d expected cap=%d", actualCapacity, expectedCapacity) + } + if actualLength, expectedLength := len(list.elements), 100; actualLength != expectedLength { + t.Errorf("Got len=%d expected len=%d", actualLength, expectedLength) + } + } + + bytes, err := list.ToJSON() + err = list.FromJSON(bytes) + if err != nil { + t.Errorf("Got error %v", err) + } + assert() +} + func TestListString(t *testing.T) { c := New[int]() c.Add(1) diff --git a/lists/arraylist/serialization.go b/lists/arraylist/serialization.go index a3aec534..77b95e1e 100644 --- a/lists/arraylist/serialization.go +++ b/lists/arraylist/serialization.go @@ -24,6 +24,7 @@ func (list *List[T]) FromJSON(data []byte) error { err := json.Unmarshal(data, &list.elements) if err == nil { list.size = len(list.elements) + list.elements = list.elements[:len(list.elements):len(list.elements)] } return err }