Skip to content

Commit c1c9c26

Browse files
committed
mut-global utility
1 parent f514404 commit c1c9c26

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

0 commit comments

Comments
 (0)