Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: skipmap.LoadOrStore return input value #42

Merged
merged 2 commits into from
May 27, 2021
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
2 changes: 1 addition & 1 deletion collection/skipmap/skipmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ func (s *Int64Map) LoadOrStore(key int64, value interface{}) (actual interface{}
loadedval, ok := s.Load(key)
if !ok {
s.Store(key, value)
return nil, false
return value, false
}
return loadedval, true
}
Expand Down
2 changes: 1 addition & 1 deletion collection/skipmap/skipmap_str.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ func (s *StringMap) LoadOrStore(key string, value interface{}) (actual interface
loadedval, ok := s.Load(key)
if !ok {
s.Store(key, value)
return nil, false
return value, false
}
return loadedval, true
}
Expand Down
44 changes: 44 additions & 0 deletions collection/skipmap/skipmap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import (
"sync"
"sync/atomic"
"testing"

"github.com/bytedance/gopkg/lang/fastrand"
)

func TestSkipMap(t *testing.T) {
Expand Down Expand Up @@ -131,6 +133,48 @@ func TestSkipMap(t *testing.T) {
if m.Len() != 999 || int(count) != m.Len() {
t.Fatal("fail")
}
// Correctness 2.
var m1 sync.Map
m2 := NewUint32()
var v1, v2 interface{}
var ok1, ok2 bool
for i := 0; i < 100000; i++ {
rd := fastrand.Uint32n(10)
r1, r2 := fastrand.Uint32n(100), fastrand.Uint32n(100)
if rd == 0 {
m1.Store(r1, r2)
m2.Store(r1, r2)
} else if rd == 1 {
v1, ok1 = m1.LoadAndDelete(r1)
v2, ok2 = m2.LoadAndDelete(r1)
if ok1 != ok2 || v1 != v2 {
t.Fatal(rd, v1, ok1, v2, ok2)
}
} else if rd == 2 {
v1, ok1 = m1.LoadOrStore(r1, r2)
v2, ok2 = m2.LoadOrStore(r1, r2)
if ok1 != ok2 || v1 != v2 {
t.Fatal(rd, v1, ok1, v2, ok2, "input -> ", r1, r2)
}
} else if rd == 3 {
m1.Delete(r1)
m2.Delete(r1)
} else if rd == 4 {
m2.Range(func(key uint32, value interface{}) bool {
v, ok := m1.Load(key)
if !ok || v != value {
t.Fatal(v, ok, key, value)
}
return true
})
} else {
v1, ok1 = m1.Load(r1)
v2, ok2 = m2.Load(r1)
if ok1 != ok2 || v1 != v2 {
t.Fatal(rd, v1, ok1, v2, ok2)
}
}
}
}

func TestSkipMapDesc(t *testing.T) {
Expand Down
38 changes: 19 additions & 19 deletions collection/skipmap/types.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.