Skip to content

Commit 50309d0

Browse files
committed
Make Once::new a const function
This fixes #2.
1 parent 8132175 commit 50309d0

File tree

1 file changed

+19
-5
lines changed

1 file changed

+19
-5
lines changed

src/lib.rs

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -558,18 +558,23 @@ impl Drop for GroupGuard {
558558
}
559559
}
560560

561-
#[allow(dead_code)]
562-
struct Once {
561+
/// A predicate used to execute a closure only once for the lifetime of an
562+
/// application.
563+
pub struct Once {
563564
predicate: UnsafeCell<dispatch_once_t>,
564565
}
565566

566-
#[allow(dead_code)]
567567
impl Once {
568-
// TODO: make this a const fn when the feature is stable
569-
pub fn new() -> Once {
568+
/// Creates a new `Once`.
569+
pub const fn new() -> Once {
570570
Once { predicate: UnsafeCell::new(0) }
571571
}
572572

573+
/// Executes a closure once, ensuring that no other closure has been or
574+
/// will be executed by self for the lifetype of the application.
575+
///
576+
/// If called simultaneously from multiple threads, waits synchronously
577+
// until the work has completed.
573578
#[inline(always)]
574579
pub fn call_once<F>(&'static self, work: F) where F: FnOnce() {
575580
#[cold]
@@ -799,4 +804,13 @@ mod tests {
799804
// The notify must have run after the two blocks of the group
800805
assert_eq!(*num.lock().unwrap(), 10);
801806
}
807+
808+
#[test]
809+
fn test_once() {
810+
static ONCE: Once = Once::new();
811+
let mut num = 0;
812+
ONCE.call_once(|| num += 1);
813+
ONCE.call_once(|| num += 1);
814+
assert!(num == 1);
815+
}
802816
}

0 commit comments

Comments
 (0)