Currently, the codebase uses OnceLock and some unsafe code to manage global environment locking. This adds unnecessary complexity and potential safety concerns. It is suggested to replace this mechanism with a static Mutex, which would simplify the locking logic and remove the need for unsafe blocks and OnceLock boilerplate.
A proposed implementation is as follows:
use std::env;
use std::ffi::OsStr;
use std::sync::Mutex;
static ENV_LOCK: Mutex<()> = Mutex::new(());
pub fn with_lock<T, F: FnOnce() -> T>(f: F) -> T {
let _guard = ENV_LOCK.lock().unwrap();
f()
}
pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, val: V) {
let _guard = ENV_LOCK.lock().unwrap();
env::set_var(key, val);
}
pub fn remove_var<K: AsRef<OsStr>>(key: K) {
let _guard = ENV_LOCK.lock().unwrap();
env::remove_var(key);
}
pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, env::VarError> {
let _guard = ENV_LOCK.lock().unwrap();
env::var(key)
}
Tests can then use env::set_var, remove_var, or with_lock directly under the global mutex, eliminating the need for unsafe code and OnceLock.
Action items:
- Refactor the environment locking code to use a static
Mutex as shown above.
- Remove all usages of
OnceLock and unsafe related to environment locking.
- Update tests to use the new locking mechanism if necessary.
This change will improve code safety and maintainability.
I created this issue for @leynos from #147 (comment).
Tips and commands
Getting Help
Currently, the codebase uses
OnceLockand someunsafecode to manage global environment locking. This adds unnecessary complexity and potential safety concerns. It is suggested to replace this mechanism with a staticMutex, which would simplify the locking logic and remove the need forunsafeblocks andOnceLockboilerplate.A proposed implementation is as follows:
Tests can then use
env::set_var,remove_var, orwith_lockdirectly under the global mutex, eliminating the need forunsafecode andOnceLock.Action items:
Mutexas shown above.OnceLockandunsaferelated to environment locking.This change will improve code safety and maintainability.
I created this issue for @leynos from #147 (comment).
Tips and commands
Getting Help