From eb7009b60a44f26d1b3c14833c58f8191e14d082 Mon Sep 17 00:00:00 2001 From: cbracketdash Date: Wed, 10 Feb 2021 02:01:25 -0800 Subject: [PATCH] rand: generate hexadecimal numbers (#8664) --- vlib/rand/rand.v | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/vlib/rand/rand.v b/vlib/rand/rand.v index dd5b0da90c..a75c93cef7 100644 --- a/vlib/rand/rand.v +++ b/vlib/rand/rand.v @@ -152,6 +152,22 @@ pub fn string(len int) string { return unsafe { buf.vstring_with_len(len) } } + +const ( + hex_chars = 'abcdef0123456789' +) + +// hex returns a hexadecimal number of length `len` containing random characters in range `[a-f0-9]`. +pub fn hex(len int) string { + mut buf := malloc(len) + for i in 0 .. len { + unsafe { + buf[i] = rand.hex_chars[intn(rand.hex_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 {