Browse Source

+lib/once: a little library to make sure stuff only gets called once

master
3moon 8 years ago
parent
commit
8ebf1a2f28
3 changed files with 55 additions and 0 deletions
  1. +4
    -0
      lib/once/Cargo.lock
  2. +6
    -0
      lib/once/Cargo.toml
  3. +45
    -0
      lib/once/src/lib.rs

+ 4
- 0
lib/once/Cargo.lock View File

@ -0,0 +1,4 @@
[root]
name = "once"
version = "0.1.0"

+ 6
- 0
lib/once/Cargo.toml View File

@ -0,0 +1,6 @@
[package]
name = "once"
version = "0.1.0"
authors = ["Erin <erin@hashbang.sh>"]
[dependencies]

+ 45
- 0
lib/once/src/lib.rs View File

@ -0,0 +1,45 @@
#![no_std]
#[cfg(test)]
extern crate std;
#[macro_export]
macro_rules! assert_first_call {
() => {
assert_first_call!("assertion failed: function called more than once");
};
($($arg:tt)+) => {{
use ::core::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
static CALLED: AtomicBool = ATOMIC_BOOL_INIT;
let called = CALLED.swap(true, Ordering::Relaxed);
assert!(called == false, $($arg)+);
}};
}
#[test]
fn test_run_once() {
fn once() {
assert_first_call!();
}
once();
}
#[test]
fn test_run_once_two_funcs() {
fn once1() {assert_first_call!();}
fn once2() {assert_first_call!();}
once1(); once2();
}
#[test]
#[should_panic]
fn test_run_twice() {
fn once() {
assert_first_call!();
}
once(); once();
}

Loading…
Cancel
Save