#[macro_use]
extern crate lazy_static;
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
#[derive(Clone)]
pub struct Behold {
context: Arc<Mutex<BTreeMap<String, bool>>>,
speak_up: bool,
tag: Option<String>,
}
impl Behold {
pub fn new() -> Self {
BEHOLD.clone()
}
pub fn set_context(&self, key: &str, value: bool) {
let context = (*self.context).lock();
if let Ok(mut context) = context {
(*context).insert(key.to_string(), value);
} else if let Err(err) = context {
panic!(
"when_context called on an instance of Behold - mutex already acquired - {:?}!",
err
);
}
}
pub fn tag(&self, tag: &str) -> Self {
Behold {
context: self.context.clone(),
speak_up: self.speak_up,
tag: Some(tag.to_string()),
}
}
pub fn when(&self, speak_up: bool) -> Self {
Behold {
context: self.context.clone(),
speak_up: speak_up,
tag: self.tag.clone(),
}
}
pub fn when_context(&self, key: &str) -> Self {
let speak_up = match (*self.context).lock() {
Ok(context) => (*context).get(&key.to_string()).cloned().unwrap_or_default(),
Err(err) => {
panic!(
"when_context called on an instance of Behold - mutex already acquired - {:?}!",
err
);
}
};
Behold {
context: self.context.clone(),
speak_up: speak_up,
tag: self.tag.clone(),
}
}
pub fn show(&self, msg: String) {
if self.speak_up {
if let Some(ref tag) = self.tag {
println!("{}, {}", msg, tag);
} else {
println!("{}", msg);
}
}
}
pub fn call(&self, f: &Fn()) {
if self.speak_up {
f()
}
}
}
pub fn behold() -> Behold {
Behold::new()
}
lazy_static! {
static ref BEHOLD: Behold = {
Behold {
context: Arc::new(Mutex::new(BTreeMap::new())),
speak_up: true,
tag: None,
}
};
}
#[cfg(test)]
include!(concat!(env!("OUT_DIR"), "/skeptic-tests.rs"));