aboutsummaryrefslogtreecommitdiff
path: root/map_test.go
diff options
context:
space:
mode:
authorRunxi Yu <me@runxiyu.org>2024-12-29 17:54:59 +0000
committerRunxi Yu <me@runxiyu.org>2024-12-29 17:54:59 +0000
commit132bc3c2f59ee09c9a59c4ed72a4ade195d07259 (patch)
tree9dbc93ffd2d15de99b76d523b17701831baf54ad /map_test.go
downloadgo-lindenii-common-132bc3c2f59ee09c9a59c4ed72a4ade195d07259.tar.gz
go-lindenii-common-132bc3c2f59ee09c9a59c4ed72a4ade195d07259.tar.zst
go-lindenii-common-132bc3c2f59ee09c9a59c4ed72a4ade195d07259.zip
Initial commit
Diffstat (limited to 'map_test.go')
-rw-r--r--map_test.go76
1 files changed, 76 insertions, 0 deletions
diff --git a/map_test.go b/map_test.go
new file mode 100644
index 0000000..b131207
--- /dev/null
+++ b/map_test.go
@@ -0,0 +1,76 @@
+// This is directly ported from github.com/SaveTheRbtz/generic-sync-map-go
+// and does not test the new CompareAndSwap and related functions yet.
+// Copyright 2016 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package lindenii_common_test
+
+import (
+ "math/rand"
+ "runtime"
+ "sync"
+ "testing"
+
+ lindenii_common "go.lindenii.runxiyu.org/lindenii-common"
+)
+
+func TestConcurrentRange(t *testing.T) {
+ const mapSize = 1 << 10
+
+ m := new(lindenii_common.Map[int64, int64])
+ for n := int64(1); n <= mapSize; n++ {
+ m.Store(n, int64(n))
+ }
+
+ done := make(chan struct{})
+ var wg sync.WaitGroup
+ defer func() {
+ close(done)
+ wg.Wait()
+ }()
+ for g := int64(runtime.GOMAXPROCS(0)); g > 0; g-- {
+ r := rand.New(rand.NewSource(g))
+ wg.Add(1)
+ go func(g int64) {
+ defer wg.Done()
+ for i := int64(0); ; i++ {
+ select {
+ case <-done:
+ return
+ default:
+ }
+ for n := int64(1); n < mapSize; n++ {
+ if r.Int63n(mapSize) == 0 {
+ m.Store(n, n*i*g)
+ } else {
+ m.Load(n)
+ }
+ }
+ }
+ }(g)
+ }
+
+ iters := 1 << 10
+ if testing.Short() {
+ iters = 16
+ }
+ for n := iters; n > 0; n-- {
+ seen := make(map[int64]bool, mapSize)
+
+ m.Range(func(k, v int64) bool {
+ if v%k != 0 {
+ t.Fatalf("while Storing multiples of %v, Range saw value %v", k, v)
+ }
+ if seen[k] {
+ t.Fatalf("Range visited key %v twice", k)
+ }
+ seen[k] = true
+ return true
+ })
+
+ if len(seen) != mapSize {
+ t.Fatalf("Range visited %v elements of %v-element Map", len(seen), mapSize)
+ }
+ }
+}