rand.go 690 B

12345678910111213141516171819202122232425262728293031
  1. package rand
  2. import (
  3. "crypto/rand"
  4. "fmt"
  5. "io"
  6. "math/big"
  7. )
  8. func init() {
  9. Reader = rand.Reader
  10. }
  11. // Reader provides a random reader that can reset during testing.
  12. var Reader io.Reader
  13. // Int63n returns a int64 between zero and value of max, read from an io.Reader source.
  14. func Int63n(reader io.Reader, max int64) (int64, error) {
  15. bi, err := rand.Int(reader, big.NewInt(max))
  16. if err != nil {
  17. return 0, fmt.Errorf("failed to read random value, %w", err)
  18. }
  19. return bi.Int64(), nil
  20. }
  21. // CryptoRandInt63n returns a random int64 between zero and value of max
  22. // obtained from the crypto rand source.
  23. func CryptoRandInt63n(max int64) (int64, error) {
  24. return Int63n(Reader, max)
  25. }