Skip to content

Instantly share code, notes, and snippets.

@durka
Forked from anonymous/playground.rs
Last active October 1, 2015 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save durka/1b5bfdef2995b3b67bb0 to your computer and use it in GitHub Desktop.
Save durka/1b5bfdef2995b3b67bb0 to your computer and use it in GitHub Desktop.
Signaling-NaN simulator wrapper for f32/f64
#[cfg(debug_assertions)] use std::ops::*;
#[cfg(debug_assertions)] use std::{f32, f64, fmt};
#[cfg(debug_assertions)]
#[derive(Copy, Clone, Debug)]
struct Signaling<T>(T);
#[cfg(debug_assertions)]
impl<T: fmt::Display> fmt::Display for Signaling<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[cfg(debug_assertions)]
impl<T: fmt::Debug> fmt::Debug for Signaling<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.0)
}
}
macro_rules! checking_impl {
($t:ident, $trate:ident, $func:ident) => {
#[cfg(debug_assertions)]
impl $trate for Signaling<$t> {
type Output = Self;
fn $func(self, rhs: Self) -> Self {
let res = (self.0).$func(rhs.0);
if $t::is_nan(res) {
panic!("NaN");
} else {
Signaling(res)
}
}
}
}
}
macro_rules! impl_ops {
($t:ident) => {
checking_impl!($t, Add, add);
checking_impl!($t, Sub, sub);
checking_impl!($t, Mul, mul);
checking_impl!($t, Div, div);
checking_impl!($t, Rem, rem);
}
}
impl_ops!(f32);
impl_ops!(f64);
#[cfg(not(debug_assertions))]
#[inline(always)]
#[allow(non_snake_case)]
fn Signaling<T>(t: T) -> T { t }
fn main() {
println!("{:?}", Signaling(1.0) / Signaling(2.0));
println!("{:?}", Signaling(0.0) / Signaling(0.0));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment