Skip to content

Commit c636a70

Browse files
author
cbracketdash
authored
rand: add rand.ascii (#8675)
1 parent d4f6488 commit c636a70

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

vlib/rand/rand.v

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,21 @@ pub fn hex(len int) string {
168168
return unsafe { buf.vstring_with_len(len) }
169169
}
170170

171+
const (
172+
ascii_chars = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\^_`abcdefghijklmnopqrstuvwxyz{|}~'
173+
)
174+
175+
// ascii returns a random string of the printable ASCII characters with length `len`.
176+
pub fn ascii(len int) string {
177+
mut buf := malloc(len)
178+
for i in 0 .. len {
179+
unsafe {
180+
buf[i] = rand.ascii_chars[intn(rand.ascii_chars.len)]
181+
}
182+
}
183+
return unsafe { buf.vstring_with_len(len) }
184+
}
185+
171186
// uuid_v4 generates a random (v4) UUID
172187
// See https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random)
173188
pub fn uuid_v4() string {

0 commit comments

Comments
 (0)