From f7acd40303b9a08b9665ec1fb60179fb982f219b Mon Sep 17 00:00:00 2001 From: Rupayon Haldar <80724680+rupayon123@users.noreply.github.com> Date: Fri, 30 Oct 2026 21:53:45 -0400 Subject: [PATCH] fix(list): preserve receiver contents in SubList (#410) --- datastructure/list/copyonwritelist.go | 1 - datastructure/list/sublist_preserve_test.go | 40 +++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 datastructure/list/sublist_preserve_test.go diff --git a/datastructure/list/copyonwritelist.go b/datastructure/list/copyonwritelist.go index 2878bbc..0aac7af 100644 --- a/datastructure/list/copyonwritelist.go +++ b/datastructure/list/copyonwritelist.go @@ -374,6 +374,5 @@ func (c *CopyOnWriteList[T]) SubList(start int, end int) (newList []T) { } newList = make([]T, end-start) copy(newList, list[start:end]) - c.setList(newList) return } diff --git a/datastructure/list/sublist_preserve_test.go b/datastructure/list/sublist_preserve_test.go new file mode 100644 index 0000000..5fee9b2 --- /dev/null +++ b/datastructure/list/sublist_preserve_test.go @@ -0,0 +1,40 @@ +package datastructure_test + +import ( + list "github.com/duke-git/lancet/v2/datastructure/list" + "reflect" + "testing" +) + +func TestCopyOnWriteSubListPreservesReceiver(t *testing.T) { + for _, tc := range []struct { + name string + start, end int + want []int + }{ + {"middle", 1, 3, []int{2, 3}}, {"empty range", 2, 2, []int{}}, {"prefix", 0, 2, []int{1, 2}}, {"suffix", 2, 4, []int{3, 4}}, {"full control", 0, 4, []int{1, 2, 3, 4}}, {"invalid control", 3, 1, []int{}}, + } { + t.Run(tc.name, func(t *testing.T) { + c := list.NewCopyOnWriteList([]int{1, 2, 3, 4}) + got := c.SubList(tc.start, tc.end) + if !reflect.DeepEqual(got, tc.want) { + t.Fatalf("sublist=%v want%v", got, tc.want) + } + values := []int{} + c.ForEach(func(v int) { values = append(values, v) }) + if c.Size() != 4 || !reflect.DeepEqual(values, []int{1, 2, 3, 4}) { + t.Fatalf("SubList discarded source values: %v", values) + } + if len(got) > 0 { + got[0] = 99 + } + if *c.Get(0) != 1 || *c.Get(1) != 2 { + t.Fatal("returned slice aliases receiver") + } + c.Add(5) + if c.Size() != 5 || *c.Get(4) != 5 { + t.Fatal("later append changed") + } + }) + } +}