Skip to content

Add IterBytes impls for float/f32/f64. This allows creating HashMaps with floats as keys. #7156

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/libstd/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -558,4 +558,15 @@ mod tests {
val & !(0xff << (byte * 8))
}
}

#[test]
fn test_float_hashes_differ() {
assert!(0.0.hash() != 1.0.hash());
assert!(1.0.hash() != (-1.0).hash());
}

#[test]
fn test_float_hashes_of_zero() {
assert_eq!(0.0.hash(), (-0.0).hash());
}
}
30 changes: 30 additions & 0 deletions src/libstd/to_bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ The `ToBytes` and `IterBytes` traits

*/

use cast;
use io;
use io::Writer;
use option::{None, Option, Some};
Expand Down Expand Up @@ -190,6 +191,35 @@ impl IterBytes for int {
}
}

impl IterBytes for float {
#[inline(always)]
fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool {
(*self as f64).iter_bytes(lsb0, f)
}
}

impl IterBytes for f32 {
#[inline(always)]
fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool {
let i: u32 = unsafe {
// 0.0 == -0.0 so they should also have the same hashcode
cast::transmute(if *self == -0.0 { 0.0 } else { *self })
};
i.iter_bytes(lsb0, f)
}
}

impl IterBytes for f64 {
#[inline(always)]
fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool {
let i: u64 = unsafe {
// 0.0 == -0.0 so they should also have the same hashcode
cast::transmute(if *self == -0.0 { 0.0 } else { *self })
};
i.iter_bytes(lsb0, f)
}
}

impl<'self,A:IterBytes> IterBytes for &'self [A] {
#[inline(always)]
fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool {
Expand Down