Skip to content

Commit

Permalink
Update README with rand/v2 examples and explanation.
Browse files Browse the repository at this point in the history
Signed-off-by: Erik Westra <[email protected]>
  • Loading branch information
webstradev committed Mar 2, 2025
1 parent f838578 commit 1cc5281
Showing 1 changed file with 7 additions and 3 deletions.
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ performance, cryptographic security, etc., use the
[ulid.Make](https://pkg.go.dev/github.com/oklog/ulid/v2#Make) helper function.
This function calls [time.Now](https://pkg.go.dev/time#Now) to get a timestamp,
and uses a source of entropy which is process-global,
[pseudo-random](https://pkg.go.dev/math/rand), and
[pseudo-random](https://pkg.go.dev/math/rand/v2), and
[monotonic](https://pkg.go.dev/github.com/oklog/ulid/v2#LockedMonotonicReader).

```go
Expand All @@ -69,15 +69,19 @@ More advanced use cases should utilize
[ulid.New](https://pkg.go.dev/github.com/oklog/ulid/v2#New).

```go
entropy := rand.New(rand.NewSource(time.Now().UnixNano()))

seed := [32]byte{}
binary.LittleEndian.PutUint64(seed[:8], uint64(time.Now().UnixNano()))
entropy := rand.NewChaCha8(seed) // This uses math/rand/v2.

ms := ulid.Timestamp(time.Now())
fmt.Println(ulid.New(ms, entropy))
// 01G65Z755AFWAKHE12NY0CQ9FH
```

Care should be taken when providing a source of entropy.

The above example utilizes [math/rand.Rand](https://pkg.go.dev/math/rand#Rand),
The above example utilizes [math/rand/v2.Rand](https://pkg.go.dev/math/rand/v2#Rand),
which is not safe for concurrent use by multiple goroutines. Consider
alternatives such as
[x/exp/rand](https://pkg.go.dev/golang.org/x/exp/rand#LockedSource).
Expand Down

0 comments on commit 1cc5281

Please sign in to comment.