MCPcopy Create free account
hub / github.com/labstack/gommon / String

Method String

random/random.go:45–87  ·  view source on GitHub ↗
(length uint8, charsets ...string)

Source from the content-addressed store, hash-verified

43}
44
45func (r *Random) String(length uint8, charsets ...string) string {
46 charset := strings.Join(charsets, "")
47 if charset == "" {
48 charset = Alphanumeric
49 }
50
51 charsetLen := len(charset)
52 if charsetLen > 255 {
53 charsetLen = 255
54 }
55 maxByte := 255 - (256 % charsetLen)
56
57 reader := r.readerPool.Get().(*bufio.Reader)
58 defer r.readerPool.Put(reader)
59
60 b := make([]byte, length)
61 rs := make([]byte, length+(length/4)) // perf: avoid read from rand.Reader many times
62 var i uint8 = 0
63
64 // security note:
65 // we can't just simply do b[i]=charset[rb%byte(charsetLen)],
66 // for example, when charsetLen is 52, and rb is [0, 255], 256 = 52 * 4 + 48.
67 // this will make the first 48 characters more possibly to be generated then others.
68 // so we have to skip bytes when rb > maxByte
69
70 for {
71 _, err := io.ReadFull(reader, rs)
72 if err != nil {
73 panic("unexpected error happened when reading from bufio.NewReader(crypto/rand.Reader)")
74 }
75 for _, rb := range rs {
76 if rb > byte(maxByte) {
77 // Skip this number to avoid bias.
78 continue
79 }
80 b[i] = charset[rb%byte(charsetLen)]
81 i++
82 if i == length {
83 return string(b)
84 }
85 }
86 }
87}
88
89func String(length uint8, charsets ...string) string {
90 return global.String(length, charsets...)

Callers 12

StringFunction · 0.80
TestFunction · 0.80
TestDial_PlainAcceptsFunction · 0.80
testFunction · 0.80
loggerFatalTestFunction · 0.80
TestFormatFunction · 0.80
TestJSONFunction · 0.80
TestStringWithQuotesFunction · 0.80
TestEmptyHeaderFunction · 0.80
TestCallerFileFunction · 0.80
logMethod · 0.80
outerFunction · 0.80

Calls

no outgoing calls

Tested by 9

TestFunction · 0.64
TestDial_PlainAcceptsFunction · 0.64
testFunction · 0.64
loggerFatalTestFunction · 0.64
TestFormatFunction · 0.64
TestJSONFunction · 0.64
TestStringWithQuotesFunction · 0.64
TestEmptyHeaderFunction · 0.64
TestCallerFileFunction · 0.64