rand: add uuid_v7(), session function, simplify uuid_v4() (#24313)

This commit is contained in:
kbkpbot 2025-04-25 23:30:57 +08:00 committed by GitHub
parent 0bcfd0f9ea
commit e0a7f87693
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 150 additions and 59 deletions

View file

@ -21,6 +21,58 @@ fn test_rand_uuid_v4() {
}
}
// uuid_v7:
fn test_rand_uuid_v7() {
uuid1 := rand.uuid_v7()
uuid2 := rand.uuid_v7()
uuid3 := rand.uuid_v7()
assert uuid1 != uuid2
assert uuid1 != uuid3
assert uuid2 != uuid3
assert uuid1.len == 36
assert uuid2.len == 36
assert uuid3.len == 36
for i in 0 .. 1000 {
x := rand.uuid_v7()
// check the version field is always 7:
assert x[14] == `7`
// and variant field is always 0b10:
assert x[19] in [`8`, `9`, `a`, `b`]
}
}
// uuid_v7_session:
fn test_rand_uuid_v7_session() {
mut u := rand.new_uuid_v7_session()
uuid1 := u.next()
uuid2 := u.next()
uuid3 := u.next()
assert uuid1 != uuid2
assert uuid1 != uuid3
assert uuid2 != uuid3
assert uuid1.len == 36
assert uuid2.len == 36
assert uuid3.len == 36
mut prev_counter := `3`
for i in 0 .. 1000 {
x := u.next()
// check the version field is always 7:
assert x[14] == `7`
// and variant field is always 0b10:
assert x[19] in [`8`, `9`, `a`, `b`]
// verify counter increase
assert x[17] == prev_counter
if prev_counter == `9` {
prev_counter = `a`
} else if prev_counter == `f` {
prev_counter = `0`
} else {
prev_counter++
}
}
}
// ulids:
fn test_ulids_are_unique() {
ulid1 := rand.ulid()