File: xrand.go

package info (click to toggle)
golang-nhooyr-websocket 1.8.12-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 528 kB
  • sloc: asm: 158; sh: 101; javascript: 62; makefile: 6
file content (53 lines) | stat: -rw-r--r-- 1,111 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package xrand

import (
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"math/big"
	"strings"
)

// Bytes generates random bytes with length n.
func Bytes(n int) []byte {
	b := make([]byte, n)
	_, err := rand.Reader.Read(b)
	if err != nil {
		panic(fmt.Sprintf("failed to generate rand bytes: %v", err))
	}
	return b
}

// String generates a random string with length n.
func String(n int) string {
	s := strings.ToValidUTF8(string(Bytes(n)), "_")
	s = strings.ReplaceAll(s, "\x00", "_")
	if len(s) > n {
		return s[:n]
	}
	if len(s) < n {
		// Pad with =
		extra := n - len(s)
		return s + strings.Repeat("=", extra)
	}
	return s
}

// Bool returns a randomly generated boolean.
func Bool() bool {
	return Int(2) == 1
}

// Int returns a randomly generated integer between [0, max).
func Int(max int) int {
	x, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
	if err != nil {
		panic(fmt.Sprintf("failed to get random int: %v", err))
	}
	return int(x.Int64())
}

// Base64 returns a randomly generated base64 string of length n.
func Base64(n int) string {
	return base64.StdEncoding.EncodeToString(Bytes(n))
}