use std::{
fmt,
ops::Not,
};
use {
super::Tester,
crate::{
internal::CallbackMetadata,
macros::{
impl_common_name_methods,
impl_common_new_methods,
},
},
};
#[must_use = "callback wrappers do nothing unless stored or invoked"]
pub struct BoxTester {
pub(super) function: Box<dyn Fn() -> bool>,
pub(super) metadata: CallbackMetadata,
}
impl BoxTester {
impl_common_new_methods!(
semantic(Tester + 'static),
|source| move || source.test(),
|function| Box::new(function),
"tester"
);
impl_common_name_methods!("tester");
#[inline]
pub fn and<T>(self, next: T) -> BoxTester
where
T: Tester + 'static,
{
let self_fn = self.function;
let next_tester = next;
BoxTester::new(move || self_fn() && next_tester.test())
}
#[inline]
pub fn or<T>(self, next: T) -> BoxTester
where
T: Tester + 'static,
{
let self_fn = self.function;
let next_tester = next;
BoxTester::new(move || self_fn() || next_tester.test())
}
#[inline]
pub fn nand<T>(self, next: T) -> BoxTester
where
T: Tester + 'static,
{
let self_fn = self.function;
let next_tester = next;
BoxTester::new(move || !(self_fn() && next_tester.test()))
}
#[inline]
pub fn xor<T>(self, next: T) -> BoxTester
where
T: Tester + 'static,
{
let self_fn = self.function;
let next_tester = next;
BoxTester::new(move || self_fn() ^ next_tester.test())
}
#[inline]
pub fn nor<T>(self, next: T) -> BoxTester
where
T: Tester + 'static,
{
let self_fn = self.function;
let next_tester = next;
BoxTester::new(move || !(self_fn() || next_tester.test()))
}
}
impl Not for BoxTester {
type Output = BoxTester;
#[inline]
fn not(self) -> Self::Output {
let metadata = self.metadata;
let self_fn = self.function;
BoxTester::new_with_metadata(move || !self_fn(), metadata)
}
}
impl Tester for BoxTester {
#[inline(always)]
fn test(&self) -> bool {
(self.function)()
}
}
impl fmt::Debug for BoxTester {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("BoxTester")
.field("name", &self.metadata.name())
.finish()
}
}
impl fmt::Display for BoxTester {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.metadata.name() {
Some(name) => write!(formatter, "BoxTester({name})"),
None => formatter.write_str("BoxTester"),
}
}
}