rutil 0.2.0

A library containing utilities for creating programs in rust.
Documentation
/// Sign operations.
pub trait SignOps {
    /// Computes the absolute value of `self`.
    fn abs(self) -> Self;

    /// Computes the absolute difference between `self` and `other`.
    fn abs_diff(self, other: Self) -> Self;

    /// Returns a number representing sign of `self`.
    ///
    ///  - `0` if the number is zero
    ///  - `1` if the number is positive
    ///  - `-1` if the number is negative
    fn signum(self) -> Self;

    /// Returns `true` if `self` is positive and `false` if the number is zero or negative.
    fn is_positive(self) -> bool;

    /// Returns `true` if `self` is negative and `false` if the number is zero or positive.
    fn is_negative(self) -> bool;
}

/// Implements [`SignOps`] for unsigned integers.
macro_rules! impl_sign_uint {
    ($($t:ty),*) => {
        $(impl SignOps for $t {
            #[inline] fn abs(self) -> Self { self }
            #[inline] fn abs_diff(self, other: Self) -> Self { self.abs_diff(other) }
            #[inline] fn signum(self) -> Self { if self == 0 { 0 } else { 1 } }
            #[inline] fn is_positive(self) -> bool { self != 0 }
            #[inline] fn is_negative(self) -> bool { false }
        })*
    };
}

impl_sign_uint!(u8, u16, u32, u64, u128, usize);

/// Implements [`SignOps`] for signed integers.
macro_rules! impl_sign_int {
    ($($t:ty),*) => {
        $(impl SignOps for $t {
            #[inline] fn abs(self) -> Self { self.abs() }
            #[inline] fn signum(self) -> Self { self.signum() }
            #[inline] fn is_positive(self) -> bool { self.is_positive() }
            #[inline] fn is_negative(self) -> bool { self.is_negative() }

            #[inline]
            fn abs_diff(self, other: Self) -> Self {
                if self < other {
                    other - self
                } else {
                    self - other
                }
            }
        })*
    };
}

impl_sign_int!(i8, i16, i32, i64, i128, isize);

/// Implements [`SignOps`] for floats.
macro_rules! impl_sign_float {
    ($($t:ty),*) => {
        $(impl SignOps for $t {
            #[inline] fn abs(self) -> Self { self.abs() }
            #[inline] fn signum(self) -> Self { self.signum() }
            #[inline] fn is_positive(self) -> bool { self.is_sign_positive() }
            #[inline] fn is_negative(self) -> bool { self.is_sign_negative() }

            #[inline]
            fn abs_diff(self, other: Self) -> Self {
                if self < other {
                    other - self
                } else {
                    self - other
                }
            }
        })*
    };
}

impl_sign_float!(f32, f64);