Skip to content

Commit

Permalink
Add call_once, make init_once possible to panic
Browse files Browse the repository at this point in the history
  • Loading branch information
equation314 committed Jul 25, 2024
1 parent 09de84e commit 69f8924
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ assert!(!VALUE.is_inited());
assert_eq!(VALUE.get(), None);

VALUE.init_once(233);
// VALUE.init_by(666); // panic: already initialized
// VALUE.init_once(666); // panic: already initialized
assert!(VALUE.is_inited());
assert_eq!(*VALUE, 233);
assert_eq!(VALUE.get(), Some(&233));
Expand All @@ -40,7 +40,7 @@ let threads = (0..N)
.map(|i| {
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(10));
VALUE.init_once(i)
VALUE.call_once(|| i)
})
})
.collect::<Vec<_>>();
Expand Down
26 changes: 24 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,36 @@ impl<T> LazyInit<T> {

/// Initializes the value once and only once.
///
/// Returns [`None`] if the value is already initialized.
pub fn init_once(&self, data: T) -> Option<&T> {
/// # Panics
///
/// Panics if the value is already initialized.
pub fn init_once(&self, data: T) -> &T {
match self
.inited
.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
{
Ok(_) => {
unsafe { (*self.data.get()).as_mut_ptr().write(data) };
unsafe { self.force_get() }
}
Err(_) => panic!("Already initialized"),
}
}

/// Performs an initialization routine once and only once.
///
/// If the value is already initialized, the function will not be called
/// and a [`None`] will be returned.
pub fn call_once<F>(&self, f: F) -> Option<&T>
where
F: FnOnce() -> T,
{
match self
.inited
.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
{
Ok(_) => {
unsafe { (*self.data.get()).as_mut_ptr().write(f()) };
Some(unsafe { self.force_get() })
}
Err(_) => None,
Expand Down

0 comments on commit 69f8924

Please sign in to comment.