use std::sync::RwLock;
static LOCKED: RwLock<Option<String>> = RwLock::new(None);
pub fn init_from_env() {
let value = std::env::var("ORIGIN_SPACE")
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
*LOCKED.write().expect("lock_state write lock poisoned") = value;
}
pub fn locked_space() -> Option<String> {
LOCKED
.read()
.expect("lock_state read lock poisoned")
.clone()
}
pub fn is_locked() -> bool {
LOCKED
.read()
.expect("lock_state read lock poisoned")
.is_some()
}
#[cfg(test)]
pub(crate) static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn locked_space_returns_none_when_env_unset() {
let _guard = ENV_LOCK.lock().unwrap();
std::env::remove_var("ORIGIN_SPACE");
init_from_env();
assert_eq!(locked_space(), None);
assert!(!is_locked());
}
#[test]
fn locked_space_returns_value_when_env_set() {
let _guard = ENV_LOCK.lock().unwrap();
std::env::set_var("ORIGIN_SPACE", "work");
init_from_env();
assert_eq!(locked_space().as_deref(), Some("work"));
assert!(is_locked());
std::env::remove_var("ORIGIN_SPACE");
init_from_env();
}
#[test]
fn whitespace_only_value_treated_as_unset() {
let _guard = ENV_LOCK.lock().unwrap();
std::env::set_var("ORIGIN_SPACE", " ");
init_from_env();
assert_eq!(locked_space(), None);
std::env::remove_var("ORIGIN_SPACE");
init_from_env();
}
}