From bba0edf9a3b03894c2d93ddb4f291089e72c4fd0 Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Fri, 24 Jul 2020 13:58:30 +0300 Subject: [PATCH] rand: add rand.uuid_v4() --- vlib/rand/rand.v | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/vlib/rand/rand.v b/vlib/rand/rand.v index d2994efe90..0269e6160a 100644 --- a/vlib/rand/rand.v +++ b/vlib/rand/rand.v @@ -131,6 +131,7 @@ pub fn f64_in_range(min, max f64) f64 { const ( chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' + hex_chars = '0123456789abcdef' ) pub fn string(len int) string { @@ -142,3 +143,22 @@ pub fn string(len int) string { } return string(buf, len) } + +// rand.uuid_v4 generate a completely random UUID (v4) +// See https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random) +pub fn uuid_v4() string { + mut buf := malloc(37) + for i in 0..36 { + unsafe { + buf[i] = hex_chars[intn(16)] + } + } + unsafe { + buf[8] = `-` + buf[13] = `-` + buf[18] = `-` + buf[23] = `-` + buf[36] = 0 + } + return string(buf, 36) +}