-
Notifications
You must be signed in to change notification settings - Fork 366
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
71 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
//! A settable global variable. | ||
//! | ||
//! Used for testing purposes only. | ||
|
||
use std::sync::Mutex; | ||
|
||
/// A global variable that can be set exactly once. | ||
pub struct MutGlobal<T> { | ||
value: Mutex<Option<T>>, | ||
default_fn: fn() -> T, | ||
} | ||
|
||
impl<T: Clone> MutGlobal<T> { | ||
/// Create a new `MutGlobal` with no value set. | ||
pub const fn new(default_fn: fn() -> T) -> Self { | ||
Self { value: Mutex::new(None), default_fn } | ||
} | ||
|
||
/// Set the value of the global variable. | ||
/// | ||
/// Ignores any attempt to set the value more than once. | ||
pub fn set(&self, value: T) { | ||
let mut lock = self.value.lock().unwrap(); | ||
*lock = Some(value); | ||
} | ||
|
||
/// Get the value of the global variable. | ||
/// | ||
/// # Panics | ||
/// | ||
/// Panics if the value has not been set. | ||
pub fn get(&self) -> T { | ||
let mut lock = self.value.lock().unwrap(); | ||
if let Some(value) = &*lock { | ||
value.clone() | ||
} else { | ||
let value = (self.default_fn)(); | ||
*lock = Some(value.clone()); | ||
value | ||
} | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
#[test] | ||
fn test() { | ||
let v = MutGlobal::<u8>::new(|| 0); | ||
assert_eq!(v.get(), 0); | ||
v.set(42); | ||
assert_eq!(v.get(), 42); | ||
v.set(43); | ||
assert_eq!(v.get(), 43); | ||
} | ||
|
||
static G: MutGlobal<u8> = MutGlobal::new(|| 0); | ||
|
||
#[test] | ||
fn test_global() { | ||
G.set(42); | ||
assert_eq!(G.get(), 42); | ||
G.set(43); | ||
assert_eq!(G.get(), 43); | ||
} | ||
} |