random.go 660 B

123456789101112131415161718192021222324252627282930313233343536
  1. // License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package random
  3. import (
  4. "crypto/rand"
  5. "fmt"
  6. "math/big"
  7. "golang.org/x/exp/constraints"
  8. )
  9. var _ = fmt.Print
  10. // Return a random integer in the range [0, limit). limit must be > 0
  11. func Int[T constraints.Integer](limit T) T {
  12. b := big.NewInt(int64(limit))
  13. n, err := rand.Int(rand.Reader, b)
  14. if err != nil {
  15. panic(err)
  16. }
  17. return T(n.Uint64())
  18. }
  19. // Return one of items randomnly
  20. func Choice[T any](items ...T) T {
  21. return items[Int(len(items))]
  22. }
  23. // Write randomn bytes into the provided slice
  24. func Bytes(b []byte) {
  25. if _, err := rand.Read(b); err != nil {
  26. panic(err)
  27. }
  28. }