Skip to content

Commit 07ef667

Browse files
committed
random: make RandomChoice fall back to the global RNG
1 parent f8c3e8c commit 07ef667

File tree

3 files changed

+25
-16
lines changed

3 files changed

+25
-16
lines changed

random/random.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ import (
1919
)
2020

2121
// GetRandom returns a uint64 value chosen by Antithesis. You should not store this value or use it to seed a PRNG, but should use it immediately.
22+
//
23+
// Deprecated: Use [NewSource] instead.
2224
func GetRandom() uint64 {
2325
return internal.Get_random()
2426
}
@@ -46,3 +48,15 @@ func (source) Uint64() uint64 {
4648
func NewSource(seed int64) rand.Source {
4749
return source{}
4850
}
51+
52+
// RandomChoice returns a randomly chosen item from a list of options. You should not store this value, but should use it immediately.
53+
func RandomChoice[T any](things []T) T {
54+
numThings := len(things)
55+
if numThings == 0 {
56+
var nullThing T
57+
return nullThing
58+
}
59+
60+
index := rand.New(NewSource(0)).Intn(numThings)
61+
return things[index]
62+
}

random/random_choice.go

Lines changed: 0 additions & 16 deletions
This file was deleted.

random/random_local.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,14 @@ func GetRandom() uint64 {
1313
func NewSource(seed int64) rand.Source {
1414
return rand.NewSource(seed)
1515
}
16+
17+
func RandomChoice[T any](things []T) T {
18+
numThings := len(things)
19+
if numThings == 0 {
20+
var nullThing T
21+
return nullThing
22+
}
23+
24+
index := rand.Intn(numThings)
25+
return things[index]
26+
}

0 commit comments

Comments
 (0)