io.util: simplify random number generation in util.v

pull/11955/head
Delyan Angelov 2021-09-23 14:20:39 +03:00
parent afc3531945
commit 4a0d00fb30
No known key found for this signature in database
GPG Key ID: 66886C0F12D595ED
1 changed files with 6 additions and 15 deletions

View File

@ -2,7 +2,6 @@ module util
import os import os
import rand import rand
import rand.seed as rseed
const ( const (
retries = 10000 retries = 10000
@ -25,18 +24,14 @@ pub fn temp_file(tfo TempFileOptions) ?(os.File, string) {
' could not create temporary file in "$d". Please ensure write permissions.') ' could not create temporary file in "$d". Please ensure write permissions.')
} }
d = d.trim_right(os.path_separator) d = d.trim_right(os.path_separator)
mut rng := rand.new_default()
prefix, suffix := prefix_and_suffix(tfo.pattern) or { return error(@FN + ' ' + err.msg) } prefix, suffix := prefix_and_suffix(tfo.pattern) or { return error(@FN + ' ' + err.msg) }
for retry := 0; retry < util.retries; retry++ { for retry := 0; retry < util.retries; retry++ {
path := os.join_path(d, prefix + random_number(mut rng) + suffix) path := os.join_path(d, prefix + random_number() + suffix)
mut mode := 'rw+' mut mode := 'rw+'
$if windows { $if windows {
mode = 'w+' mode = 'w+'
} }
mut file := os.open_file(path, mode, 0o600) or { mut file := os.open_file(path, mode, 0o600) or { continue }
rng.seed(rseed.time_seed_array(2))
continue
}
if os.exists(path) && os.is_file(path) { if os.exists(path) && os.is_file(path) {
return file, path return file, path
} }
@ -62,14 +57,10 @@ pub fn temp_dir(tdo TempFileOptions) ?string {
' could not create temporary directory "$d". Please ensure write permissions.') ' could not create temporary directory "$d". Please ensure write permissions.')
} }
d = d.trim_right(os.path_separator) d = d.trim_right(os.path_separator)
mut rng := rand.new_default()
prefix, suffix := prefix_and_suffix(tdo.pattern) or { return error(@FN + ' ' + err.msg) } prefix, suffix := prefix_and_suffix(tdo.pattern) or { return error(@FN + ' ' + err.msg) }
for retry := 0; retry < util.retries; retry++ { for retry := 0; retry < util.retries; retry++ {
path := os.join_path(d, prefix + random_number(mut rng) + suffix) path := os.join_path(d, prefix + random_number() + suffix)
os.mkdir_all(path) or { os.mkdir_all(path) or { continue }
rng.seed(rseed.time_seed_array(2))
continue
}
if os.is_dir(path) && os.exists(path) { if os.is_dir(path) && os.exists(path) {
os.is_writable_folder(path) or { os.is_writable_folder(path) or {
return error(@FN + return error(@FN +
@ -83,8 +74,8 @@ pub fn temp_dir(tdo TempFileOptions) ?string {
} }
// * Utility functions // * Utility functions
fn random_number(mut rng rand.PRNG) string { fn random_number() string {
s := (u32(1e9) + (u32(os.getpid()) + rng.u32() % u32(1e9))).str() s := (1_000_000_000 + (u32(os.getpid()) + rand.u32n(1_000_000_000))).str()
return s.substr(1, s.len) return s.substr(1, s.len)
} }