rand: add rand.uuid_v4()

pull/5965/head
Delyan Angelov 2020-07-24 13:58:30 +03:00
parent bfca55b87a
commit bba0edf9a3
1 changed files with 20 additions and 0 deletions

View File

@ -131,6 +131,7 @@ pub fn f64_in_range(min, max f64) f64 {
const ( const (
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
hex_chars = '0123456789abcdef'
) )
pub fn string(len int) string { pub fn string(len int) string {
@ -142,3 +143,22 @@ pub fn string(len int) string {
} }
return string(buf, len) 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)
}