1// Copyright 2017 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.
4
5package runtime_test
6
7import (
8	. "runtime"
9	"strconv"
10	"testing"
11	_ "unsafe" // for go:linkname
12)
13
14func TestReadRandom(t *testing.T) {
15	if *ReadRandomFailed {
16		switch GOOS {
17		default:
18			t.Fatalf("readRandom failed at startup")
19		case "plan9":
20			// ok
21		}
22	}
23}
24
25func BenchmarkFastrand(b *testing.B) {
26	b.RunParallel(func(pb *testing.PB) {
27		for pb.Next() {
28			Fastrand()
29		}
30	})
31}
32
33func BenchmarkFastrand64(b *testing.B) {
34	b.RunParallel(func(pb *testing.PB) {
35		for pb.Next() {
36			Fastrand64()
37		}
38	})
39}
40
41func BenchmarkFastrandHashiter(b *testing.B) {
42	var m = make(map[int]int, 10)
43	for i := 0; i < 10; i++ {
44		m[i] = i
45	}
46	b.RunParallel(func(pb *testing.PB) {
47		for pb.Next() {
48			for range m {
49				break
50			}
51		}
52	})
53}
54
55var sink32 uint32
56
57func BenchmarkFastrandn(b *testing.B) {
58	for n := uint32(2); n <= 5; n++ {
59		b.Run(strconv.Itoa(int(n)), func(b *testing.B) {
60			for i := 0; i < b.N; i++ {
61				sink32 = Fastrandn(n)
62			}
63		})
64	}
65}
66
67//go:linkname fastrand runtime.fastrand
68func fastrand() uint32
69
70//go:linkname fastrandn runtime.fastrandn
71func fastrandn(uint32) uint32
72
73//go:linkname fastrand64 runtime.fastrand64
74func fastrand64() uint64
75
76func TestLegacyFastrand(t *testing.T) {
77	// Testing mainly that the calls work at all,
78	// but check that all three don't return the same number (1 in 2^64 chance)
79	{
80		x, y, z := fastrand(), fastrand(), fastrand()
81		if x == y && y == z {
82			t.Fatalf("fastrand three times = %#x, %#x, %#x, want different numbers", x, y, z)
83		}
84	}
85	{
86		x, y, z := fastrandn(1e9), fastrandn(1e9), fastrandn(1e9)
87		if x == y && y == z {
88			t.Fatalf("fastrandn three times = %#x, %#x, %#x, want different numbers", x, y, z)
89		}
90	}
91	{
92		x, y, z := fastrand64(), fastrand64(), fastrand64()
93		if x == y && y == z {
94			t.Fatalf("fastrand64 three times = %#x, %#x, %#x, want different numbers", x, y, z)
95		}
96	}
97}
98