Skip to content

Commit 4f8b26e

Browse files
committed
all: replace math/rand with math/rand/v2
1 parent 0227c63 commit 4f8b26e

File tree

11 files changed

+53
-55
lines changed

11 files changed

+53
-55
lines changed

baggage/baggage_test.go

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ package baggage
55

66
import (
77
"fmt"
8-
"math/rand"
8+
"math/rand/v2"
99
"slices"
1010
"strings"
1111
"testing"
@@ -17,12 +17,8 @@ import (
1717
"go.opentelemetry.io/otel/internal/baggage"
1818
)
1919

20-
var rng *rand.Rand
21-
22-
func init() {
23-
// Seed with a static value to ensure deterministic results.
24-
rng = rand.New(rand.NewSource(1))
25-
}
20+
// Seed with a static value to ensure deterministic results.
21+
var rng = rand.New(rand.NewChaCha8([32]byte{}))
2622

2723
func TestValidateKeyChar(t *testing.T) {
2824
// ASCII only
@@ -255,7 +251,7 @@ func key(n int) string {
255251

256252
b := make([]rune, n)
257253
for i := range b {
258-
b[i] = r[rng.Intn(len(r))]
254+
b[i] = r[rng.IntN(len(r))]
259255
}
260256
return string(b)
261257
}

bridge/opencensus/internal/ocmetric/metric_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import (
77
"errors"
88
"fmt"
99
"math"
10-
"math/rand"
10+
"math/rand/v2"
1111
"reflect"
1212
"strconv"
1313
"testing"
@@ -1189,7 +1189,7 @@ func BenchmarkConvertExemplar(b *testing.B) {
11891189
for i := range data {
11901190
a := make(ocmetricdata.Attachments, attchmentsN)
11911191
for j := 0; j < attchmentsN; j++ {
1192-
a[strconv.Itoa(j)] = rand.Int63()
1192+
a[strconv.Itoa(j)] = rand.Int64()
11931193
}
11941194
data[i] = &ocmetricdata.Exemplar{
11951195
Value: rand.NormFloat64(),

bridge/opentracing/internal/mock.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ package internal // import "go.opentelemetry.io/otel/bridge/opentracing/internal
55

66
import (
77
"context"
8-
"math/rand"
8+
crand "crypto/rand"
9+
"math/rand/v2"
910
"reflect"
1011
"sync"
1112
"time"
@@ -44,7 +45,7 @@ type MockTracer struct {
4445
TraceFlags trace.TraceFlags
4546

4647
randLock sync.Mutex
47-
rand *rand.Rand
48+
rand *rand.ChaCha8
4849
}
4950

5051
var (
@@ -53,13 +54,15 @@ var (
5354
)
5455

5556
func NewMockTracer() *MockTracer {
57+
var seed [32]byte
58+
crand.Read(seed[:]) //nolint // crypto/rand never errors
5659
return &MockTracer{
5760
FinishedSpans: nil,
5861
SpareTraceIDs: nil,
5962
SpareSpanIDs: nil,
6063
SpareContextKeyValues: nil,
6164

62-
rand: rand.New(rand.NewSource(time.Now().Unix())),
65+
rand: rand.NewChaCha8(seed),
6366
}
6467
}
6568

metric/example_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import (
77
"context"
88
"database/sql"
99
"fmt"
10-
"math/rand"
10+
"math/rand/v2"
1111
"net/http"
1212
"runtime"
1313
"time"
@@ -159,7 +159,7 @@ func ExampleMeter_gauge() {
159159
getCPUFanSpeed := func() int64 {
160160
// Generates a random fan speed for demonstration purpose.
161161
// In real world applications, replace this to get the actual fan speed.
162-
return int64(1500 + rand.Intn(1000))
162+
return int64(1500 + rand.IntN(1000))
163163
}
164164

165165
fanSpeedSubscription := make(chan int64, 1)
@@ -170,7 +170,7 @@ func ExampleMeter_gauge() {
170170
// Synchronous gauges are used when the measurement cycle is
171171
// synchronous to an external change.
172172
// Simulate that external cycle here.
173-
time.Sleep(time.Duration(rand.Intn(3)) * time.Second)
173+
time.Sleep(time.Duration(rand.IntN(3)) * time.Second)
174174
fanSpeed := getCPUFanSpeed()
175175
fanSpeedSubscription <- fanSpeed
176176
}

sdk/metric/exemplar/fixed_size_reservoir.go

Lines changed: 8 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@ package exemplar // import "go.opentelemetry.io/otel/sdk/metric/exemplar"
55

66
import (
77
"context"
8+
crand "crypto/rand"
89
"math"
9-
"math/rand"
10+
"math/rand/v2"
1011
"time"
1112

1213
"go.opentelemetry.io/otel/attribute"
@@ -53,9 +54,11 @@ type FixedSizeReservoir struct {
5354
}
5455

5556
func newFixedSizeReservoir(s *storage) *FixedSizeReservoir {
57+
var seed [32]byte
58+
crand.Read(seed[:]) //nolint // crypto/rand never errors
5659
r := &FixedSizeReservoir{
5760
storage: s,
58-
rng: rand.New(rand.NewSource(time.Now().UnixNano())),
61+
rng: rand.New(rand.NewChaCha8(seed)),
5962
}
6063
r.reset()
6164
return r
@@ -64,26 +67,9 @@ func newFixedSizeReservoir(s *storage) *FixedSizeReservoir {
6467
// randomFloat64 returns, as a float64, a uniform pseudo-random number in the
6568
// open interval (0.0,1.0).
6669
func (r *FixedSizeReservoir) randomFloat64() float64 {
67-
// TODO: This does not return a uniform number. rng.Float64 returns a
68-
// uniformly random int in [0,2^53) that is divided by 2^53. Meaning it
69-
// returns multiples of 2^-53, and not all floating point numbers between 0
70-
// and 1 (i.e. for values less than 2^-4 the 4 last bits of the significand
71-
// are always going to be 0).
72-
//
73-
// An alternative algorithm should be considered that will actually return
74-
// a uniform number in the interval (0,1). For example, since the default
75-
// rand source provides a uniform distribution for Int63, this can be
76-
// converted following the prototypical code of Mersenne Twister 64 (Takuji
77-
// Nishimura and Makoto Matsumoto:
78-
// http://www.math.sci.hiroshima-u.ac.jp/m-mat/MT/VERSIONS/C-LANG/mt19937-64.c)
79-
//
80-
// (float64(rng.Int63()>>11) + 0.5) * (1.0 / 4503599627370496.0)
81-
//
82-
// There are likely many other methods to explore here as well.
83-
84-
f := r.rng.Float64()
70+
f := rand.Float64()
8571
for f == 0 {
86-
f = r.rng.Float64()
72+
f = rand.Float64()
8773
}
8874
return f
8975
}
@@ -146,7 +132,7 @@ func (r *FixedSizeReservoir) Offer(ctx context.Context, t time.Time, n Value, a
146132
} else {
147133
if r.count == r.next {
148134
// Overwrite a random existing measurement with the one offered.
149-
idx := int(r.rng.Int63n(int64(cap(r.store))))
135+
idx := int(rand.Int64N(int64(cap(r.store))))
150136
r.store[idx] = newMeasurement(ctx, t, n, a)
151137
r.advance()
152138
}

sdk/metric/exemplar/fixed_size_reservoir_test.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@ package exemplar
55

66
import (
77
"context"
8+
crand "crypto/rand"
89
"math"
9-
"math/rand"
10+
"math/rand/v2"
1011
"slices"
1112
"testing"
12-
"time"
1313

1414
"github.com/stretchr/testify/assert"
1515
)
@@ -28,7 +28,9 @@ func TestNewFixedSizeReservoirSamplingCorrectness(t *testing.T) {
2828
intensity := 0.1
2929
sampleSize := 1000
3030

31-
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
31+
var seed [32]byte
32+
crand.Read(seed[:]) //nolint // crypto/rand never errors
33+
rng := rand.New(rand.NewChaCha8(seed))
3234

3335
data := make([]float64, sampleSize*1000)
3436
for i := range data {

sdk/resource/benchmark_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ package resource_test
55

66
import (
77
"fmt"
8-
"math/rand"
8+
"math/rand/v2"
99
"testing"
1010

1111
"go.opentelemetry.io/otel/attribute"
@@ -21,18 +21,18 @@ func makeAttrs(n int) (_, _ *resource.Resource) {
2121
for i := 0; i < n; i++ {
2222
var k string
2323
for {
24-
k = fmt.Sprint("k", rand.Intn(1000000000))
24+
k = fmt.Sprint("k", rand.IntN(1000000000))
2525
if !used[k] {
2626
used[k] = true
2727
break
2828
}
2929
}
30-
l1[i] = attribute.String(k, fmt.Sprint("v", rand.Intn(1000000000)))
30+
l1[i] = attribute.String(k, fmt.Sprint("v", rand.IntN(1000000000)))
3131

3232
if rand.Float64() < conflict {
3333
l2[i] = l1[i]
3434
} else {
35-
l2[i] = attribute.String(k, fmt.Sprint("v", rand.Intn(1000000000)))
35+
l2[i] = attribute.String(k, fmt.Sprint("v", rand.IntN(1000000000)))
3636
}
3737
}
3838
return resource.NewSchemaless(l1...), resource.NewSchemaless(l2...)

sdk/trace/id_generator.go

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,7 @@ package trace // import "go.opentelemetry.io/otel/sdk/trace"
66
import (
77
"context"
88
crand "crypto/rand"
9-
"encoding/binary"
10-
"math/rand"
9+
"math/rand/v2"
1110
"sync"
1211

1312
"go.opentelemetry.io/otel/trace"
@@ -31,7 +30,7 @@ type IDGenerator interface {
3130

3231
type randomIDGenerator struct {
3332
sync.Mutex
34-
randSource *rand.Rand
33+
randSource *rand.ChaCha8
3534
}
3635

3736
var _ IDGenerator = &randomIDGenerator{}
@@ -73,9 +72,9 @@ func (gen *randomIDGenerator) NewIDs(ctx context.Context) (trace.TraceID, trace.
7372
}
7473

7574
func defaultIDGenerator() IDGenerator {
76-
gen := &randomIDGenerator{}
77-
var rngSeed int64
78-
_ = binary.Read(crand.Reader, binary.LittleEndian, &rngSeed)
79-
gen.randSource = rand.New(rand.NewSource(rngSeed))
80-
return gen
75+
var seed [32]byte
76+
crand.Read(seed[:]) //nolint // crypto/rand never errors
77+
return &randomIDGenerator{
78+
randSource: rand.NewChaCha8(seed),
79+
}
8180
}

sdk/trace/id_generator_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,15 @@ func TestNewSpanIDWithInvalidTraceID(t *testing.T) {
3939
spanID := gen.NewSpanID(context.Background(), trace.TraceID{})
4040
assert.Truef(t, spanID.IsValid(), "span id: %s", spanID.String())
4141
}
42+
43+
var (
44+
_traceID trace.TraceID
45+
_spanID trace.SpanID
46+
)
47+
48+
func BenchmarkIDGenerator(b *testing.B) {
49+
var gen IDGenerator = defaultIDGenerator()
50+
for range b.N {
51+
_traceID, _spanID = gen.NewIDs(context.Background())
52+
}
53+
}

sdk/trace/provider_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import (
77
"context"
88
"errors"
99
"fmt"
10-
"math/rand"
10+
"math/rand/v2"
1111
"testing"
1212

1313
"github.com/stretchr/testify/assert"

0 commit comments

Comments
 (0)