Last active
February 24, 2023 20:13
-
-
Save orez-/70b1f3d75cfeeb6948da50874b41dc66 to your computer and use it in GitHub Desktop.
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
// https://stackoverflow.com/a/39647997/1163020 | |
// probably unsuitable for production. | |
use std::hash; | |
#[derive(Debug, Copy, Clone, PartialOrd)] | |
pub struct NormalF64(f64); | |
impl NormalF64 { | |
pub fn new(n: f64) -> Option<Self> { | |
if n == 0.0 { return Some(Self(0.0)); } | |
n.is_normal().then(|| Self(n)) | |
} | |
pub fn new_unchecked(n: f64) -> Self { | |
Self::new(n).expect("value is not normal") | |
} | |
fn key(&self) -> u64 { | |
self.0.to_bits() | |
} | |
} | |
impl hash::Hash for NormalF64 { | |
fn hash<H>(&self, state: &mut H) | |
where H: hash::Hasher { | |
self.key().hash(state) | |
} | |
} | |
impl PartialEq for NormalF64 { | |
fn eq(&self, other: &NormalF64) -> bool { | |
self.key() == other.key() | |
} | |
} | |
impl Eq for NormalF64 {} | |
impl Ord for NormalF64 { | |
fn cmp(&self, other: &Self) -> std::cmp::Ordering { | |
self.partial_cmp(other) | |
.expect("normal f64 should be total orderable") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment