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.
18 // https://golang.org/issue/6849.
19 func TestPrimeSmall(t
*testing
.T
) {
20 for n
:= 2; n
< 10; n
++ {
21 p
, err
:= rand
.Prime(rand
.Reader
, n
)
23 t
.Fatalf("Can't generate %d-bit prime: %v", n
, err
)
26 t
.Fatalf("%v is not %d-bit", p
, n
)
28 if !p
.ProbablyPrime(32) {
29 t
.Fatalf("%v is not prime", p
)
34 // Test that passing bits < 2 causes Prime to return nil, error
35 func TestPrimeBitsLt2(t
*testing
.T
) {
36 if p
, err
:= rand
.Prime(rand
.Reader
, 1); p
!= nil || err
== nil {
37 t
.Errorf("Prime should return nil, error when called with bits < 2")
41 func TestInt(t
*testing
.T
) {
42 // start at 128 so the case of (max.BitLen() % 8) == 0 is covered
43 for n
:= 128; n
< 140; n
++ {
44 b
:= new(big
.Int
).SetInt64(int64(n
))
45 if i
, err
:= rand
.Int(rand
.Reader
, b
); err
!= nil {
46 t
.Fatalf("Can't generate random value: %v, %v", i
, err
)
51 type countingReader
struct {
56 func (r
*countingReader
) Read(p
[]byte) (n
int, err error
) {
62 // Test that Int reads only the necessary number of bytes from the reader for
63 // max at each bit length
64 func TestIntReads(t
*testing
.T
) {
65 for i
:= 0; i
< 32; i
++ {
66 max
:= int64(1 << uint64(i
))
67 t
.Run(fmt
.Sprintf("max=%d", max
), func(t
*testing
.T
) {
68 reader
:= &countingReader
{r
: rand
.Reader
}
70 _
, err
:= rand
.Int(reader
, big
.NewInt(max
))
72 t
.Fatalf("Can't generate random value: %d, %v", max
, err
)
74 expected
:= (i
+ 7) / 8
75 if reader
.n
!= expected
{
76 t
.Errorf("Int(reader, %d) should read %d bytes, but it read: %d", max
, expected
, reader
.n
)
82 // Test that Int does not mask out valid return values
83 func TestIntMask(t
*testing
.T
) {
84 for max
:= 1; max
<= 256; max
++ {
85 t
.Run(fmt
.Sprintf("max=%d", max
), func(t
*testing
.T
) {
86 for i
:= 0; i
< max
; i
++ {
89 n
, err
:= rand
.Int(&b
, big
.NewInt(int64(max
)))
91 t
.Fatalf("Can't generate random value: %d, %v", max
, err
)
93 if n
.Int64() != int64(i
) {
94 t
.Errorf("Int(reader, %d) should have returned value of %d, but it returned: %v", max
, i
, n
)
101 func testIntPanics(t
*testing
.T
, b
*big
.Int
) {
103 if err
:= recover(); err
== nil {
104 t
.Errorf("Int should panic when called with max <= 0: %v", b
)
107 rand
.Int(rand
.Reader
, b
)
110 // Test that passing a new big.Int as max causes Int to panic
111 func TestIntEmptyMaxPanics(t
*testing
.T
) {
116 // Test that passing a negative value as max causes Int to panic
117 func TestIntNegativeMaxPanics(t
*testing
.T
) {
118 b
:= new(big
.Int
).SetInt64(int64(-1))
122 func BenchmarkPrime(b
*testing
.B
) {
123 r
:= mathrand
.New(mathrand
.NewSource(time
.Now().UnixNano()))
124 for i
:= 0; i
< b
.N
; i
++ {