Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -355,8 +355,9 @@ func (m *Map[K, V]) Swap(key K, value V) (previous V, loaded bool) {
}

// CompareAndSwap swaps the old and new values for key if the value stored in
// the map is equal to old according to eq. The eq function is called while the
// node of the key is locked.
// the map is equal to old according to eq. The eq function may be called more
// than once: to find the entry, and again while the node of the key is locked,
// so it must not use m. If eq panics, the node is unlocked.
//
// If there is no current value for key in the map, CompareAndSwap returns false.
func (m *Map[K, V]) CompareAndSwap(key K, old, new V, eq func(current, old V) bool) (swapped bool) {
Expand Down Expand Up @@ -441,7 +442,8 @@ func (m *Map[K, V]) Delete(key K) {
}

// CompareAndDelete deletes the entry for key if its value is equal to old
// according to eq. The eq function is called while the node of the key is locked.
// according to eq. The eq function is called while the node of the key is
// locked, so it must not use m. If eq panics, the node is unlocked.
//
// If there is no current value for key in the map, CompareAndDelete returns false.
func (m *Map[K, V]) CompareAndDelete(key K, old V, eq func(current, old V) bool) (deleted bool) {
Expand All @@ -455,31 +457,38 @@ func (m *Map[K, V]) CompareAndDelete(key K, old V, eq func(current, old V) bool)

// Find a node with the key. n != nil if we found the node.
i, hashShift, slot, n := m.find(key, hash, nil, old)
if n == nil {
if i != nil {
if i == nil {
return false
}
// i.mu is unlocked by the deferred call unless pruneEmpty takes it over,
// so that a panic in eq does not leave the node locked.
locked := true
defer func() {
if locked {
i.mu.Unlock()
}
}()
if n == nil {
return false
}

// Try to delete the entry.
e, deleted := n.entry().compareAndDelete(key, old, eq)
if !deleted {
// Nothing was actually deleted, which means the node is no longer there.
i.mu.Unlock()
return false
}
if e != nil {
// We didn't actually delete the whole entry, just one entry in the chain.
// Nothing else to do, since the parent is definitely not empty.
slot.Store(&e.node)
i.mu.Unlock()
return true
}
// Delete the entry.
slot.Store(nil)

// Check if the node is now empty (and isn't the root), and delete it if able.
locked = false
m.pruneEmpty(i, hash, hashShift)
return true
}
Expand Down
2 changes: 2 additions & 0 deletions map_extra_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,8 @@ func TestNoAlloc(t *testing.T) { //nolint:paralleltest // AllocsPerRun
"LoadOrStoreExists": func() { m.LoadOrStore("gamma", 0) },
"DeleteMissing": func() { m.Delete("omega") },
"CompareAndSwapNo": func() { m.CompareAndSwap("gamma", -1, 0) },
"CompareAndDelNo": func() { m.CompareAndDelete("gamma", -1) },
"CompareAndDelMiss": func() { m.CompareAndDelete("omega", 0) },
"Range": func() { m.Range(func(string, int) bool { return true }) },
"Len": func() { m.Len() },
"Empty": func() { m.Empty() },
Expand Down
116 changes: 116 additions & 0 deletions map_panic_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package gosync_test

import (
"testing"
"time"

"github.com/darxnet/gosync"
)

// mustPanic calls f and fails the test if it does not panic.
func mustPanic(t *testing.T, name string, f func()) {
t.Helper()

defer func() {
if recover() == nil {
t.Errorf("%s did not panic", name)
}
}()

f()
}

// completes fails the test if f does not return in time: a node left locked
// by a panic makes the next write to its subtree block forever.
func completes(t *testing.T, name string, f func()) {
t.Helper()

done := make(chan struct{})

go func() {
defer close(done)

f()
}()

select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatalf("%s blocked: a node is still locked after a panic in user code", name)
}
}

// TestUserCodePanicUnlocks checks that a panic in a user function called with
// a node locked (eq, compute, or == on values of a dynamic type that is not
// comparable) unlocks the node, so later writes to the same key do not hang.
func TestUserCodePanicUnlocks(t *testing.T) {
t.Parallel()

panicky := func(_, _ int) bool { panic("eq") }

t.Run("CompareAndDelete", func(t *testing.T) {
t.Parallel()

var m gosync.Map[string, int]
m.Store("k", 1)

mustPanic(t, "CompareAndDelete", func() { m.CompareAndDelete("k", 1, panicky) })
completes(t, "Store after CompareAndDelete", func() { m.Store("k", 2) })

if !m.CompareAndDelete("k", 2, func(a, b int) bool { return a == b }) {
t.Fatal("CompareAndDelete after the panic did not delete")
}
})

t.Run("CompareAndDeleteNotComparable", func(t *testing.T) {
t.Parallel()

var m gosync.ComparableMap[string, any]
m.Store("k", []byte("v"))

mustPanic(t, "CompareAndDelete", func() { m.CompareAndDelete("k", []byte("v")) })
completes(t, "Store after CompareAndDelete", func() { m.Store("k", 2) })
})

t.Run("CompareAndDeleteOverflow", func(t *testing.T) {
t.Parallel()

// every key hashes to 0, so "b" sits in the overflow chain of "a"
m := gosync.NewBadMap[string, any]()
m.Store("b", []byte("v"))
m.Store("a", 1)

mustPanic(t, "CompareAndDelete", func() { m.CompareAndDelete("b", []byte("v")) })
completes(t, "Store after CompareAndDelete", func() { m.Store("c", 3) })
})

t.Run("CompareAndSwap", func(t *testing.T) {
t.Parallel()

var m gosync.Map[string, int]
m.Store("k", 1)

// the first call is the unlocked lookup, the second runs locked
calls := 0
eq := func(a, b int) bool {
calls++
if calls > 1 {
panic("eq")
}

return a == b
}

mustPanic(t, "CompareAndSwap", func() { m.CompareAndSwap("k", 1, 2, eq) })
completes(t, "Store after CompareAndSwap", func() { m.Store("k", 2) })
})

t.Run("LoadOrCompute", func(t *testing.T) {
t.Parallel()

var m gosync.Map[string, int]

mustPanic(t, "LoadOrCompute", func() { m.LoadOrCompute("k", func() int { panic("compute") }) })
completes(t, "Store after LoadOrCompute", func() { m.Store("k", 2) })
})
}
Loading