sketchbook 0.0.2

Interactive visual applications in Rust
Documentation
//! Real number conversion trait.

use core::ops::*;

/// Convert to real number.
///
/// This conversion preserves sign and will not fail.
/// The resulting value is a closest approximation of the input value.
/// This trait has the same behavior as the `as` operator.
/// ```
/// # use sketchbook::ToReal;
/// let x: i64 = 123;
/// let y: f32 = x.to_real();
/// assert_eq!(y, 123.0);
/// ```
pub trait ToReal<T> {
    /// Convert to real number.
    fn to_real(self) -> T;
}

macro_rules! impl_to_real {
    [$($num:ident),*] => {
        $(impl ToReal<f32> for $num {
            fn to_real(self) -> f32 {
                #![allow(trivial_numeric_casts)]
                self as f32
            }
        })*
        $(impl ToReal<f32> for &$num {
            fn to_real(self) -> f32 {
                #![allow(trivial_numeric_casts)]
                *self as f32
            }
        })*
        $(impl ToReal<f32> for &mut $num {
            fn to_real(self) -> f32 {
                #![allow(trivial_numeric_casts)]
                *self as f32
            }
        })*
        $(impl ToReal<f64> for $num {
            fn to_real(self) -> f64 {
                #![allow(trivial_numeric_casts)]
                self as f64
            }
        })*
        $(impl ToReal<f64> for &$num {
            fn to_real(self) -> f64 {
                #![allow(trivial_numeric_casts)]
                *self as f64
            }
        })*
        $(impl ToReal<f64> for &mut $num {
            fn to_real(self) -> f64 {
                #![allow(trivial_numeric_casts)]
                *self as f64
            }
        })*
    }
}

impl_to_real![f32, f64, u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, usize, isize];

/// Trait for real numbers.
pub trait Real: Add<Output = Self> + Sub<Output = Self> + Copy + Sized {
    /// Multiply the number by `2`.
    fn mul2(self) -> Self;

    /// Divide the number by `2`.
    fn div2(self) -> Self;
    
    /// Get the zero value for the type.
    fn zero() -> Self;
}

impl Real for f32 {
    fn mul2(self) -> Self {
        self * 2.0
    }

    fn div2(self) -> Self {
        self / 2.0
    }

    fn zero() -> Self {
        0.0
    }
}

impl Real for f64 {
    fn mul2(self) -> Self {
        self * 2.0
    }

    fn div2(self) -> Self {
        self / 2.0
    }

    fn zero() -> Self {
        0.0
    }
}