forked from shardus/lib-net
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: better singleton pattern for SHARDUS_CRYPTO_INSTANCE
This commit discharge the use of static mut to be able to compile with rust 1.77
- Loading branch information
Showing
1 changed file
with
11 additions
and
21 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,32 +1,22 @@ | ||
use crypto::ShardusCrypto; | ||
use std::sync::Once; | ||
use crypto::ShardusCrypto; | ||
use once_cell::sync::OnceCell; | ||
|
||
static SHARDUS_CRYPTO_INSTANCE: OnceCell<ShardusCrypto> = OnceCell::new(); | ||
static INIT: Once = Once::new(); | ||
|
||
// TODO figure out optimal way to lock mutability of this static as soon as it's initialized once. | ||
// - Mutex locks both read write access, will lock out all threads that want to read? #BAD | ||
// - Can we use RwLock? | ||
static mut SHARDUS_CRYPTO_INSTANCE: Option<ShardusCrypto> = None; | ||
|
||
// Initialize the ShardusCrypto instance exactly once | ||
pub fn initialize_shardus_crypto_instance(hex_key: &str) { | ||
INIT.call_once(|| match unsafe { &SHARDUS_CRYPTO_INSTANCE } { | ||
Some(_) => { | ||
panic!("ShardusCrypto instance already initialized"); | ||
} | ||
None => { | ||
let crypto = ShardusCrypto::new(hex_key); | ||
unsafe { | ||
SHARDUS_CRYPTO_INSTANCE = Some(crypto); | ||
} | ||
INIT.call_once(|| { | ||
let crypto = ShardusCrypto::new(hex_key); | ||
// Attempt to set the OnceCell, which should never fail since it's guarded by `INIT.call_once()` | ||
if SHARDUS_CRYPTO_INSTANCE.set(crypto).is_err() { | ||
panic!("ShardusCrypto instance has already been initialized, this should never happen"); | ||
} | ||
}); | ||
} | ||
|
||
// Get a reference to the initialized ShardusCrypto instance | ||
pub fn get_shardus_crypto_instance() -> &'static ShardusCrypto { | ||
unsafe { | ||
match &SHARDUS_CRYPTO_INSTANCE { | ||
Some(instance) => instance, | ||
None => panic!("ShardusCrypto instance not initialized"), | ||
} | ||
} | ||
SHARDUS_CRYPTO_INSTANCE.get().expect("ShardusCrypto instance not initialized") | ||
} |