From c636a7080d593e6e5cad6e57527ddae4a4a0e5e7 Mon Sep 17 00:00:00 2001 From: cbracketdash Date: Wed, 10 Feb 2021 22:32:40 -0800 Subject: [PATCH] rand: add rand.ascii (#8675) --- vlib/rand/rand.v | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/vlib/rand/rand.v b/vlib/rand/rand.v index a75c93cef7..f5a557c556 100644 --- a/vlib/rand/rand.v +++ b/vlib/rand/rand.v @@ -168,6 +168,21 @@ pub fn hex(len int) string { return unsafe { buf.vstring_with_len(len) } } +const ( + ascii_chars = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\^_`abcdefghijklmnopqrstuvwxyz{|}~' +) + +// ascii returns a random string of the printable ASCII characters with length `len`. +pub fn ascii(len int) string { + mut buf := malloc(len) + for i in 0 .. len { + unsafe { + buf[i] = rand.ascii_chars[intn(rand.ascii_chars.len)] + } + } + return unsafe { buf.vstring_with_len(len) } +} + // uuid_v4 generates a random (v4) UUID // See https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random) pub fn uuid_v4() string {