* README.Portability: Remove note on an Irix compatibility issue.
[official-gcc.git] / libgo / go / runtime / map_test.go
blob9b5b051250e58670a9dab15b30a4736d74a58af0
1 // Copyright 2013 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.
5 package runtime_test
7 import (
8 "fmt"
9 "math"
10 "reflect"
11 "runtime"
12 "sort"
13 "strings"
14 "sync"
15 "testing"
18 // negative zero is a good test because:
19 // 1) 0 and -0 are equal, yet have distinct representations.
20 // 2) 0 is represented as all zeros, -0 isn't.
21 // I'm not sure the language spec actually requires this behavior,
22 // but it's what the current map implementation does.
23 func TestNegativeZero(t *testing.T) {
24 m := make(map[float64]bool, 0)
26 m[+0.0] = true
27 m[math.Copysign(0.0, -1.0)] = true // should overwrite +0 entry
29 if len(m) != 1 {
30 t.Error("length wrong")
33 for k := range m {
34 if math.Copysign(1.0, k) > 0 {
35 t.Error("wrong sign")
39 m = make(map[float64]bool, 0)
40 m[math.Copysign(0.0, -1.0)] = true
41 m[+0.0] = true // should overwrite -0.0 entry
43 if len(m) != 1 {
44 t.Error("length wrong")
47 for k := range m {
48 if math.Copysign(1.0, k) < 0 {
49 t.Error("wrong sign")
54 // nan is a good test because nan != nan, and nan has
55 // a randomized hash value.
56 func TestNan(t *testing.T) {
57 m := make(map[float64]int, 0)
58 nan := math.NaN()
59 m[nan] = 1
60 m[nan] = 2
61 m[nan] = 4
62 if len(m) != 3 {
63 t.Error("length wrong")
65 s := 0
66 for k, v := range m {
67 if k == k {
68 t.Error("nan disappeared")
70 if (v & (v - 1)) != 0 {
71 t.Error("value wrong")
73 s |= v
75 if s != 7 {
76 t.Error("values wrong")
80 // Maps aren't actually copied on assignment.
81 func TestAlias(t *testing.T) {
82 m := make(map[int]int, 0)
83 m[0] = 5
84 n := m
85 n[0] = 6
86 if m[0] != 6 {
87 t.Error("alias didn't work")
91 func TestGrowWithNaN(t *testing.T) {
92 m := make(map[float64]int, 4)
93 nan := math.NaN()
94 m[nan] = 1
95 m[nan] = 2
96 m[nan] = 4
97 cnt := 0
98 s := 0
99 growflag := true
100 for k, v := range m {
101 if growflag {
102 // force a hashtable resize
103 for i := 0; i < 100; i++ {
104 m[float64(i)] = i
106 growflag = false
108 if k != k {
109 cnt++
110 s |= v
113 if cnt != 3 {
114 t.Error("NaN keys lost during grow")
116 if s != 7 {
117 t.Error("NaN values lost during grow")
121 type FloatInt struct {
122 x float64
123 y int
126 func TestGrowWithNegativeZero(t *testing.T) {
127 negzero := math.Copysign(0.0, -1.0)
128 m := make(map[FloatInt]int, 4)
129 m[FloatInt{0.0, 0}] = 1
130 m[FloatInt{0.0, 1}] = 2
131 m[FloatInt{0.0, 2}] = 4
132 m[FloatInt{0.0, 3}] = 8
133 growflag := true
134 s := 0
135 cnt := 0
136 negcnt := 0
137 // The first iteration should return the +0 key.
138 // The subsequent iterations should return the -0 key.
139 // I'm not really sure this is required by the spec,
140 // but it makes sense.
141 // TODO: are we allowed to get the first entry returned again???
142 for k, v := range m {
143 if v == 0 {
144 continue
145 } // ignore entries added to grow table
146 cnt++
147 if math.Copysign(1.0, k.x) < 0 {
148 if v&16 == 0 {
149 t.Error("key/value not updated together 1")
151 negcnt++
152 s |= v & 15
153 } else {
154 if v&16 == 16 {
155 t.Error("key/value not updated together 2", k, v)
157 s |= v
159 if growflag {
160 // force a hashtable resize
161 for i := 0; i < 100; i++ {
162 m[FloatInt{3.0, i}] = 0
164 // then change all the entries
165 // to negative zero
166 m[FloatInt{negzero, 0}] = 1 | 16
167 m[FloatInt{negzero, 1}] = 2 | 16
168 m[FloatInt{negzero, 2}] = 4 | 16
169 m[FloatInt{negzero, 3}] = 8 | 16
170 growflag = false
173 if s != 15 {
174 t.Error("entry missing", s)
176 if cnt != 4 {
177 t.Error("wrong number of entries returned by iterator", cnt)
179 if negcnt != 3 {
180 t.Error("update to negzero missed by iteration", negcnt)
184 func TestIterGrowAndDelete(t *testing.T) {
185 m := make(map[int]int, 4)
186 for i := 0; i < 100; i++ {
187 m[i] = i
189 growflag := true
190 for k := range m {
191 if growflag {
192 // grow the table
193 for i := 100; i < 1000; i++ {
194 m[i] = i
196 // delete all odd keys
197 for i := 1; i < 1000; i += 2 {
198 delete(m, i)
200 growflag = false
201 } else {
202 if k&1 == 1 {
203 t.Error("odd value returned")
209 // make sure old bucket arrays don't get GCd while
210 // an iterator is still using them.
211 func TestIterGrowWithGC(t *testing.T) {
212 m := make(map[int]int, 4)
213 for i := 0; i < 16; i++ {
214 m[i] = i
216 growflag := true
217 bitmask := 0
218 for k := range m {
219 if k < 16 {
220 bitmask |= 1 << uint(k)
222 if growflag {
223 // grow the table
224 for i := 100; i < 1000; i++ {
225 m[i] = i
227 // trigger a gc
228 runtime.GC()
229 growflag = false
232 if bitmask != 1<<16-1 {
233 t.Error("missing key", bitmask)
237 func testConcurrentReadsAfterGrowth(t *testing.T, useReflect bool) {
238 t.Parallel()
239 if runtime.GOMAXPROCS(-1) == 1 {
240 if runtime.GOARCH == "s390" {
241 // Test uses too much address space on 31-bit S390.
242 defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(8))
243 } else {
244 defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(16))
247 numLoop := 10
248 numGrowStep := 250
249 numReader := 16
250 if testing.Short() {
251 numLoop, numGrowStep = 2, 500
253 for i := 0; i < numLoop; i++ {
254 m := make(map[int]int, 0)
255 for gs := 0; gs < numGrowStep; gs++ {
256 m[gs] = gs
257 var wg sync.WaitGroup
258 wg.Add(numReader * 2)
259 for nr := 0; nr < numReader; nr++ {
260 go func() {
261 defer wg.Done()
262 for range m {
265 go func() {
266 defer wg.Done()
267 for key := 0; key < gs; key++ {
268 _ = m[key]
271 if useReflect {
272 wg.Add(1)
273 go func() {
274 defer wg.Done()
275 mv := reflect.ValueOf(m)
276 keys := mv.MapKeys()
277 for _, k := range keys {
278 mv.MapIndex(k)
283 wg.Wait()
288 func TestConcurrentReadsAfterGrowth(t *testing.T) {
289 testConcurrentReadsAfterGrowth(t, false)
292 func TestConcurrentReadsAfterGrowthReflect(t *testing.T) {
293 testConcurrentReadsAfterGrowth(t, true)
296 func TestBigItems(t *testing.T) {
297 var key [256]string
298 for i := 0; i < 256; i++ {
299 key[i] = "foo"
301 m := make(map[[256]string][256]string, 4)
302 for i := 0; i < 100; i++ {
303 key[37] = fmt.Sprintf("string%02d", i)
304 m[key] = key
306 var keys [100]string
307 var values [100]string
308 i := 0
309 for k, v := range m {
310 keys[i] = k[37]
311 values[i] = v[37]
314 sort.Strings(keys[:])
315 sort.Strings(values[:])
316 for i := 0; i < 100; i++ {
317 if keys[i] != fmt.Sprintf("string%02d", i) {
318 t.Errorf("#%d: missing key: %v", i, keys[i])
320 if values[i] != fmt.Sprintf("string%02d", i) {
321 t.Errorf("#%d: missing value: %v", i, values[i])
326 func TestMapHugeZero(t *testing.T) {
327 type T [4000]byte
328 m := map[int]T{}
329 x := m[0]
330 if x != (T{}) {
331 t.Errorf("map value not zero")
333 y, ok := m[0]
334 if ok {
335 t.Errorf("map value should be missing")
337 if y != (T{}) {
338 t.Errorf("map value not zero")
342 type empty struct {
345 func TestEmptyKeyAndValue(t *testing.T) {
346 a := make(map[int]empty, 4)
347 b := make(map[empty]int, 4)
348 c := make(map[empty]empty, 4)
349 a[0] = empty{}
350 b[empty{}] = 0
351 b[empty{}] = 1
352 c[empty{}] = empty{}
354 if len(a) != 1 {
355 t.Errorf("empty value insert problem")
357 if b[empty{}] != 1 {
358 t.Errorf("empty key returned wrong value")
362 // Tests a map with a single bucket, with same-lengthed short keys
363 // ("quick keys") as well as long keys.
364 func TestSingleBucketMapStringKeys_DupLen(t *testing.T) {
365 testMapLookups(t, map[string]string{
366 "x": "x1val",
367 "xx": "x2val",
368 "foo": "fooval",
369 "bar": "barval", // same key length as "foo"
370 "xxxx": "x4val",
371 strings.Repeat("x", 128): "longval1",
372 strings.Repeat("y", 128): "longval2",
376 // Tests a map with a single bucket, with all keys having different lengths.
377 func TestSingleBucketMapStringKeys_NoDupLen(t *testing.T) {
378 testMapLookups(t, map[string]string{
379 "x": "x1val",
380 "xx": "x2val",
381 "foo": "fooval",
382 "xxxx": "x4val",
383 "xxxxx": "x5val",
384 "xxxxxx": "x6val",
385 strings.Repeat("x", 128): "longval",
389 func testMapLookups(t *testing.T, m map[string]string) {
390 for k, v := range m {
391 if m[k] != v {
392 t.Fatalf("m[%q] = %q; want %q", k, m[k], v)
397 // Tests whether the iterator returns the right elements when
398 // started in the middle of a grow, when the keys are NaNs.
399 func TestMapNanGrowIterator(t *testing.T) {
400 m := make(map[float64]int)
401 nan := math.NaN()
402 const nBuckets = 16
403 // To fill nBuckets buckets takes LOAD * nBuckets keys.
404 nKeys := int(nBuckets * *runtime.HashLoad)
406 // Get map to full point with nan keys.
407 for i := 0; i < nKeys; i++ {
408 m[nan] = i
410 // Trigger grow
411 m[1.0] = 1
412 delete(m, 1.0)
414 // Run iterator
415 found := make(map[int]struct{})
416 for _, v := range m {
417 if v != -1 {
418 if _, repeat := found[v]; repeat {
419 t.Fatalf("repeat of value %d", v)
421 found[v] = struct{}{}
423 if len(found) == nKeys/2 {
424 // Halfway through iteration, finish grow.
425 for i := 0; i < nBuckets; i++ {
426 delete(m, 1.0)
430 if len(found) != nKeys {
431 t.Fatalf("missing value")
435 func TestMapIterOrder(t *testing.T) {
436 for _, n := range [...]int{3, 7, 9, 15} {
437 for i := 0; i < 1000; i++ {
438 // Make m be {0: true, 1: true, ..., n-1: true}.
439 m := make(map[int]bool)
440 for i := 0; i < n; i++ {
441 m[i] = true
443 // Check that iterating over the map produces at least two different orderings.
444 ord := func() []int {
445 var s []int
446 for key := range m {
447 s = append(s, key)
449 return s
451 first := ord()
452 ok := false
453 for try := 0; try < 100; try++ {
454 if !reflect.DeepEqual(first, ord()) {
455 ok = true
456 break
459 if !ok {
460 t.Errorf("Map with n=%d elements had consistent iteration order: %v", n, first)
461 break
467 // Issue 8410
468 func TestMapSparseIterOrder(t *testing.T) {
469 // Run several rounds to increase the probability
470 // of failure. One is not enough.
471 NextRound:
472 for round := 0; round < 10; round++ {
473 m := make(map[int]bool)
474 // Add 1000 items, remove 980.
475 for i := 0; i < 1000; i++ {
476 m[i] = true
478 for i := 20; i < 1000; i++ {
479 delete(m, i)
482 var first []int
483 for i := range m {
484 first = append(first, i)
487 // 800 chances to get a different iteration order.
488 // See bug 8736 for why we need so many tries.
489 for n := 0; n < 800; n++ {
490 idx := 0
491 for i := range m {
492 if i != first[idx] {
493 // iteration order changed.
494 continue NextRound
496 idx++
499 t.Fatalf("constant iteration order on round %d: %v", round, first)
503 func TestMapStringBytesLookup(t *testing.T) {
504 // Use large string keys to avoid small-allocation coalescing,
505 // which can cause AllocsPerRun to report lower counts than it should.
506 m := map[string]int{
507 "1000000000000000000000000000000000000000000000000": 1,
508 "2000000000000000000000000000000000000000000000000": 2,
510 buf := []byte("1000000000000000000000000000000000000000000000000")
511 if x := m[string(buf)]; x != 1 {
512 t.Errorf(`m[string([]byte("1"))] = %d, want 1`, x)
514 buf[0] = '2'
515 if x := m[string(buf)]; x != 2 {
516 t.Errorf(`m[string([]byte("2"))] = %d, want 2`, x)
519 t.Skip("does not work on gccgo without better escape analysis")
521 var x int
522 n := testing.AllocsPerRun(100, func() {
523 x += m[string(buf)]
525 if n != 0 {
526 t.Errorf("AllocsPerRun for m[string(buf)] = %v, want 0", n)
529 x = 0
530 n = testing.AllocsPerRun(100, func() {
531 y, ok := m[string(buf)]
532 if !ok {
533 panic("!ok")
535 x += y
537 if n != 0 {
538 t.Errorf("AllocsPerRun for x,ok = m[string(buf)] = %v, want 0", n)
542 func TestMapLargeKeyNoPointer(t *testing.T) {
543 const (
544 I = 1000
545 N = 64
547 type T [N]int
548 m := make(map[T]int)
549 for i := 0; i < I; i++ {
550 var v T
551 for j := 0; j < N; j++ {
552 v[j] = i + j
554 m[v] = i
556 runtime.GC()
557 for i := 0; i < I; i++ {
558 var v T
559 for j := 0; j < N; j++ {
560 v[j] = i + j
562 if m[v] != i {
563 t.Fatalf("corrupted map: want %+v, got %+v", i, m[v])
568 func TestMapLargeValNoPointer(t *testing.T) {
569 const (
570 I = 1000
571 N = 64
573 type T [N]int
574 m := make(map[int]T)
575 for i := 0; i < I; i++ {
576 var v T
577 for j := 0; j < N; j++ {
578 v[j] = i + j
580 m[i] = v
582 runtime.GC()
583 for i := 0; i < I; i++ {
584 var v T
585 for j := 0; j < N; j++ {
586 v[j] = i + j
588 v1 := m[i]
589 for j := 0; j < N; j++ {
590 if v1[j] != v[j] {
591 t.Fatalf("corrupted map: want %+v, got %+v", v, v1)
597 func benchmarkMapPop(b *testing.B, n int) {
598 m := map[int]int{}
599 for i := 0; i < b.N; i++ {
600 for j := 0; j < n; j++ {
601 m[j] = j
603 for j := 0; j < n; j++ {
604 // Use iterator to pop an element.
605 // We want this to be fast, see issue 8412.
606 for k := range m {
607 delete(m, k)
608 break
614 func BenchmarkMapPop100(b *testing.B) { benchmarkMapPop(b, 100) }
615 func BenchmarkMapPop1000(b *testing.B) { benchmarkMapPop(b, 1000) }
616 func BenchmarkMapPop10000(b *testing.B) { benchmarkMapPop(b, 10000) }
618 func TestNonEscapingMap(t *testing.T) {
619 t.Skip("does not work on gccgo without better escape analysis")
620 n := testing.AllocsPerRun(1000, func() {
621 m := make(map[int]int)
622 m[0] = 0
624 if n != 0 {
625 t.Fatalf("want 0 allocs, got %v", n)