MCPcopy Index your code
hub / github.com/coder/coder / StringCharset

Function StringCharset

cryptorand/strings.go:71–109  ·  view source on GitHub ↗

StringCharset generates a random string using the provided charset and size.

(charSetStr string, size int)

Source from the content-addressed store, hash-verified

69
70// StringCharset generates a random string using the provided charset and size.
71func StringCharset(charSetStr string, size int) (string, error) {
72 if size == 0 {
73 return "", nil
74 }
75
76 if len(charSetStr) == 0 {
77 return "", xerrors.Errorf("charSetStr must not be empty")
78 }
79
80 charSet := []rune(charSetStr)
81
82 // We pre-allocate the entropy to amortize the crypto/rand syscall overhead.
83 entropy := make([]byte, 4*size)
84
85 _, err := rand.Read(entropy)
86 if err != nil {
87 return "", err
88 }
89
90 var buf strings.Builder
91 buf.Grow(size)
92
93 for i := 0; i < size; i++ {
94 r := binary.BigEndian.Uint32(entropy[:4])
95 entropy = entropy[4:]
96
97 ci, err := unbiasedModulo32(
98 r,
99 int32(len(charSet)), // #nosec G115 - Safe conversion as len(charSet) will be reasonably small for character sets
100 )
101 if err != nil {
102 return "", err
103 }
104
105 _, _ = buf.WriteRune(charSet[ci])
106 }
107
108 return buf.String(), nil
109}
110
111// String returns a random string using Default.
112func String(size int) (string, error) {

Callers 9

genAgentMetricFunction · 0.92
CreateMethod · 0.92
TestStringCharsetFunction · 0.92
sshMethod · 0.92
userCreateMethod · 0.92
mainFunction · 0.92
StringFunction · 0.85
HexStringFunction · 0.85
Sha1StringFunction · 0.85

Calls 4

unbiasedModulo32Function · 0.85
ReadMethod · 0.65
ErrorfMethod · 0.45
StringMethod · 0.45

Tested by 2

genAgentMetricFunction · 0.74
TestStringCharsetFunction · 0.74