use core::ops::Neg;
use crate::element::Element;
use crate::element::element_kind::ElementKind;
use crate::log_compute_step;
impl Neg for Element {
type Output = Self;
fn neg(self) -> Self {
let kind = match self.kind {
ElementKind::Known(val) => ElementKind::Known(-val),
ElementKind::Variable {
factor,
unknown,
offset,
} => ElementKind::Variable {
factor: -factor,
unknown,
offset: -offset,
},
ElementKind::Transformed {
factor,
transform,
inner,
offset,
} => ElementKind::Transformed {
factor: -factor,
transform,
inner,
offset: -offset,
},
};
let res = Self {
kind,
error: self.error,
};
log_compute_step!("Step: -({res})");
res
}
}
impl Neg for &Element {
type Output = Element;
fn neg(self) -> Element {
-self.clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[allow(unused_imports)]
use alloc::format;
use alloc::rc::Rc;
#[allow(unused_imports)]
use alloc::string::ToString;
use core::cell::RefCell;
#[test]
fn test_neg_known() {
let element = Element::known(3.0);
let neg = -element;
assert_eq!(neg.value(), Some(-3.0));
}
#[test]
fn test_neg_variable() {
let rc = Rc::new(RefCell::new(0.0));
let x = Element::new_unknown(rc);
let expr = x + 3.0;
let neg = -expr;
assert_eq!(format!("{neg}"), "-x - 3");
}
#[test]
fn test_neg_double_negation() {
let element = Element::known(42.0);
assert_eq!(-(-element), Element::known(42.0));
}
}