Skip to content

Commit

Permalink
feat: allow passing FnOnce closures (#23)
Browse files Browse the repository at this point in the history
FnOnce is most flexible, and there is no reason why this library
would ever change to call the closure more than once.
  • Loading branch information
KamilaBorowska authored Sep 24, 2023
1 parent 8895379 commit 46b6313
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
//! let s = temp_env::with_var("INNER_ENV_VAR", Some("inner value"), || {
//! std::env::var("INNER_ENV_VAR").unwrap()
//! });
//! println!("{}", s);
//! println!("{}", s);
//! ```
//!

Expand All @@ -63,7 +63,7 @@ pub fn with_var<K, V, F, R>(key: K, value: Option<V>, closure: F) -> R
where
K: AsRef<OsStr> + Clone + Eq + Hash,
V: AsRef<OsStr> + Clone,
F: Fn() -> R,
F: FnOnce() -> R,
{
with_vars([(key, value)], closure)
}
Expand All @@ -82,7 +82,7 @@ where
pub fn with_var_unset<K, F, R>(key: K, closure: F) -> R
where
K: AsRef<OsStr> + Clone + Eq + Hash,
F: Fn() -> R,
F: FnOnce() -> R,
{
with_var(key, None::<&str>, closure)
}
Expand Down Expand Up @@ -127,7 +127,7 @@ pub fn with_vars<K, V, F, R>(kvs: impl AsRef<[(K, Option<V>)]>, closure: F) -> R
where
K: AsRef<OsStr> + Clone + Eq + Hash,
V: AsRef<OsStr> + Clone,
F: Fn() -> R,
F: FnOnce() -> R,
{
let old_env = RestoreEnv::capture(
SERIAL_TEST.lock(),
Expand Down Expand Up @@ -162,7 +162,7 @@ where
pub fn with_vars_unset<K, F, R>(keys: impl AsRef<[K]>, closure: F) -> R
where
K: AsRef<OsStr> + Clone + Eq + Hash,
F: Fn() -> R,
F: FnOnce() -> R,
{
let kvs = keys
.as_ref()
Expand Down Expand Up @@ -535,6 +535,15 @@ mod tests {
assert!(env::var("MY_VAR_2").is_err());
}

#[test]
fn test_fn_once() {
let value = String::from("Hello, ");
let value = crate::with_var("WORLD", Some("world!"), || {
value + &env::var("WORLD").unwrap()
});
assert_eq!(value, "Hello, world!");
}

#[cfg(feature = "async_closure")]
async fn check_var() {
let v = std::env::var("MY_VAR").unwrap();
Expand Down

0 comments on commit 46b6313

Please sign in to comment.