-
-
Save shterrett/90f4d429ff165a266b2f1a0187ed9065 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://stackoverflow.com/a/39639200 | |
use std::mem; | |
use std::hash::{Hash, Hasher}; | |
use std::collections::HashSet; | |
use std::fmt; | |
fn integer_decode(val: f64) -> (u64, i16, i8) { | |
let bits: u64 = unsafe { mem::transmute(val) }; | |
let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 }; | |
let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16; | |
let mantissa = if exponent == 0 { | |
(bits & 0xfffffffffffff) << 1 | |
} else { | |
(bits & 0xfffffffffffff) | 0x10000000000000 | |
}; | |
exponent -= 1023 + 52; | |
(mantissa, exponent, sign) | |
} | |
#[derive(Debug)] | |
struct Point { | |
x: f64, | |
y: f64, | |
} | |
impl PartialEq for Point { | |
fn eq(&self, other: &Point) -> bool { | |
self.x == other.x && self.y == other.y | |
} | |
} | |
impl Eq for Point {} | |
impl Hash for Point { | |
fn hash<H: Hasher>(&self, state: &mut H) { | |
let x = integer_decode(self.x); | |
let y = integer_decode(self.y); | |
x.hash(state); | |
y.hash(state) | |
} | |
} | |
impl fmt::Display for Point { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
write!(f, "(x: {}, y: {})", self.x, self.y) | |
} | |
} | |
fn main() { | |
let mut test = HashSet::new(); | |
let point = Point { x: 3.5, y: 5.5 }; | |
test.insert(point); | |
println!("{:?}", test); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment