io.util: simplify random number generation in util.v
parent
afc3531945
commit
4a0d00fb30
|
@ -2,7 +2,6 @@ module util
|
|||
|
||||
import os
|
||||
import rand
|
||||
import rand.seed as rseed
|
||||
|
||||
const (
|
||||
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.')
|
||||
}
|
||||
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) }
|
||||
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+'
|
||||
$if windows {
|
||||
mode = 'w+'
|
||||
}
|
||||
mut file := os.open_file(path, mode, 0o600) or {
|
||||
rng.seed(rseed.time_seed_array(2))
|
||||
continue
|
||||
}
|
||||
mut file := os.open_file(path, mode, 0o600) or { continue }
|
||||
if os.exists(path) && os.is_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.')
|
||||
}
|
||||
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) }
|
||||
for retry := 0; retry < util.retries; retry++ {
|
||||
path := os.join_path(d, prefix + random_number(mut rng) + suffix)
|
||||
os.mkdir_all(path) or {
|
||||
rng.seed(rseed.time_seed_array(2))
|
||||
continue
|
||||
}
|
||||
path := os.join_path(d, prefix + random_number() + suffix)
|
||||
os.mkdir_all(path) or { continue }
|
||||
if os.is_dir(path) && os.exists(path) {
|
||||
os.is_writable_folder(path) or {
|
||||
return error(@FN +
|
||||
|
@ -83,8 +74,8 @@ pub fn temp_dir(tdo TempFileOptions) ?string {
|
|||
}
|
||||
|
||||
// * Utility functions
|
||||
fn random_number(mut rng rand.PRNG) string {
|
||||
s := (u32(1e9) + (u32(os.getpid()) + rng.u32() % u32(1e9))).str()
|
||||
fn random_number() string {
|
||||
s := (1_000_000_000 + (u32(os.getpid()) + rand.u32n(1_000_000_000))).str()
|
||||
return s.substr(1, s.len)
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue