tmac 0.1.3

Macros that help with testing, e.g. asserting float equality
Documentation
/// Asserts the equality of two floats within the float types epsilon.
///
/// ```rs
/// assert_ne!(0.2f64 * 3.0, 0.6);
/// assert_float_eq(0.2f64 * 3.0, 0.6);
/// assert_ne!(0.3f32 * 3.0, 0.9);
/// assert_float_eq(0.3f32 * 3.0, 0.9);
/// ```
#[inline(always)]
pub fn assert_float_eq_fn<T: num::Float>(a: T, b: T) {
    assert!(a < b + T::epsilon());
    assert!(a > b - T::epsilon());
}

/// Macro version for asserting float equality.
#[macro_export]
macro_rules! assert_float_eq {
    ($a:expr, $b:expr) => {
        tmac::assert_float_eq_fn($a, $b);
    };
}

// function unfortunately needed so that the user doesn't need to specify the
// type of float for getting the epsilon
/// Asserts the inequality of two floats with regard to the float types epsilon.
///
/// ```rs
/// assert_float_ne(0.2f64 * 3.0, 0.600000000000001);
/// assert_float_ne(0.3f32 * 3.0, 0.9000002);
/// ```
pub fn assert_float_ne_fn<T: num::Float + std::fmt::Debug>(a: T, b: T) {
    assert_ne!(a, b);
    if a > b {
        assert!(a > b + T::epsilon())
    } else {
        assert!(a < b - T::epsilon())
    }
}

/// Macro version for asserting float inequality.
#[macro_export]
macro_rules! assert_float_ne {
    ($a:expr, $b:expr) => {
        tmac::assert_float_ne_fn($a, $b);
    };
}

#[cfg(test)]
mod tests {
    use crate as tmac;

    #[test]
    fn assert_float_eq_accepts() {
        assert_ne!(0.2f64 * 3.0, 0.6);
        assert_float_eq!(0.2f64 * 3.0, 0.6);
        assert_ne!(0.3f32 * 3.0, 0.9);
        assert_float_eq!(0.3f32 * 3.0, 0.9);
    }

    #[test]
    #[should_panic]
    fn assert_float_eq_rejects() {
        assert_float_eq!(0.2f64 * 3.0, 0.600000000000001f64);
        assert_float_eq!(0.3f32 * 3.0, 0.9000002);
    }

    #[test]
    fn assert_float_ne_accepts() {
        assert_float_ne!(0.2f64 * 3.0, 0.600000000000001);
        assert_float_ne!(0.3f32 * 3.0, 0.9000002);
    }

    #[test]
    #[should_panic]
    fn assert_float_ne_rejects() {
        assert_float_ne!(0.2f64 * 3.0, 0.6);
        assert_float_ne!(0.3f32 * 3.0, 0.9);
    }
}