Skip to content

Instantly share code, notes, and snippets.

Created January 17, 2017 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/ffb855c248d80595fccee131f24ef1d6 to your computer and use it in GitHub Desktop.
Save anonymous/ffb855c248d80595fccee131f24ef1d6 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
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