Skip to content

Commit 7754bbb

Browse files
committed
mut-global utility
1 parent dbd6513 commit 7754bbb

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

lightning/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ regex = { version = "1.5.6", optional = true }
4949
backtrace = { version = "0.3", optional = true }
5050

5151
libm = { version = "0.2", default-features = false }
52+
delegate = "0.12.0"
5253

5354
[dev-dependencies]
5455
regex = "1.5.6"

lightning/src/util/mod.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ pub(crate) mod fuzz_wrappers;
1515
#[macro_use]
1616
pub mod ser_macros;
1717

18+
#[cfg(feature = "std")]
19+
pub mod mut_global;
20+
1821
pub mod errors;
1922
pub mod ser;
2023
pub mod message_signing;

lightning/src/util/mut_global.rs

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
//! A settable global variable.
2+
//!
3+
//! Used for testing purposes only.
4+
5+
use std::sync::Mutex;
6+
7+
/// A global variable that can be set exactly once.
8+
pub struct MutGlobal<T> {
9+
value: Mutex<Option<T>>,
10+
default_fn: fn() -> T,
11+
}
12+
13+
impl<T: Clone> MutGlobal<T> {
14+
/// Create a new `MutGlobal` with no value set.
15+
pub const fn new(default_fn: fn() -> T) -> Self {
16+
Self { value: Mutex::new(None), default_fn }
17+
}
18+
19+
/// Set the value of the global variable.
20+
///
21+
/// Ignores any attempt to set the value more than once.
22+
pub fn set(&self, value: T) {
23+
let mut lock = self.value.lock().unwrap();
24+
*lock = Some(value);
25+
}
26+
27+
/// Get the value of the global variable.
28+
///
29+
/// # Panics
30+
///
31+
/// Panics if the value has not been set.
32+
pub fn get(&self) -> T {
33+
let mut lock = self.value.lock().unwrap();
34+
if let Some(value) = &*lock {
35+
value.clone()
36+
} else {
37+
let value = (self.default_fn)();
38+
*lock = Some(value.clone());
39+
value
40+
}
41+
}
42+
}
43+
44+
#[cfg(test)]
45+
mod tests {
46+
use super::*;
47+
48+
#[test]
49+
fn test() {
50+
let v = MutGlobal::<u8>::new(|| 0);
51+
assert_eq!(v.get(), 0);
52+
v.set(42);
53+
assert_eq!(v.get(), 42);
54+
v.set(43);
55+
assert_eq!(v.get(), 43);
56+
}
57+
58+
static G: MutGlobal<u8> = MutGlobal::new(|| 0);
59+
60+
#[test]
61+
fn test_global() {
62+
G.set(42);
63+
assert_eq!(G.get(), 42);
64+
G.set(43);
65+
assert_eq!(G.get(), 43);
66+
}
67+
}

0 commit comments

Comments
 (0)