1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use std::cmp::Ordering;
13 use std::mem::transmute;
17 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
22 pub use self::ConstFloat::*;
25 /// Description of the type, not the value
26 pub fn description(&self) -> &'static str {
33 pub fn is_nan(&self) -> bool {
40 /// Compares the values if they are of the same type
41 pub fn try_cmp(self, rhs: Self) -> Result<Ordering, ConstMathErr> {
44 // This is pretty bad but it is the existing behavior.
64 _ => Err(CmpBetweenUnequalTypes),
69 /// Note that equality for `ConstFloat` means that the it is the same
70 /// constant, not that the rust values are equal. In particular, `NaN
71 /// == NaN` (at least if it's the same NaN; distinct encodings for NaN
72 /// are considering unequal).
73 impl PartialEq for ConstFloat {
74 fn eq(&self, other: &Self) -> bool {
75 match (*self, *other) {
77 unsafe{transmute::<_,u64>(a) == transmute::<_,u64>(b)}
80 unsafe{transmute::<_,u32>(a) == transmute::<_,u32>(b)}
87 impl Eq for ConstFloat {}
89 impl hash::Hash for ConstFloat {
90 fn hash<H: hash::Hasher>(&self, state: &mut H) {
93 unsafe { transmute::<_,u64>(a) }.hash(state)
96 unsafe { transmute::<_,u32>(a) }.hash(state)
102 impl ::std::fmt::Display for ConstFloat {
103 fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
105 F32(f) => write!(fmt, "{}f32", f),
106 F64(f) => write!(fmt, "{}f64", f),
111 macro_rules! derive_binop {
112 ($op:ident, $func:ident) => {
113 impl ::std::ops::$op for ConstFloat {
114 type Output = Result<Self, ConstMathErr>;
115 fn $func(self, rhs: Self) -> Result<Self, ConstMathErr> {
117 (F32(a), F32(b)) => Ok(F32(a.$func(b))),
118 (F64(a), F64(b)) => Ok(F64(a.$func(b))),
119 _ => Err(UnequalTypes(Op::$op)),
126 derive_binop!(Add, add);
127 derive_binop!(Sub, sub);
128 derive_binop!(Mul, mul);
129 derive_binop!(Div, div);
130 derive_binop!(Rem, rem);
132 impl ::std::ops::Neg for ConstFloat {
134 fn neg(self) -> Self {