rand: add PRNG.fill_buffer_from_set/2 (#21037)

This commit is contained in:
Delyan Angelov 2024-03-16 16:32:47 +02:00 committed by GitHub
parent 4221522c0a
commit a1c6377ab6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 143 additions and 31 deletions

View file

@ -93,6 +93,7 @@ fn internal_ulid_at_millisecond(mut rng PRNG, unix_time_milli u64) string {
}
}
@[direct_array_access]
fn internal_string_from_set(mut rng PRNG, charset string, len int) string {
if len == 0 {
return ''
@ -100,7 +101,7 @@ fn internal_string_from_set(mut rng PRNG, charset string, len int) string {
mut buf := unsafe { malloc_noscan(len + 1) }
for i in 0 .. len {
unsafe {
buf[i] = charset[intn(charset.len) or { 0 }]
buf[i] = charset[rng.u32() % charset.len]
}
}
unsafe {
@ -109,6 +110,19 @@ fn internal_string_from_set(mut rng PRNG, charset string, len int) string {
return unsafe { buf.vstring_with_len(len) }
}
@[direct_array_access]
fn internal_fill_buffer_from_set(mut rng PRNG, charset string, mut buf []u8) {
if buf.len == 0 {
return
}
blen := buf.len
for i in 0 .. blen {
unsafe {
buf[i] = charset[rng.u32() % charset.len]
}
}
}
fn deinit() {
unsafe {
default_rng.free() // free the implementation