Skip to content

Commit 1c0625d

Browse files
committed
mut-global utility
1 parent f302e2e commit 1c0625d

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed

lightning/Cargo.toml

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

5151
core2 = { version = "0.3.0", optional = true, default-features = false }
5252
libm = { version = "0.2", optional = true, default-features = false }
53+
delegate = "0.12.0"
5354

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

lightning/src/util/mod.rs

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

18+
pub mod dyn_signer;
19+
20+
#[cfg(feature = "std")]
21+
pub mod mut_global;
22+
1823
pub mod errors;
1924
pub mod ser;
2025
pub mod message_signing;

lightning/src/util/mut_global.rs

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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+
}
11+
12+
impl<T: Clone> MutGlobal<T> {
13+
/// Create a new `MutGlobal` with no value set.
14+
pub const fn new() -> Self {
15+
Self {
16+
value: Mutex::new(None),
17+
}
18+
}
19+
20+
/// Set the value of the global variable.
21+
///
22+
/// Ignores any attempt to set the value more than once.
23+
pub fn set(&self, value: T) {
24+
let mut lock = self.value.lock().unwrap();
25+
*lock = Some(value);
26+
}
27+
28+
/// Get the value of the global variable.
29+
///
30+
/// # Panics
31+
///
32+
/// Panics if the value has not been set.
33+
pub fn get(&self) -> T {
34+
self.value
35+
.lock()
36+
.unwrap()
37+
.clone()
38+
.expect("not set")
39+
}
40+
41+
/// Whether a value was set
42+
pub fn is_set(&self) -> bool {
43+
self.value.lock().unwrap().is_some()
44+
}
45+
}
46+
47+
#[cfg(test)]
48+
mod tests {
49+
use super::*;
50+
51+
#[test]
52+
fn test() {
53+
let v = MutGlobal::<u8>::new();
54+
assert!(!v.is_set());
55+
v.set(42);
56+
assert_eq!(v.get(), 42);
57+
v.set(43);
58+
assert_eq!(v.get(), 43);
59+
}
60+
61+
static G: MutGlobal<u8> = MutGlobal::new();
62+
63+
#[test]
64+
fn test_global() {
65+
assert!(!G.is_set());
66+
G.set(42);
67+
assert_eq!(G.get(), 42);
68+
G.set(43);
69+
assert_eq!(G.get(), 43);
70+
}
71+
}

0 commit comments

Comments
 (0)