From 9c401c40439e506dbdb2e510772cf6fb8a4e91db Mon Sep 17 00:00:00 2001 From: Rupayon Haldar <80724680+rupayon123@users.noreply.github.com> Date: Fri, 30 Oct 2026 21:54:39 -0400 Subject: [PATCH] fix(list): release the sort lock on every exit (#409) --- datastructure/list/copyonwritelist.go | 1 + datastructure/list/sort_unlock_test.go | 69 ++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 datastructure/list/sort_unlock_test.go diff --git a/datastructure/list/copyonwritelist.go b/datastructure/list/copyonwritelist.go index 0aac7af..5b0680c 100644 --- a/datastructure/list/copyonwritelist.go +++ b/datastructure/list/copyonwritelist.go @@ -354,6 +354,7 @@ func (c *CopyOnWriteList[T]) ForEach(f func(T)) { func (c *CopyOnWriteList[T]) Sort(compare func(o1 T, o2 T) bool) { lock := c.lock lock.Lock() + defer lock.Unlock() list := c.getList() sort.Slice(list, func(i, j int) bool { diff --git a/datastructure/list/sort_unlock_test.go b/datastructure/list/sort_unlock_test.go new file mode 100644 index 0000000..50081e2 --- /dev/null +++ b/datastructure/list/sort_unlock_test.go @@ -0,0 +1,69 @@ +package datastructure_test + +import ( + "reflect" + "testing" + "time" + + list "github.com/duke-git/lancet/v2/datastructure/list" +) + +func TestCopyOnWriteSortReleasesLock(t *testing.T) { + for _, tc := range []struct { + name string + values []int + panicCompare bool + sort bool + }{ + {"sorted values", []int{3, 1, 2}, false, true}, + {"empty values", []int{}, false, true}, + {"comparator panic", []int{3, 1, 2}, true, true}, + {"without sort control", []int{1, 2, 3}, false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + c := list.NewCopyOnWriteList(tc.values) + marker := new(int) + if tc.sort { + func() { + defer func() { + r := recover() + if tc.panicCompare { + if r != marker { + t.Errorf("panic identity changed: %v", r) + } + } else if r != nil { + t.Errorf("unexpected panic: %v", r) + } + }() + c.Sort(func(a, b int) bool { + if tc.panicCompare { + panic(marker) + } + return a < b + }) + }() + } + if tc.sort && !tc.panicCompare { + got := []int{} + c.ForEach(func(v int) { got = append(got, v) }) + want := []int{1, 2, 3} + if len(tc.values) == 0 { + want = []int{} + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("sort got=%v want=%v", got, want) + } + } + done := make(chan struct{}) + go func() { c.Add(4); close(done) }() + select { + case <-done: + if c.Size() != len(tc.values)+1 { + t.Fatal("next mutation did not persist") + } + case <-time.After(time.Second): + t.Fatal("Sort left the mutation lock held") + } + }) + } +}