1 // Copyright 2016 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
15 "golang.org/x/sync/syncmap"
21 opLoad = mapOp("Load")
22 opStore = mapOp("Store")
23 opLoadOrStore = mapOp("LoadOrStore")
24 opDelete = mapOp("Delete")
27 var mapOps = [...]mapOp{opLoad, opStore, opLoadOrStore, opDelete}
29 // mapCall is a quick.Generator for calls on mapInterface.
35 func (c mapCall) apply(m mapInterface) (interface{}, bool) {
43 return m.LoadOrStore(c.k, c.v)
48 panic("invalid mapOp")
52 type mapResult struct {
57 func randValue(r *rand.Rand) interface{} {
58 b := make([]byte, r.Intn(4))
60 b[i] = 'a' + byte(rand.Intn(26))
65 func (mapCall) Generate(r *rand.Rand, size int) reflect.Value {
66 c := mapCall{op: mapOps[rand.Intn(len(mapOps))], k: randValue(r)}
68 case opStore, opLoadOrStore:
71 return reflect.ValueOf(c)
74 func applyCalls(m mapInterface, calls []mapCall) (results []mapResult, final map[interface{}]interface{}) {
75 for _, c := range calls {
77 results = append(results, mapResult{v, ok})
80 final = make(map[interface{}]interface{})
81 m.Range(func(k, v interface{}) bool {
89 func applyMap(calls []mapCall) ([]mapResult, map[interface{}]interface{}) {
90 return applyCalls(new(syncmap.Map), calls)
93 func applyRWMutexMap(calls []mapCall) ([]mapResult, map[interface{}]interface{}) {
94 return applyCalls(new(RWMutexMap), calls)
97 func applyDeepCopyMap(calls []mapCall) ([]mapResult, map[interface{}]interface{}) {
98 return applyCalls(new(DeepCopyMap), calls)
101 func TestMapMatchesRWMutex(t *testing.T) {
102 if err := quick.CheckEqual(applyMap, applyRWMutexMap, nil); err != nil {
107 func TestMapMatchesDeepCopy(t *testing.T) {
108 if err := quick.CheckEqual(applyMap, applyDeepCopyMap, nil); err != nil {
113 func TestConcurrentRange(t *testing.T) {
114 const mapSize = 1 << 10
116 m := new(syncmap.Map)
117 for n := int64(1); n <= mapSize; n++ {
121 done := make(chan struct{})
122 var wg sync.WaitGroup
127 for g := int64(runtime.GOMAXPROCS(0)); g > 0; g-- {
128 r := rand.New(rand.NewSource(g))
132 for i := int64(0); ; i++ {
138 for n := int64(1); n < mapSize; n++ {
139 if r.Int63n(mapSize) == 0 {
153 for n := iters; n > 0; n-- {
154 seen := make(map[int64]bool, mapSize)
156 m.Range(func(ki, vi interface{}) bool {
157 k, v := ki.(int64), vi.(int64)
159 t.Fatalf("while Storing multiples of %v, Range saw value %v", k, v)
162 t.Fatalf("Range visited key %v twice", k)
168 if len(seen) != mapSize {
169 t.Fatalf("Range visited %v elements of %v-element Map", len(seen), mapSize)