| 1 |
#![no_std] |
| 2 |
#![cfg_attr(test, deny(warnings))] |
| 3 |
#![deny(missing_docs)] |
| 4 |
#![allow(clippy::derive_partial_eq_without_eq)] |
| 5 |
|
| 6 |
//! Wrappers for total order on Floats. See the [`OrderedFloat`] and [`NotNan`] docs for details. |
| 7 |
|
| 8 |
#[cfg(feature = "std")] |
| 9 |
extern crate std; |
| 10 |
#[cfg(feature = "std")] |
| 11 |
use std::error::Error; |
| 12 |
|
| 13 |
use core::borrow::Borrow; |
| 14 |
use core::cmp::Ordering; |
| 15 |
use core::convert::TryFrom; |
| 16 |
use core::fmt; |
| 17 |
use core::hash::{Hash, Hasher}; |
| 18 |
use core::hint::unreachable_unchecked; |
| 19 |
use core::iter::{Product, Sum}; |
| 20 |
use core::num::FpCategory; |
| 21 |
use core::ops::{ |
| 22 |
Add, AddAssign, Deref, DerefMut, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, |
| 23 |
SubAssign, |
| 24 |
}; |
| 25 |
use core::str::FromStr; |
| 26 |
|
| 27 |
#[cfg(not(feature = "std"))] |
| 28 |
use num_traits::float::FloatCore as Float; |
| 29 |
#[cfg(feature = "std")] |
| 30 |
pub use num_traits::Float; |
| 31 |
use num_traits::{ |
| 32 |
AsPrimitive, Bounded, FromPrimitive, Num, NumCast, One, Signed, ToPrimitive, Zero, |
| 33 |
}; |
| 34 |
|
| 35 |
// masks for the parts of the IEEE 754 float |
| 36 |
const SIGN_MASK: u64 = 0x8000000000000000u64; |
| 37 |
const EXP_MASK: u64 = 0x7ff0000000000000u64; |
| 38 |
const MAN_MASK: u64 = 0x000fffffffffffffu64; |
| 39 |
|
| 40 |
// canonical raw bit patterns (for hashing) |
| 41 |
const CANONICAL_NAN_BITS: u64 = 0x7ff8000000000000u64; |
| 42 |
const CANONICAL_ZERO_BITS: u64 = 0x0u64; |
| 43 |
|
| 44 |
/// A wrapper around floats providing implementations of `Eq`, `Ord`, and `Hash`. |
| 45 |
/// |
| 46 |
/// NaN is sorted as *greater* than all other values and *equal* |
| 47 |
/// to itself, in contradiction with the IEEE standard. |
| 48 |
/// |
| 49 |
/// ``` |
| 50 |
/// use ordered_float::OrderedFloat; |
| 51 |
/// use std::f32::NAN; |
| 52 |
/// |
| 53 |
/// let mut v = [OrderedFloat(NAN), OrderedFloat(2.0), OrderedFloat(1.0)]; |
| 54 |
/// v.sort(); |
| 55 |
/// assert_eq!(v, [OrderedFloat(1.0), OrderedFloat(2.0), OrderedFloat(NAN)]); |
| 56 |
/// ``` |
| 57 |
/// |
| 58 |
/// Because `OrderedFloat` implements `Ord` and `Eq`, it can be used as a key in a `HashSet`, |
| 59 |
/// `HashMap`, `BTreeMap`, or `BTreeSet` (unlike the primitive `f32` or `f64` types): |
| 60 |
/// |
| 61 |
/// ``` |
| 62 |
/// # use ordered_float::OrderedFloat; |
| 63 |
/// # use std::collections::HashSet; |
| 64 |
/// # use std::f32::NAN; |
| 65 |
/// |
| 66 |
/// let mut s: HashSet<OrderedFloat<f32>> = HashSet::new(); |
| 67 |
/// s.insert(OrderedFloat(NAN)); |
| 68 |
/// assert!(s.contains(&OrderedFloat(NAN))); |
| 69 |
/// ``` |
| 70 |
#[derive(Debug, Default, Clone, Copy)] |
| 71 |
#[repr(transparent)] |
| 72 |
pub struct OrderedFloat<T>(pub T); |
| 73 |
|
| 74 |
impl<T: Float> OrderedFloat<T> { |
| 75 |
/// Get the value out. |
| 76 |
#[inline] |
| 77 |
pub fn into_inner(self) -> T { |
| 78 |
self.0 |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
impl<T: Float> AsRef<T> for OrderedFloat<T> { |
| 83 |
#[inline] |
| 84 |
fn as_ref(&self) -> &T { |
| 85 |
&self.0 |
| 86 |
} |
| 87 |
} |
| 88 |
|
| 89 |
impl<T: Float> AsMut<T> for OrderedFloat<T> { |
| 90 |
#[inline] |
| 91 |
fn as_mut(&mut self) -> &mut T { |
| 92 |
&mut self.0 |
| 93 |
} |
| 94 |
} |
| 95 |
|
| 96 |
impl<'a, T: Float> From<&'a T> for &'a OrderedFloat<T> { |
| 97 |
#[inline] |
| 98 |
fn from(t: &'a T) -> &'a OrderedFloat<T> { |
| 99 |
// Safety: OrderedFloat is #[repr(transparent)] and has no invalid values. |
| 100 |
unsafe { &*(t as *const T as *const OrderedFloat<T>) } |
| 101 |
} |
| 102 |
} |
| 103 |
|
| 104 |
impl<'a, T: Float> From<&'a mut T> for &'a mut OrderedFloat<T> { |
| 105 |
#[inline] |
| 106 |
fn from(t: &'a mut T) -> &'a mut OrderedFloat<T> { |
| 107 |
// Safety: OrderedFloat is #[repr(transparent)] and has no invalid values. |
| 108 |
unsafe { &mut *(t as *mut T as *mut OrderedFloat<T>) } |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
impl<T: Float> PartialOrd for OrderedFloat<T> { |
| 113 |
#[inline] |
| 114 |
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { |
| 115 |
Some(self.cmp(other)) |
| 116 |
} |
| 117 |
} |
| 118 |
|
| 119 |
impl<T: Float> Ord for OrderedFloat<T> { |
| 120 |
fn cmp(&self, other: &Self) -> Ordering { |
| 121 |
let lhs = &self.0; |
| 122 |
let rhs = &other.0; |
| 123 |
match lhs.partial_cmp(rhs) { |
| 124 |
Some(ordering) => ordering, |
| 125 |
None => { |
| 126 |
if lhs.is_nan() { |
| 127 |
if rhs.is_nan() { |
| 128 |
Ordering::Equal |
| 129 |
} else { |
| 130 |
Ordering::Greater |
| 131 |
} |
| 132 |
} else { |
| 133 |
Ordering::Less |
| 134 |
} |
| 135 |
} |
| 136 |
} |
| 137 |
} |
| 138 |
} |
| 139 |
|
| 140 |
impl<T: Float> PartialEq for OrderedFloat<T> { |
| 141 |
#[inline] |
| 142 |
fn eq(&self, other: &OrderedFloat<T>) -> bool { |
| 143 |
if self.0.is_nan() { |
| 144 |
other.0.is_nan() |
| 145 |
} else { |
| 146 |
self.0 == other.0 |
| 147 |
} |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
impl<T: Float> PartialEq<T> for OrderedFloat<T> { |
| 152 |
#[inline] |
| 153 |
fn eq(&self, other: &T) -> bool { |
| 154 |
self.0 == *other |
| 155 |
} |
| 156 |
} |
| 157 |
|
| 158 |
impl<T: Float> Hash for OrderedFloat<T> { |
| 159 |
fn hash<H: Hasher>(&self, state: &mut H) { |
| 160 |
if self.is_nan() { |
| 161 |
// normalize to one representation of NaN |
| 162 |
hash_float(&T::nan(), state) |
| 163 |
} else { |
| 164 |
hash_float(&self.0, state) |
| 165 |
} |
| 166 |
} |
| 167 |
} |
| 168 |
|
| 169 |
impl<T: Float + fmt::Display> fmt::Display for OrderedFloat<T> { |
| 170 |
#[inline] |
| 171 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 172 |
self.0.fmt(f) |
| 173 |
} |
| 174 |
} |
| 175 |
|
| 176 |
impl<T: Float + fmt::LowerExp> fmt::LowerExp for OrderedFloat<T> { |
| 177 |
#[inline] |
| 178 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 179 |
self.0.fmt(f) |
| 180 |
} |
| 181 |
} |
| 182 |
|
| 183 |
impl<T: Float + fmt::UpperExp> fmt::UpperExp for OrderedFloat<T> { |
| 184 |
#[inline] |
| 185 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 186 |
self.0.fmt(f) |
| 187 |
} |
| 188 |
} |
| 189 |
|
| 190 |
impl From<OrderedFloat<f32>> for f32 { |
| 191 |
#[inline] |
| 192 |
fn from(f: OrderedFloat<f32>) -> f32 { |
| 193 |
f.0 |
| 194 |
} |
| 195 |
} |
| 196 |
|
| 197 |
impl From<OrderedFloat<f64>> for f64 { |
| 198 |
#[inline] |
| 199 |
fn from(f: OrderedFloat<f64>) -> f64 { |
| 200 |
f.0 |
| 201 |
} |
| 202 |
} |
| 203 |
|
| 204 |
impl<T: Float> From<T> for OrderedFloat<T> { |
| 205 |
#[inline] |
| 206 |
fn from(val: T) -> Self { |
| 207 |
OrderedFloat(val) |
| 208 |
} |
| 209 |
} |
| 210 |
|
| 211 |
impl<T: Float> Deref for OrderedFloat<T> { |
| 212 |
type Target = T; |
| 213 |
|
| 214 |
#[inline] |
| 215 |
fn deref(&self) -> &Self::Target { |
| 216 |
&self.0 |
| 217 |
} |
| 218 |
} |
| 219 |
|
| 220 |
impl<T: Float> DerefMut for OrderedFloat<T> { |
| 221 |
#[inline] |
| 222 |
fn deref_mut(&mut self) -> &mut Self::Target { |
| 223 |
&mut self.0 |
| 224 |
} |
| 225 |
} |
| 226 |
|
| 227 |
impl<T: Float> Eq for OrderedFloat<T> {} |
| 228 |
|
| 229 |
macro_rules! impl_ordered_float_binop { |
| 230 |
($imp:ident, $method:ident, $assign_imp:ident, $assign_method:ident) => { |
| 231 |
impl<T: $imp> $imp for OrderedFloat<T> { |
| 232 |
type Output = OrderedFloat<T::Output>; |
| 233 |
|
| 234 |
#[inline] |
| 235 |
fn $method(self, other: Self) -> Self::Output { |
| 236 |
OrderedFloat((self.0).$method(other.0)) |
| 237 |
} |
| 238 |
} |
| 239 |
|
| 240 |
impl<T: $imp> $imp<T> for OrderedFloat<T> { |
| 241 |
type Output = OrderedFloat<T::Output>; |
| 242 |
|
| 243 |
#[inline] |
| 244 |
fn $method(self, other: T) -> Self::Output { |
| 245 |
OrderedFloat((self.0).$method(other)) |
| 246 |
} |
| 247 |
} |
| 248 |
|
| 249 |
impl<'a, T> $imp<&'a T> for OrderedFloat<T> |
| 250 |
where |
| 251 |
T: $imp<&'a T>, |
| 252 |
{ |
| 253 |
type Output = OrderedFloat<<T as $imp<&'a T>>::Output>; |
| 254 |
|
| 255 |
#[inline] |
| 256 |
fn $method(self, other: &'a T) -> Self::Output { |
| 257 |
OrderedFloat((self.0).$method(other)) |
| 258 |
} |
| 259 |
} |
| 260 |
|
| 261 |
impl<'a, T> $imp<&'a Self> for OrderedFloat<T> |
| 262 |
where |
| 263 |
T: $imp<&'a T>, |
| 264 |
{ |
| 265 |
type Output = OrderedFloat<<T as $imp<&'a T>>::Output>; |
| 266 |
|
| 267 |
#[inline] |
| 268 |
fn $method(self, other: &'a Self) -> Self::Output { |
| 269 |
OrderedFloat((self.0).$method(&other.0)) |
| 270 |
} |
| 271 |
} |
| 272 |
|
| 273 |
impl<'a, T> $imp<OrderedFloat<T>> for &'a OrderedFloat<T> |
| 274 |
where |
| 275 |
&'a T: $imp<T>, |
| 276 |
{ |
| 277 |
type Output = OrderedFloat<<&'a T as $imp<T>>::Output>; |
| 278 |
|
| 279 |
#[inline] |
| 280 |
fn $method(self, other: OrderedFloat<T>) -> Self::Output { |
| 281 |
OrderedFloat((self.0).$method(other.0)) |
| 282 |
} |
| 283 |
} |
| 284 |
|
| 285 |
impl<'a, T> $imp<T> for &'a OrderedFloat<T> |
| 286 |
where |
| 287 |
&'a T: $imp<T>, |
| 288 |
{ |
| 289 |
type Output = OrderedFloat<<&'a T as $imp<T>>::Output>; |
| 290 |
|
| 291 |
#[inline] |
| 292 |
fn $method(self, other: T) -> Self::Output { |
| 293 |
OrderedFloat((self.0).$method(other)) |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
impl<'a, T> $imp<&'a T> for &'a OrderedFloat<T> |
| 298 |
where |
| 299 |
&'a T: $imp, |
| 300 |
{ |
| 301 |
type Output = OrderedFloat<<&'a T as $imp>::Output>; |
| 302 |
|
| 303 |
#[inline] |
| 304 |
fn $method(self, other: &'a T) -> Self::Output { |
| 305 |
OrderedFloat((self.0).$method(other)) |
| 306 |
} |
| 307 |
} |
| 308 |
|
| 309 |
impl<T: $assign_imp> $assign_imp<T> for OrderedFloat<T> { |
| 310 |
#[inline] |
| 311 |
fn $assign_method(&mut self, other: T) { |
| 312 |
(self.0).$assign_method(other); |
| 313 |
} |
| 314 |
} |
| 315 |
|
| 316 |
impl<'a, T: $assign_imp<&'a T>> $assign_imp<&'a T> for OrderedFloat<T> { |
| 317 |
#[inline] |
| 318 |
fn $assign_method(&mut self, other: &'a T) { |
| 319 |
(self.0).$assign_method(other); |
| 320 |
} |
| 321 |
} |
| 322 |
|
| 323 |
impl<T: $assign_imp> $assign_imp for OrderedFloat<T> { |
| 324 |
#[inline] |
| 325 |
fn $assign_method(&mut self, other: Self) { |
| 326 |
(self.0).$assign_method(other.0); |
| 327 |
} |
| 328 |
} |
| 329 |
|
| 330 |
impl<'a, T: $assign_imp<&'a T>> $assign_imp<&'a Self> for OrderedFloat<T> { |
| 331 |
#[inline] |
| 332 |
fn $assign_method(&mut self, other: &'a Self) { |
| 333 |
(self.0).$assign_method(&other.0); |
| 334 |
} |
| 335 |
} |
| 336 |
}; |
| 337 |
} |
| 338 |
|
| 339 |
impl_ordered_float_binop! {Add, add, AddAssign, add_assign} |
| 340 |
impl_ordered_float_binop! {Sub, sub, SubAssign, sub_assign} |
| 341 |
impl_ordered_float_binop! {Mul, mul, MulAssign, mul_assign} |
| 342 |
impl_ordered_float_binop! {Div, div, DivAssign, div_assign} |
| 343 |
impl_ordered_float_binop! {Rem, rem, RemAssign, rem_assign} |
| 344 |
|
| 345 |
/// Adds a float directly. |
| 346 |
impl<T: Float + Sum> Sum for OrderedFloat<T> { |
| 347 |
fn sum<I: Iterator<Item = OrderedFloat<T>>>(iter: I) -> Self { |
| 348 |
OrderedFloat(iter.map(|v| v.0).sum()) |
| 349 |
} |
| 350 |
} |
| 351 |
|
| 352 |
impl<'a, T: Float + Sum + 'a> Sum<&'a OrderedFloat<T>> for OrderedFloat<T> { |
| 353 |
#[inline] |
| 354 |
fn sum<I: Iterator<Item = &'a OrderedFloat<T>>>(iter: I) -> Self { |
| 355 |
iter.cloned().sum() |
| 356 |
} |
| 357 |
} |
| 358 |
|
| 359 |
impl<T: Float + Product> Product for OrderedFloat<T> { |
| 360 |
fn product<I: Iterator<Item = OrderedFloat<T>>>(iter: I) -> Self { |
| 361 |
OrderedFloat(iter.map(|v| v.0).product()) |
| 362 |
} |
| 363 |
} |
| 364 |
|
| 365 |
impl<'a, T: Float + Product + 'a> Product<&'a OrderedFloat<T>> for OrderedFloat<T> { |
| 366 |
#[inline] |
| 367 |
fn product<I: Iterator<Item = &'a OrderedFloat<T>>>(iter: I) -> Self { |
| 368 |
iter.cloned().product() |
| 369 |
} |
| 370 |
} |
| 371 |
|
| 372 |
impl<T: Float + Signed> Signed for OrderedFloat<T> { |
| 373 |
#[inline] |
| 374 |
fn abs(&self) -> Self { |
| 375 |
OrderedFloat(self.0.abs()) |
| 376 |
} |
| 377 |
|
| 378 |
fn abs_sub(&self, other: &Self) -> Self { |
| 379 |
OrderedFloat(Signed::abs_sub(&self.0, &other.0)) |
| 380 |
} |
| 381 |
|
| 382 |
#[inline] |
| 383 |
fn signum(&self) -> Self { |
| 384 |
OrderedFloat(self.0.signum()) |
| 385 |
} |
| 386 |
#[inline] |
| 387 |
fn is_positive(&self) -> bool { |
| 388 |
self.0.is_positive() |
| 389 |
} |
| 390 |
#[inline] |
| 391 |
fn is_negative(&self) -> bool { |
| 392 |
self.0.is_negative() |
| 393 |
} |
| 394 |
} |
| 395 |
|
| 396 |
impl<T: Bounded> Bounded for OrderedFloat<T> { |
| 397 |
#[inline] |
| 398 |
fn min_value() -> Self { |
| 399 |
OrderedFloat(T::min_value()) |
| 400 |
} |
| 401 |
|
| 402 |
#[inline] |
| 403 |
fn max_value() -> Self { |
| 404 |
OrderedFloat(T::max_value()) |
| 405 |
} |
| 406 |
} |
| 407 |
|
| 408 |
impl<T: FromStr> FromStr for OrderedFloat<T> { |
| 409 |
type Err = T::Err; |
| 410 |
|
| 411 |
/// Convert a &str to `OrderedFloat`. Returns an error if the string fails to parse. |
| 412 |
/// |
| 413 |
/// ``` |
| 414 |
/// use ordered_float::OrderedFloat; |
| 415 |
/// |
| 416 |
/// assert!("-10".parse::<OrderedFloat<f32>>().is_ok()); |
| 417 |
/// assert!("abc".parse::<OrderedFloat<f32>>().is_err()); |
| 418 |
/// assert!("NaN".parse::<OrderedFloat<f32>>().is_ok()); |
| 419 |
/// ``` |
| 420 |
fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 421 |
T::from_str(s).map(OrderedFloat) |
| 422 |
} |
| 423 |
} |
| 424 |
|
| 425 |
impl<T: Neg> Neg for OrderedFloat<T> { |
| 426 |
type Output = OrderedFloat<T::Output>; |
| 427 |
|
| 428 |
#[inline] |
| 429 |
fn neg(self) -> Self::Output { |
| 430 |
OrderedFloat(-self.0) |
| 431 |
} |
| 432 |
} |
| 433 |
|
| 434 |
impl<'a, T> Neg for &'a OrderedFloat<T> |
| 435 |
where |
| 436 |
&'a T: Neg, |
| 437 |
{ |
| 438 |
type Output = OrderedFloat<<&'a T as Neg>::Output>; |
| 439 |
|
| 440 |
#[inline] |
| 441 |
fn neg(self) -> Self::Output { |
| 442 |
OrderedFloat(-(&self.0)) |
| 443 |
} |
| 444 |
} |
| 445 |
|
| 446 |
impl<T: Zero> Zero for OrderedFloat<T> { |
| 447 |
#[inline] |
| 448 |
fn zero() -> Self { |
| 449 |
OrderedFloat(T::zero()) |
| 450 |
} |
| 451 |
|
| 452 |
#[inline] |
| 453 |
fn is_zero(&self) -> bool { |
| 454 |
self.0.is_zero() |
| 455 |
} |
| 456 |
} |
| 457 |
|
| 458 |
impl<T: One> One for OrderedFloat<T> { |
| 459 |
#[inline] |
| 460 |
fn one() -> Self { |
| 461 |
OrderedFloat(T::one()) |
| 462 |
} |
| 463 |
} |
| 464 |
|
| 465 |
impl<T: NumCast> NumCast for OrderedFloat<T> { |
| 466 |
#[inline] |
| 467 |
fn from<F: ToPrimitive>(n: F) -> Option<Self> { |
| 468 |
T::from(n).map(OrderedFloat) |
| 469 |
} |
| 470 |
} |
| 471 |
|
| 472 |
macro_rules! impl_as_primitive { |
| 473 |
(@ (OrderedFloat<$T: ty>) => $(#[$cfg:meta])* impl (OrderedFloat<$U: ty>) ) => { |
| 474 |
$(#[$cfg])* |
| 475 |
impl AsPrimitive<OrderedFloat<$U>> for OrderedFloat<$T> { |
| 476 |
#[inline] fn as_(self) -> OrderedFloat<$U> { OrderedFloat(self.0 as $U) } |
| 477 |
} |
| 478 |
}; |
| 479 |
(@ ($T: ty) => $(#[$cfg:meta])* impl (OrderedFloat<$U: ty>) ) => { |
| 480 |
$(#[$cfg])* |
| 481 |
impl AsPrimitive<OrderedFloat<$U>> for $T { |
| 482 |
#[inline] fn as_(self) -> OrderedFloat<$U> { OrderedFloat(self as $U) } |
| 483 |
} |
| 484 |
}; |
| 485 |
(@ (OrderedFloat<$T: ty>) => $(#[$cfg:meta])* impl ($U: ty) ) => { |
| 486 |
$(#[$cfg])* |
| 487 |
impl AsPrimitive<$U> for OrderedFloat<$T> { |
| 488 |
#[inline] fn as_(self) -> $U { self.0 as $U } |
| 489 |
} |
| 490 |
}; |
| 491 |
($T: tt => { $( $U: tt ),* } ) => {$( |
| 492 |
impl_as_primitive!(@ $T => impl $U); |
| 493 |
)*}; |
| 494 |
} |
| 495 |
|
| 496 |
impl_as_primitive!((OrderedFloat<f32>) => { (OrderedFloat<f32>), (OrderedFloat<f64>) }); |
| 497 |
impl_as_primitive!((OrderedFloat<f64>) => { (OrderedFloat<f32>), (OrderedFloat<f64>) }); |
| 498 |
|
| 499 |
impl_as_primitive!((u8) => { (OrderedFloat<f32>), (OrderedFloat<f64>) }); |
| 500 |
impl_as_primitive!((i8) => { (OrderedFloat<f32>), (OrderedFloat<f64>) }); |
| 501 |
impl_as_primitive!((u16) => { (OrderedFloat<f32>), (OrderedFloat<f64>) }); |
| 502 |
impl_as_primitive!((i16) => { (OrderedFloat<f32>), (OrderedFloat<f64>) }); |
| 503 |
impl_as_primitive!((u32) => { (OrderedFloat<f32>), (OrderedFloat<f64>) }); |
| 504 |
impl_as_primitive!((i32) => { (OrderedFloat<f32>), (OrderedFloat<f64>) }); |
| 505 |
impl_as_primitive!((u64) => { (OrderedFloat<f32>), (OrderedFloat<f64>) }); |
| 506 |
impl_as_primitive!((i64) => { (OrderedFloat<f32>), (OrderedFloat<f64>) }); |
| 507 |
impl_as_primitive!((usize) => { (OrderedFloat<f32>), (OrderedFloat<f64>) }); |
| 508 |
impl_as_primitive!((isize) => { (OrderedFloat<f32>), (OrderedFloat<f64>) }); |
| 509 |
impl_as_primitive!((f32) => { (OrderedFloat<f32>), (OrderedFloat<f64>) }); |
| 510 |
impl_as_primitive!((f64) => { (OrderedFloat<f32>), (OrderedFloat<f64>) }); |
| 511 |
|
| 512 |
impl_as_primitive!((OrderedFloat<f32>) => { (u8), (u16), (u32), (u64), (usize), (i8), (i16), (i32), (i64), (isize), (f32), (f64) }); |
| 513 |
impl_as_primitive!((OrderedFloat<f64>) => { (u8), (u16), (u32), (u64), (usize), (i8), (i16), (i32), (i64), (isize), (f32), (f64) }); |
| 514 |
|
| 515 |
impl<T: FromPrimitive> FromPrimitive for OrderedFloat<T> { |
| 516 |
fn from_i64(n: i64) -> Option<Self> { |
| 517 |
T::from_i64(n).map(OrderedFloat) |
| 518 |
} |
| 519 |
fn from_u64(n: u64) -> Option<Self> { |
| 520 |
T::from_u64(n).map(OrderedFloat) |
| 521 |
} |
| 522 |
fn from_isize(n: isize) -> Option<Self> { |
| 523 |
T::from_isize(n).map(OrderedFloat) |
| 524 |
} |
| 525 |
fn from_i8(n: i8) -> Option<Self> { |
| 526 |
T::from_i8(n).map(OrderedFloat) |
| 527 |
} |
| 528 |
fn from_i16(n: i16) -> Option<Self> { |
| 529 |
T::from_i16(n).map(OrderedFloat) |
| 530 |
} |
| 531 |
fn from_i32(n: i32) -> Option<Self> { |
| 532 |
T::from_i32(n).map(OrderedFloat) |
| 533 |
} |
| 534 |
fn from_usize(n: usize) -> Option<Self> { |
| 535 |
T::from_usize(n).map(OrderedFloat) |
| 536 |
} |
| 537 |
fn from_u8(n: u8) -> Option<Self> { |
| 538 |
T::from_u8(n).map(OrderedFloat) |
| 539 |
} |
| 540 |
fn from_u16(n: u16) -> Option<Self> { |
| 541 |
T::from_u16(n).map(OrderedFloat) |
| 542 |
} |
| 543 |
fn from_u32(n: u32) -> Option<Self> { |
| 544 |
T::from_u32(n).map(OrderedFloat) |
| 545 |
} |
| 546 |
fn from_f32(n: f32) -> Option<Self> { |
| 547 |
T::from_f32(n).map(OrderedFloat) |
| 548 |
} |
| 549 |
fn from_f64(n: f64) -> Option<Self> { |
| 550 |
T::from_f64(n).map(OrderedFloat) |
| 551 |
} |
| 552 |
} |
| 553 |
|
| 554 |
impl<T: ToPrimitive> ToPrimitive for OrderedFloat<T> { |
| 555 |
fn to_i64(&self) -> Option<i64> { |
| 556 |
self.0.to_i64() |
| 557 |
} |
| 558 |
fn to_u64(&self) -> Option<u64> { |
| 559 |
self.0.to_u64() |
| 560 |
} |
| 561 |
fn to_isize(&self) -> Option<isize> { |
| 562 |
self.0.to_isize() |
| 563 |
} |
| 564 |
fn to_i8(&self) -> Option<i8> { |
| 565 |
self.0.to_i8() |
| 566 |
} |
| 567 |
fn to_i16(&self) -> Option<i16> { |
| 568 |
self.0.to_i16() |
| 569 |
} |
| 570 |
fn to_i32(&self) -> Option<i32> { |
| 571 |
self.0.to_i32() |
| 572 |
} |
| 573 |
fn to_usize(&self) -> Option<usize> { |
| 574 |
self.0.to_usize() |
| 575 |
} |
| 576 |
fn to_u8(&self) -> Option<u8> { |
| 577 |
self.0.to_u8() |
| 578 |
} |
| 579 |
fn to_u16(&self) -> Option<u16> { |
| 580 |
self.0.to_u16() |
| 581 |
} |
| 582 |
fn to_u32(&self) -> Option<u32> { |
| 583 |
self.0.to_u32() |
| 584 |
} |
| 585 |
fn to_f32(&self) -> Option<f32> { |
| 586 |
self.0.to_f32() |
| 587 |
} |
| 588 |
fn to_f64(&self) -> Option<f64> { |
| 589 |
self.0.to_f64() |
| 590 |
} |
| 591 |
} |
| 592 |
|
| 593 |
impl<T: Float> num_traits::float::FloatCore for OrderedFloat<T> { |
| 594 |
fn nan() -> Self { |
| 595 |
OrderedFloat(T::nan()) |
| 596 |
} |
| 597 |
fn infinity() -> Self { |
| 598 |
OrderedFloat(T::infinity()) |
| 599 |
} |
| 600 |
fn neg_infinity() -> Self { |
| 601 |
OrderedFloat(T::neg_infinity()) |
| 602 |
} |
| 603 |
fn neg_zero() -> Self { |
| 604 |
OrderedFloat(T::neg_zero()) |
| 605 |
} |
| 606 |
fn min_value() -> Self { |
| 607 |
OrderedFloat(T::min_value()) |
| 608 |
} |
| 609 |
fn min_positive_value() -> Self { |
| 610 |
OrderedFloat(T::min_positive_value()) |
| 611 |
} |
| 612 |
fn max_value() -> Self { |
| 613 |
OrderedFloat(T::max_value()) |
| 614 |
} |
| 615 |
fn is_nan(self) -> bool { |
| 616 |
self.0.is_nan() |
| 617 |
} |
| 618 |
fn is_infinite(self) -> bool { |
| 619 |
self.0.is_infinite() |
| 620 |
} |
| 621 |
fn is_finite(self) -> bool { |
| 622 |
self.0.is_finite() |
| 623 |
} |
| 624 |
fn is_normal(self) -> bool { |
| 625 |
self.0.is_normal() |
| 626 |
} |
| 627 |
fn classify(self) -> FpCategory { |
| 628 |
self.0.classify() |
| 629 |
} |
| 630 |
fn floor(self) -> Self { |
| 631 |
OrderedFloat(self.0.floor()) |
| 632 |
} |
| 633 |
fn ceil(self) -> Self { |
| 634 |
OrderedFloat(self.0.ceil()) |
| 635 |
} |
| 636 |
fn round(self) -> Self { |
| 637 |
OrderedFloat(self.0.round()) |
| 638 |
} |
| 639 |
fn trunc(self) -> Self { |
| 640 |
OrderedFloat(self.0.trunc()) |
| 641 |
} |
| 642 |
fn fract(self) -> Self { |
| 643 |
OrderedFloat(self.0.fract()) |
| 644 |
} |
| 645 |
fn abs(self) -> Self { |
| 646 |
OrderedFloat(self.0.abs()) |
| 647 |
} |
| 648 |
fn signum(self) -> Self { |
| 649 |
OrderedFloat(self.0.signum()) |
| 650 |
} |
| 651 |
fn is_sign_positive(self) -> bool { |
| 652 |
self.0.is_sign_positive() |
| 653 |
} |
| 654 |
fn is_sign_negative(self) -> bool { |
| 655 |
self.0.is_sign_negative() |
| 656 |
} |
| 657 |
fn recip(self) -> Self { |
| 658 |
OrderedFloat(self.0.recip()) |
| 659 |
} |
| 660 |
fn powi(self, n: i32) -> Self { |
| 661 |
OrderedFloat(self.0.powi(n)) |
| 662 |
} |
| 663 |
fn integer_decode(self) -> (u64, i16, i8) { |
| 664 |
self.0.integer_decode() |
| 665 |
} |
| 666 |
fn epsilon() -> Self { |
| 667 |
OrderedFloat(T::epsilon()) |
| 668 |
} |
| 669 |
fn to_degrees(self) -> Self { |
| 670 |
OrderedFloat(self.0.to_degrees()) |
| 671 |
} |
| 672 |
fn to_radians(self) -> Self { |
| 673 |
OrderedFloat(self.0.to_radians()) |
| 674 |
} |
| 675 |
} |
| 676 |
|
| 677 |
#[cfg(feature = "std")] |
| 678 |
impl<T: Float> Float for OrderedFloat<T> { |
| 679 |
fn nan() -> Self { |
| 680 |
OrderedFloat(T::nan()) |
| 681 |
} |
| 682 |
fn infinity() -> Self { |
| 683 |
OrderedFloat(T::infinity()) |
| 684 |
} |
| 685 |
fn neg_infinity() -> Self { |
| 686 |
OrderedFloat(T::neg_infinity()) |
| 687 |
} |
| 688 |
fn neg_zero() -> Self { |
| 689 |
OrderedFloat(T::neg_zero()) |
| 690 |
} |
| 691 |
fn min_value() -> Self { |
| 692 |
OrderedFloat(T::min_value()) |
| 693 |
} |
| 694 |
fn min_positive_value() -> Self { |
| 695 |
OrderedFloat(T::min_positive_value()) |
| 696 |
} |
| 697 |
fn max_value() -> Self { |
| 698 |
OrderedFloat(T::max_value()) |
| 699 |
} |
| 700 |
fn is_nan(self) -> bool { |
| 701 |
self.0.is_nan() |
| 702 |
} |
| 703 |
fn is_infinite(self) -> bool { |
| 704 |
self.0.is_infinite() |
| 705 |
} |
| 706 |
fn is_finite(self) -> bool { |
| 707 |
self.0.is_finite() |
| 708 |
} |
| 709 |
fn is_normal(self) -> bool { |
| 710 |
self.0.is_normal() |
| 711 |
} |
| 712 |
fn classify(self) -> FpCategory { |
| 713 |
self.0.classify() |
| 714 |
} |
| 715 |
fn floor(self) -> Self { |
| 716 |
OrderedFloat(self.0.floor()) |
| 717 |
} |
| 718 |
fn ceil(self) -> Self { |
| 719 |
OrderedFloat(self.0.ceil()) |
| 720 |
} |
| 721 |
fn round(self) -> Self { |
| 722 |
OrderedFloat(self.0.round()) |
| 723 |
} |
| 724 |
fn trunc(self) -> Self { |
| 725 |
OrderedFloat(self.0.trunc()) |
| 726 |
} |
| 727 |
fn fract(self) -> Self { |
| 728 |
OrderedFloat(self.0.fract()) |
| 729 |
} |
| 730 |
fn abs(self) -> Self { |
| 731 |
OrderedFloat(self.0.abs()) |
| 732 |
} |
| 733 |
fn signum(self) -> Self { |
| 734 |
OrderedFloat(self.0.signum()) |
| 735 |
} |
| 736 |
fn is_sign_positive(self) -> bool { |
| 737 |
self.0.is_sign_positive() |
| 738 |
} |
| 739 |
fn is_sign_negative(self) -> bool { |
| 740 |
self.0.is_sign_negative() |
| 741 |
} |
| 742 |
fn mul_add(self, a: Self, b: Self) -> Self { |
| 743 |
OrderedFloat(self.0.mul_add(a.0, b.0)) |
| 744 |
} |
| 745 |
fn recip(self) -> Self { |
| 746 |
OrderedFloat(self.0.recip()) |
| 747 |
} |
| 748 |
fn powi(self, n: i32) -> Self { |
| 749 |
OrderedFloat(self.0.powi(n)) |
| 750 |
} |
| 751 |
fn powf(self, n: Self) -> Self { |
| 752 |
OrderedFloat(self.0.powf(n.0)) |
| 753 |
} |
| 754 |
fn sqrt(self) -> Self { |
| 755 |
OrderedFloat(self.0.sqrt()) |
| 756 |
} |
| 757 |
fn exp(self) -> Self { |
| 758 |
OrderedFloat(self.0.exp()) |
| 759 |
} |
| 760 |
fn exp2(self) -> Self { |
| 761 |
OrderedFloat(self.0.exp2()) |
| 762 |
} |
| 763 |
fn ln(self) -> Self { |
| 764 |
OrderedFloat(self.0.ln()) |
| 765 |
} |
| 766 |
fn log(self, base: Self) -> Self { |
| 767 |
OrderedFloat(self.0.log(base.0)) |
| 768 |
} |
| 769 |
fn log2(self) -> Self { |
| 770 |
OrderedFloat(self.0.log2()) |
| 771 |
} |
| 772 |
fn log10(self) -> Self { |
| 773 |
OrderedFloat(self.0.log10()) |
| 774 |
} |
| 775 |
fn max(self, other: Self) -> Self { |
| 776 |
OrderedFloat(self.0.max(other.0)) |
| 777 |
} |
| 778 |
fn min(self, other: Self) -> Self { |
| 779 |
OrderedFloat(self.0.min(other.0)) |
| 780 |
} |
| 781 |
fn abs_sub(self, other: Self) -> Self { |
| 782 |
OrderedFloat(self.0.abs_sub(other.0)) |
| 783 |
} |
| 784 |
fn cbrt(self) -> Self { |
| 785 |
OrderedFloat(self.0.cbrt()) |
| 786 |
} |
| 787 |
fn hypot(self, other: Self) -> Self { |
| 788 |
OrderedFloat(self.0.hypot(other.0)) |
| 789 |
} |
| 790 |
fn sin(self) -> Self { |
| 791 |
OrderedFloat(self.0.sin()) |
| 792 |
} |
| 793 |
fn cos(self) -> Self { |
| 794 |
OrderedFloat(self.0.cos()) |
| 795 |
} |
| 796 |
fn tan(self) -> Self { |
| 797 |
OrderedFloat(self.0.tan()) |
| 798 |
} |
| 799 |
fn asin(self) -> Self { |
| 800 |
OrderedFloat(self.0.asin()) |
| 801 |
} |
| 802 |
fn acos(self) -> Self { |
| 803 |
OrderedFloat(self.0.acos()) |
| 804 |
} |
| 805 |
fn atan(self) -> Self { |
| 806 |
OrderedFloat(self.0.atan()) |
| 807 |
} |
| 808 |
fn atan2(self, other: Self) -> Self { |
| 809 |
OrderedFloat(self.0.atan2(other.0)) |
| 810 |
} |
| 811 |
fn sin_cos(self) -> (Self, Self) { |
| 812 |
let (a, b) = self.0.sin_cos(); |
| 813 |
(OrderedFloat(a), OrderedFloat(b)) |
| 814 |
} |
| 815 |
fn exp_m1(self) -> Self { |
| 816 |
OrderedFloat(self.0.exp_m1()) |
| 817 |
} |
| 818 |
fn ln_1p(self) -> Self { |
| 819 |
OrderedFloat(self.0.ln_1p()) |
| 820 |
} |
| 821 |
fn sinh(self) -> Self { |
| 822 |
OrderedFloat(self.0.sinh()) |
| 823 |
} |
| 824 |
fn cosh(self) -> Self { |
| 825 |
OrderedFloat(self.0.cosh()) |
| 826 |
} |
| 827 |
fn tanh(self) -> Self { |
| 828 |
OrderedFloat(self.0.tanh()) |
| 829 |
} |
| 830 |
fn asinh(self) -> Self { |
| 831 |
OrderedFloat(self.0.asinh()) |
| 832 |
} |
| 833 |
fn acosh(self) -> Self { |
| 834 |
OrderedFloat(self.0.acosh()) |
| 835 |
} |
| 836 |
fn atanh(self) -> Self { |
| 837 |
OrderedFloat(self.0.atanh()) |
| 838 |
} |
| 839 |
fn integer_decode(self) -> (u64, i16, i8) { |
| 840 |
self.0.integer_decode() |
| 841 |
} |
| 842 |
fn epsilon() -> Self { |
| 843 |
OrderedFloat(T::epsilon()) |
| 844 |
} |
| 845 |
fn to_degrees(self) -> Self { |
| 846 |
OrderedFloat(self.0.to_degrees()) |
| 847 |
} |
| 848 |
fn to_radians(self) -> Self { |
| 849 |
OrderedFloat(self.0.to_radians()) |
| 850 |
} |
| 851 |
} |
| 852 |
|
| 853 |
impl<T: Float + Num> Num for OrderedFloat<T> { |
| 854 |
type FromStrRadixErr = T::FromStrRadixErr; |
| 855 |
fn from_str_radix(str: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> { |
| 856 |
T::from_str_radix(str, radix).map(OrderedFloat) |
| 857 |
} |
| 858 |
} |
| 859 |
|
| 860 |
/// A wrapper around floats providing an implementation of `Eq`, `Ord` and `Hash`. |
| 861 |
/// |
| 862 |
/// A NaN value cannot be stored in this type. |
| 863 |
/// |
| 864 |
/// ``` |
| 865 |
/// use ordered_float::NotNan; |
| 866 |
/// |
| 867 |
/// let mut v = [ |
| 868 |
/// NotNan::new(2.0).unwrap(), |
| 869 |
/// NotNan::new(1.0).unwrap(), |
| 870 |
/// ]; |
| 871 |
/// v.sort(); |
| 872 |
/// assert_eq!(v, [1.0, 2.0]); |
| 873 |
/// ``` |
| 874 |
/// |
| 875 |
/// Because `NotNan` implements `Ord` and `Eq`, it can be used as a key in a `HashSet`, |
| 876 |
/// `HashMap`, `BTreeMap`, or `BTreeSet` (unlike the primitive `f32` or `f64` types): |
| 877 |
/// |
| 878 |
/// ``` |
| 879 |
/// # use ordered_float::NotNan; |
| 880 |
/// # use std::collections::HashSet; |
| 881 |
/// |
| 882 |
/// let mut s: HashSet<NotNan<f32>> = HashSet::new(); |
| 883 |
/// let key = NotNan::new(1.0).unwrap(); |
| 884 |
/// s.insert(key); |
| 885 |
/// assert!(s.contains(&key)); |
| 886 |
/// ``` |
| 887 |
/// |
| 888 |
/// Arithmetic on NotNan values will panic if it produces a NaN value: |
| 889 |
/// |
| 890 |
/// ```should_panic |
| 891 |
/// # use ordered_float::NotNan; |
| 892 |
/// let a = NotNan::new(std::f32::INFINITY).unwrap(); |
| 893 |
/// let b = NotNan::new(std::f32::NEG_INFINITY).unwrap(); |
| 894 |
/// |
| 895 |
/// // This will panic: |
| 896 |
/// let c = a + b; |
| 897 |
/// ``` |
| 898 |
#[derive(PartialOrd, PartialEq, Debug, Default, Clone, Copy)] |
| 899 |
#[repr(transparent)] |
| 900 |
pub struct NotNan<T>(T); |
| 901 |
|
| 902 |
impl<T: Float> NotNan<T> { |
| 903 |
/// Create a `NotNan` value. |
| 904 |
/// |
| 905 |
/// Returns `Err` if `val` is NaN |
| 906 |
pub fn new(val: T) -> Result<Self, FloatIsNan> { |
| 907 |
match val { |
| 908 |
ref val if val.is_nan() => Err(FloatIsNan), |
| 909 |
val => Ok(NotNan(val)), |
| 910 |
} |
| 911 |
} |
| 912 |
} |
| 913 |
|
| 914 |
impl<T> NotNan<T> { |
| 915 |
/// Get the value out. |
| 916 |
#[inline] |
| 917 |
pub fn into_inner(self) -> T { |
| 918 |
self.0 |
| 919 |
} |
| 920 |
|
| 921 |
/// Create a `NotNan` value from a value that is guaranteed to not be NaN |
| 922 |
/// |
| 923 |
/// # Safety |
| 924 |
/// |
| 925 |
/// Behaviour is undefined if `val` is NaN |
| 926 |
#[inline] |
| 927 |
pub const unsafe fn new_unchecked(val: T) -> Self { |
| 928 |
NotNan(val) |
| 929 |
} |
| 930 |
|
| 931 |
/// Create a `NotNan` value from a value that is guaranteed to not be NaN |
| 932 |
/// |
| 933 |
/// # Safety |
| 934 |
/// |
| 935 |
/// Behaviour is undefined if `val` is NaN |
| 936 |
#[deprecated( |
| 937 |
since = "2.5.0", |
| 938 |
note = "Please use the new_unchecked function instead." |
| 939 |
)] |
| 940 |
#[inline] |
| 941 |
pub const unsafe fn unchecked_new(val: T) -> Self { |
| 942 |
Self::new_unchecked(val) |
| 943 |
} |
| 944 |
} |
| 945 |
|
| 946 |
impl<T: Float> AsRef<T> for NotNan<T> { |
| 947 |
#[inline] |
| 948 |
fn as_ref(&self) -> &T { |
| 949 |
&self.0 |
| 950 |
} |
| 951 |
} |
| 952 |
|
| 953 |
impl Borrow<f32> for NotNan<f32> { |
| 954 |
#[inline] |
| 955 |
fn borrow(&self) -> &f32 { |
| 956 |
&self.0 |
| 957 |
} |
| 958 |
} |
| 959 |
|
| 960 |
impl Borrow<f64> for NotNan<f64> { |
| 961 |
#[inline] |
| 962 |
fn borrow(&self) -> &f64 { |
| 963 |
&self.0 |
| 964 |
} |
| 965 |
} |
| 966 |
|
| 967 |
#[allow(clippy::derive_ord_xor_partial_ord)] |
| 968 |
impl<T: Float> Ord for NotNan<T> { |
| 969 |
fn cmp(&self, other: &NotNan<T>) -> Ordering { |
| 970 |
match self.partial_cmp(other) { |
| 971 |
Some(ord) => ord, |
| 972 |
None => unsafe { unreachable_unchecked() }, |
| 973 |
} |
| 974 |
} |
| 975 |
} |
| 976 |
|
| 977 |
#[allow(clippy::derive_hash_xor_eq)] |
| 978 |
impl<T: Float> Hash for NotNan<T> { |
| 979 |
#[inline] |
| 980 |
fn hash<H: Hasher>(&self, state: &mut H) { |
| 981 |
hash_float(&self.0, state) |
| 982 |
} |
| 983 |
} |
| 984 |
|
| 985 |
impl<T: Float + fmt::Display> fmt::Display for NotNan<T> { |
| 986 |
#[inline] |
| 987 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 988 |
self.0.fmt(f) |
| 989 |
} |
| 990 |
} |
| 991 |
|
| 992 |
impl NotNan<f64> { |
| 993 |
/// Converts this [`NotNan`]`<`[`f64`]`>` to a [`NotNan`]`<`[`f32`]`>` while giving up on |
| 994 |
/// precision, [using `roundTiesToEven` as rounding mode, yielding `Infinity` on |
| 995 |
/// overflow](https://doc.rust-lang.org/reference/expressions/operator-expr.html#semantics). |
| 996 |
pub fn as_f32(self) -> NotNan<f32> { |
| 997 |
// This is not destroying invariants, as it is a pure rounding operation. The only two special |
| 998 |
// cases are where f32 would be overflowing, then the operation yields Infinity, or where |
| 999 |
// the input is already NaN, in which case the invariant is already broken elsewhere. |
| 1000 |
NotNan(self.0 as f32) |
| 1001 |
} |
| 1002 |
} |
| 1003 |
|
| 1004 |
impl From<NotNan<f32>> for f32 { |
| 1005 |
#[inline] |
| 1006 |
fn from(value: NotNan<f32>) -> Self { |
| 1007 |
value.0 |
| 1008 |
} |
| 1009 |
} |
| 1010 |
|
| 1011 |
impl From<NotNan<f64>> for f64 { |
| 1012 |
#[inline] |
| 1013 |
fn from(value: NotNan<f64>) -> Self { |
| 1014 |
value.0 |
| 1015 |
} |
| 1016 |
} |
| 1017 |
|
| 1018 |
impl TryFrom<f32> for NotNan<f32> { |
| 1019 |
type Error = FloatIsNan; |
| 1020 |
#[inline] |
| 1021 |
fn try_from(v: f32) -> Result<Self, Self::Error> { |
| 1022 |
NotNan::new(v) |
| 1023 |
} |
| 1024 |
} |
| 1025 |
|
| 1026 |
impl TryFrom<f64> for NotNan<f64> { |
| 1027 |
type Error = FloatIsNan; |
| 1028 |
#[inline] |
| 1029 |
fn try_from(v: f64) -> Result<Self, Self::Error> { |
| 1030 |
NotNan::new(v) |
| 1031 |
} |
| 1032 |
} |
| 1033 |
|
| 1034 |
macro_rules! impl_from_int_primitive { |
| 1035 |
($primitive:ty, $inner:ty) => { |
| 1036 |
impl From<$primitive> for NotNan<$inner> { |
| 1037 |
fn from(source: $primitive) -> Self { |
| 1038 |
// the primitives with which this macro will be called cannot hold a value that |
| 1039 |
// f64::from would convert to NaN, so this does not hurt invariants |
| 1040 |
NotNan(<$inner as From<$primitive>>::from(source)) |
| 1041 |
} |
| 1042 |
} |
| 1043 |
}; |
| 1044 |
} |
| 1045 |
|
| 1046 |
impl_from_int_primitive!(i8, f64); |
| 1047 |
impl_from_int_primitive!(i16, f64); |
| 1048 |
impl_from_int_primitive!(i32, f64); |
| 1049 |
impl_from_int_primitive!(u8, f64); |
| 1050 |
impl_from_int_primitive!(u16, f64); |
| 1051 |
impl_from_int_primitive!(u32, f64); |
| 1052 |
|
| 1053 |
impl_from_int_primitive!(i8, f32); |
| 1054 |
impl_from_int_primitive!(i16, f32); |
| 1055 |
impl_from_int_primitive!(u8, f32); |
| 1056 |
impl_from_int_primitive!(u16, f32); |
| 1057 |
|
| 1058 |
impl From<NotNan<f32>> for NotNan<f64> { |
| 1059 |
#[inline] |
| 1060 |
fn from(v: NotNan<f32>) -> NotNan<f64> { |
| 1061 |
unsafe { NotNan::new_unchecked(v.0 as f64) } |
| 1062 |
} |
| 1063 |
} |
| 1064 |
|
| 1065 |
impl<T: Float> Deref for NotNan<T> { |
| 1066 |
type Target = T; |
| 1067 |
|
| 1068 |
#[inline] |
| 1069 |
fn deref(&self) -> &Self::Target { |
| 1070 |
&self.0 |
| 1071 |
} |
| 1072 |
} |
| 1073 |
|
| 1074 |
impl<T: Float + PartialEq> Eq for NotNan<T> {} |
| 1075 |
|
| 1076 |
impl<T: Float> PartialEq<T> for NotNan<T> { |
| 1077 |
#[inline] |
| 1078 |
fn eq(&self, other: &T) -> bool { |
| 1079 |
self.0 == *other |
| 1080 |
} |
| 1081 |
} |
| 1082 |
|
| 1083 |
/// Adds a float directly. |
| 1084 |
/// |
| 1085 |
/// Panics if the provided value is NaN or the computation results in NaN |
| 1086 |
impl<T: Float> Add<T> for NotNan<T> { |
| 1087 |
type Output = Self; |
| 1088 |
|
| 1089 |
#[inline] |
| 1090 |
fn add(self, other: T) -> Self { |
| 1091 |
NotNan::new(self.0 + other).expect("Addition resulted in NaN") |
| 1092 |
} |
| 1093 |
} |
| 1094 |
|
| 1095 |
/// Adds a float directly. |
| 1096 |
/// |
| 1097 |
/// Panics if the provided value is NaN. |
| 1098 |
impl<T: Float + Sum> Sum for NotNan<T> { |
| 1099 |
fn sum<I: Iterator<Item = NotNan<T>>>(iter: I) -> Self { |
| 1100 |
NotNan::new(iter.map(|v| v.0).sum()).expect("Sum resulted in NaN") |
| 1101 |
} |
| 1102 |
} |
| 1103 |
|
| 1104 |
impl<'a, T: Float + Sum + 'a> Sum<&'a NotNan<T>> for NotNan<T> { |
| 1105 |
#[inline] |
| 1106 |
fn sum<I: Iterator<Item = &'a NotNan<T>>>(iter: I) -> Self { |
| 1107 |
iter.cloned().sum() |
| 1108 |
} |
| 1109 |
} |
| 1110 |
|
| 1111 |
/// Subtracts a float directly. |
| 1112 |
/// |
| 1113 |
/// Panics if the provided value is NaN or the computation results in NaN |
| 1114 |
impl<T: Float> Sub<T> for NotNan<T> { |
| 1115 |
type Output = Self; |
| 1116 |
|
| 1117 |
#[inline] |
| 1118 |
fn sub(self, other: T) -> Self { |
| 1119 |
NotNan::new(self.0 - other).expect("Subtraction resulted in NaN") |
| 1120 |
} |
| 1121 |
} |
| 1122 |
|
| 1123 |
/// Multiplies a float directly. |
| 1124 |
/// |
| 1125 |
/// Panics if the provided value is NaN or the computation results in NaN |
| 1126 |
impl<T: Float> Mul<T> for NotNan<T> { |
| 1127 |
type Output = Self; |
| 1128 |
|
| 1129 |
#[inline] |
| 1130 |
fn mul(self, other: T) -> Self { |
| 1131 |
NotNan::new(self.0 * other).expect("Multiplication resulted in NaN") |
| 1132 |
} |
| 1133 |
} |
| 1134 |
|
| 1135 |
impl<T: Float + Product> Product for NotNan<T> { |
| 1136 |
fn product<I: Iterator<Item = NotNan<T>>>(iter: I) -> Self { |
| 1137 |
NotNan::new(iter.map(|v| v.0).product()).expect("Product resulted in NaN") |
| 1138 |
} |
| 1139 |
} |
| 1140 |
|
| 1141 |
impl<'a, T: Float + Product + 'a> Product<&'a NotNan<T>> for NotNan<T> { |
| 1142 |
#[inline] |
| 1143 |
fn product<I: Iterator<Item = &'a NotNan<T>>>(iter: I) -> Self { |
| 1144 |
iter.cloned().product() |
| 1145 |
} |
| 1146 |
} |
| 1147 |
|
| 1148 |
/// Divides a float directly. |
| 1149 |
/// |
| 1150 |
/// Panics if the provided value is NaN or the computation results in NaN |
| 1151 |
impl<T: Float> Div<T> for NotNan<T> { |
| 1152 |
type Output = Self; |
| 1153 |
|
| 1154 |
#[inline] |
| 1155 |
fn div(self, other: T) -> Self { |
| 1156 |
NotNan::new(self.0 / other).expect("Division resulted in NaN") |
| 1157 |
} |
| 1158 |
} |
| 1159 |
|
| 1160 |
/// Calculates `%` with a float directly. |
| 1161 |
/// |
| 1162 |
/// Panics if the provided value is NaN or the computation results in NaN |
| 1163 |
impl<T: Float> Rem<T> for NotNan<T> { |
| 1164 |
type Output = Self; |
| 1165 |
|
| 1166 |
#[inline] |
| 1167 |
fn rem(self, other: T) -> Self { |
| 1168 |
NotNan::new(self.0 % other).expect("Rem resulted in NaN") |
| 1169 |
} |
| 1170 |
} |
| 1171 |
|
| 1172 |
macro_rules! impl_not_nan_binop { |
| 1173 |
($imp:ident, $method:ident, $assign_imp:ident, $assign_method:ident) => { |
| 1174 |
impl<T: Float> $imp for NotNan<T> { |
| 1175 |
type Output = Self; |
| 1176 |
|
| 1177 |
#[inline] |
| 1178 |
fn $method(self, other: Self) -> Self { |
| 1179 |
self.$method(other.0) |
| 1180 |
} |
| 1181 |
} |
| 1182 |
|
| 1183 |
impl<T: Float> $imp<&T> for NotNan<T> { |
| 1184 |
type Output = NotNan<T>; |
| 1185 |
|
| 1186 |
#[inline] |
| 1187 |
fn $method(self, other: &T) -> Self::Output { |
| 1188 |
self.$method(*other) |
| 1189 |
} |
| 1190 |
} |
| 1191 |
|
| 1192 |
impl<T: Float> $imp<&Self> for NotNan<T> { |
| 1193 |
type Output = NotNan<T>; |
| 1194 |
|
| 1195 |
#[inline] |
| 1196 |
fn $method(self, other: &Self) -> Self::Output { |
| 1197 |
self.$method(other.0) |
| 1198 |
} |
| 1199 |
} |
| 1200 |
|
| 1201 |
impl<T: Float> $imp for &NotNan<T> { |
| 1202 |
type Output = NotNan<T>; |
| 1203 |
|
| 1204 |
#[inline] |
| 1205 |
fn $method(self, other: Self) -> Self::Output { |
| 1206 |
(*self).$method(other.0) |
| 1207 |
} |
| 1208 |
} |
| 1209 |
|
| 1210 |
impl<T: Float> $imp<NotNan<T>> for &NotNan<T> { |
| 1211 |
type Output = NotNan<T>; |
| 1212 |
|
| 1213 |
#[inline] |
| 1214 |
fn $method(self, other: NotNan<T>) -> Self::Output { |
| 1215 |
(*self).$method(other.0) |
| 1216 |
} |
| 1217 |
} |
| 1218 |
|
| 1219 |
impl<T: Float> $imp<T> for &NotNan<T> { |
| 1220 |
type Output = NotNan<T>; |
| 1221 |
|
| 1222 |
#[inline] |
| 1223 |
fn $method(self, other: T) -> Self::Output { |
| 1224 |
(*self).$method(other) |
| 1225 |
} |
| 1226 |
} |
| 1227 |
|
| 1228 |
impl<T: Float> $imp<&T> for &NotNan<T> { |
| 1229 |
type Output = NotNan<T>; |
| 1230 |
|
| 1231 |
#[inline] |
| 1232 |
fn $method(self, other: &T) -> Self::Output { |
| 1233 |
(*self).$method(*other) |
| 1234 |
} |
| 1235 |
} |
| 1236 |
|
| 1237 |
impl<T: Float + $assign_imp> $assign_imp<T> for NotNan<T> { |
| 1238 |
#[inline] |
| 1239 |
fn $assign_method(&mut self, other: T) { |
| 1240 |
*self = (*self).$method(other); |
| 1241 |
} |
| 1242 |
} |
| 1243 |
|
| 1244 |
impl<T: Float + $assign_imp> $assign_imp<&T> for NotNan<T> { |
| 1245 |
#[inline] |
| 1246 |
fn $assign_method(&mut self, other: &T) { |
| 1247 |
*self = (*self).$method(*other); |
| 1248 |
} |
| 1249 |
} |
| 1250 |
|
| 1251 |
impl<T: Float + $assign_imp> $assign_imp for NotNan<T> { |
| 1252 |
#[inline] |
| 1253 |
fn $assign_method(&mut self, other: Self) { |
| 1254 |
(*self).$assign_method(other.0); |
| 1255 |
} |
| 1256 |
} |
| 1257 |
|
| 1258 |
impl<T: Float + $assign_imp> $assign_imp<&Self> for NotNan<T> { |
| 1259 |
#[inline] |
| 1260 |
fn $assign_method(&mut self, other: &Self) { |
| 1261 |
(*self).$assign_method(other.0); |
| 1262 |
} |
| 1263 |
} |
| 1264 |
}; |
| 1265 |
} |
| 1266 |
|
| 1267 |
impl_not_nan_binop! {Add, add, AddAssign, add_assign} |
| 1268 |
impl_not_nan_binop! {Sub, sub, SubAssign, sub_assign} |
| 1269 |
impl_not_nan_binop! {Mul, mul, MulAssign, mul_assign} |
| 1270 |
impl_not_nan_binop! {Div, div, DivAssign, div_assign} |
| 1271 |
impl_not_nan_binop! {Rem, rem, RemAssign, rem_assign} |
| 1272 |
|
| 1273 |
impl<T: Float> Neg for NotNan<T> { |
| 1274 |
type Output = Self; |
| 1275 |
|
| 1276 |
#[inline] |
| 1277 |
fn neg(self) -> Self { |
| 1278 |
NotNan(-self.0) |
| 1279 |
} |
| 1280 |
} |
| 1281 |
|
| 1282 |
impl<T: Float> Neg for &NotNan<T> { |
| 1283 |
type Output = NotNan<T>; |
| 1284 |
|
| 1285 |
#[inline] |
| 1286 |
fn neg(self) -> Self::Output { |
| 1287 |
NotNan(-self.0) |
| 1288 |
} |
| 1289 |
} |
| 1290 |
|
| 1291 |
/// An error indicating an attempt to construct NotNan from a NaN |
| 1292 |
#[derive(Copy, Clone, PartialEq, Eq, Debug)] |
| 1293 |
pub struct FloatIsNan; |
| 1294 |
|
| 1295 |
#[cfg(feature = "std")] |
| 1296 |
impl Error for FloatIsNan { |
| 1297 |
fn description(&self) -> &str { |
| 1298 |
"NotNan constructed with NaN" |
| 1299 |
} |
| 1300 |
} |
| 1301 |
|
| 1302 |
impl fmt::Display for FloatIsNan { |
| 1303 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 1304 |
write!(f, "NotNan constructed with NaN") |
| 1305 |
} |
| 1306 |
} |
| 1307 |
|
| 1308 |
#[cfg(feature = "std")] |
| 1309 |
impl From<FloatIsNan> for std::io::Error { |
| 1310 |
#[inline] |
| 1311 |
fn from(e: FloatIsNan) -> std::io::Error { |
| 1312 |
std::io::Error::new(std::io::ErrorKind::InvalidInput, e) |
| 1313 |
} |
| 1314 |
} |
| 1315 |
|
| 1316 |
#[inline] |
| 1317 |
fn hash_float<F: Float, H: Hasher>(f: &F, state: &mut H) { |
| 1318 |
raw_double_bits(f).hash(state); |
| 1319 |
} |
| 1320 |
|
| 1321 |
#[inline] |
| 1322 |
fn raw_double_bits<F: Float>(f: &F) -> u64 { |
| 1323 |
if f.is_nan() { |
| 1324 |
return CANONICAL_NAN_BITS; |
| 1325 |
} |
| 1326 |
|
| 1327 |
let (man, exp, sign) = f.integer_decode(); |
| 1328 |
if man == 0 { |
| 1329 |
return CANONICAL_ZERO_BITS; |
| 1330 |
} |
| 1331 |
|
| 1332 |
let exp_u64 = exp as u16 as u64; |
| 1333 |
let sign_u64 = (sign > 0) as u64; |
| 1334 |
(man & MAN_MASK) | ((exp_u64 << 52) & EXP_MASK) | ((sign_u64 << 63) & SIGN_MASK) |
| 1335 |
} |
| 1336 |
|
| 1337 |
impl<T: Float> Zero for NotNan<T> { |
| 1338 |
#[inline] |
| 1339 |
fn zero() -> Self { |
| 1340 |
NotNan(T::zero()) |
| 1341 |
} |
| 1342 |
|
| 1343 |
#[inline] |
| 1344 |
fn is_zero(&self) -> bool { |
| 1345 |
self.0.is_zero() |
| 1346 |
} |
| 1347 |
} |
| 1348 |
|
| 1349 |
impl<T: Float> One for NotNan<T> { |
| 1350 |
#[inline] |
| 1351 |
fn one() -> Self { |
| 1352 |
NotNan(T::one()) |
| 1353 |
} |
| 1354 |
} |
| 1355 |
|
| 1356 |
impl<T: Float> Bounded for NotNan<T> { |
| 1357 |
#[inline] |
| 1358 |
fn min_value() -> Self { |
| 1359 |
NotNan(T::min_value()) |
| 1360 |
} |
| 1361 |
|
| 1362 |
#[inline] |
| 1363 |
fn max_value() -> Self { |
| 1364 |
NotNan(T::max_value()) |
| 1365 |
} |
| 1366 |
} |
| 1367 |
|
| 1368 |
impl<T: Float + FromStr> FromStr for NotNan<T> { |
| 1369 |
type Err = ParseNotNanError<T::Err>; |
| 1370 |
|
| 1371 |
/// Convert a &str to `NotNan`. Returns an error if the string fails to parse, |
| 1372 |
/// or if the resulting value is NaN |
| 1373 |
/// |
| 1374 |
/// ``` |
| 1375 |
/// use ordered_float::NotNan; |
| 1376 |
/// |
| 1377 |
/// assert!("-10".parse::<NotNan<f32>>().is_ok()); |
| 1378 |
/// assert!("abc".parse::<NotNan<f32>>().is_err()); |
| 1379 |
/// assert!("NaN".parse::<NotNan<f32>>().is_err()); |
| 1380 |
/// ``` |
| 1381 |
fn from_str(src: &str) -> Result<Self, Self::Err> { |
| 1382 |
src.parse() |
| 1383 |
.map_err(ParseNotNanError::ParseFloatError) |
| 1384 |
.and_then(|f| NotNan::new(f).map_err(|_| ParseNotNanError::IsNaN)) |
| 1385 |
} |
| 1386 |
} |
| 1387 |
|
| 1388 |
impl<T: Float + FromPrimitive> FromPrimitive for NotNan<T> { |
| 1389 |
fn from_i64(n: i64) -> Option<Self> { |
| 1390 |
T::from_i64(n).and_then(|n| NotNan::new(n).ok()) |
| 1391 |
} |
| 1392 |
fn from_u64(n: u64) -> Option<Self> { |
| 1393 |
T::from_u64(n).and_then(|n| NotNan::new(n).ok()) |
| 1394 |
} |
| 1395 |
|
| 1396 |
fn from_isize(n: isize) -> Option<Self> { |
| 1397 |
T::from_isize(n).and_then(|n| NotNan::new(n).ok()) |
| 1398 |
} |
| 1399 |
fn from_i8(n: i8) -> Option<Self> { |
| 1400 |
T::from_i8(n).and_then(|n| NotNan::new(n).ok()) |
| 1401 |
} |
| 1402 |
fn from_i16(n: i16) -> Option<Self> { |
| 1403 |
T::from_i16(n).and_then(|n| NotNan::new(n).ok()) |
| 1404 |
} |
| 1405 |
fn from_i32(n: i32) -> Option<Self> { |
| 1406 |
T::from_i32(n).and_then(|n| NotNan::new(n).ok()) |
| 1407 |
} |
| 1408 |
fn from_usize(n: usize) -> Option<Self> { |
| 1409 |
T::from_usize(n).and_then(|n| NotNan::new(n).ok()) |
| 1410 |
} |
| 1411 |
fn from_u8(n: u8) -> Option<Self> { |
| 1412 |
T::from_u8(n).and_then(|n| NotNan::new(n).ok()) |
| 1413 |
} |
| 1414 |
fn from_u16(n: u16) -> Option<Self> { |
| 1415 |
T::from_u16(n).and_then(|n| NotNan::new(n).ok()) |
| 1416 |
} |
| 1417 |
fn from_u32(n: u32) -> Option<Self> { |
| 1418 |
T::from_u32(n).and_then(|n| NotNan::new(n).ok()) |
| 1419 |
} |
| 1420 |
fn from_f32(n: f32) -> Option<Self> { |
| 1421 |
T::from_f32(n).and_then(|n| NotNan::new(n).ok()) |
| 1422 |
} |
| 1423 |
fn from_f64(n: f64) -> Option<Self> { |
| 1424 |
T::from_f64(n).and_then(|n| NotNan::new(n).ok()) |
| 1425 |
} |
| 1426 |
} |
| 1427 |
|
| 1428 |
impl<T: Float> ToPrimitive for NotNan<T> { |
| 1429 |
fn to_i64(&self) -> Option<i64> { |
| 1430 |
self.0.to_i64() |
| 1431 |
} |
| 1432 |
fn to_u64(&self) -> Option<u64> { |
| 1433 |
self.0.to_u64() |
| 1434 |
} |
| 1435 |
|
| 1436 |
fn to_isize(&self) -> Option<isize> { |
| 1437 |
self.0.to_isize() |
| 1438 |
} |
| 1439 |
fn to_i8(&self) -> Option<i8> { |
| 1440 |
self.0.to_i8() |
| 1441 |
} |
| 1442 |
fn to_i16(&self) -> Option<i16> { |
| 1443 |
self.0.to_i16() |
| 1444 |
} |
| 1445 |
fn to_i32(&self) -> Option<i32> { |
| 1446 |
self.0.to_i32() |
| 1447 |
} |
| 1448 |
fn to_usize(&self) -> Option<usize> { |
| 1449 |
self.0.to_usize() |
| 1450 |
} |
| 1451 |
fn to_u8(&self) -> Option<u8> { |
| 1452 |
self.0.to_u8() |
| 1453 |
} |
| 1454 |
fn to_u16(&self) -> Option<u16> { |
| 1455 |
self.0.to_u16() |
| 1456 |
} |
| 1457 |
fn to_u32(&self) -> Option<u32> { |
| 1458 |
self.0.to_u32() |
| 1459 |
} |
| 1460 |
fn to_f32(&self) -> Option<f32> { |
| 1461 |
self.0.to_f32() |
| 1462 |
} |
| 1463 |
fn to_f64(&self) -> Option<f64> { |
| 1464 |
self.0.to_f64() |
| 1465 |
} |
| 1466 |
} |
| 1467 |
|
| 1468 |
/// An error indicating a parse error from a string for `NotNan`. |
| 1469 |
#[derive(Copy, Clone, PartialEq, Eq, Debug)] |
| 1470 |
pub enum ParseNotNanError<E> { |
| 1471 |
/// A plain parse error from the underlying float type. |
| 1472 |
ParseFloatError(E), |
| 1473 |
/// The parsed float value resulted in a NaN. |
| 1474 |
IsNaN, |
| 1475 |
} |
| 1476 |
|
| 1477 |
#[cfg(feature = "std")] |
| 1478 |
impl<E: fmt::Debug + Error + 'static> Error for ParseNotNanError<E> { |
| 1479 |
fn description(&self) -> &str { |
| 1480 |
"Error parsing a not-NaN floating point value" |
| 1481 |
} |
| 1482 |
|
| 1483 |
fn source(&self) -> Option<&(dyn Error + 'static)> { |
| 1484 |
match self { |
| 1485 |
ParseNotNanError::ParseFloatError(e) => Some(e), |
| 1486 |
ParseNotNanError::IsNaN => None, |
| 1487 |
} |
| 1488 |
} |
| 1489 |
} |
| 1490 |
|
| 1491 |
impl<E: fmt::Display> fmt::Display for ParseNotNanError<E> { |
| 1492 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 1493 |
match self { |
| 1494 |
ParseNotNanError::ParseFloatError(e) => write!(f, "Parse error: {}", e), |
| 1495 |
ParseNotNanError::IsNaN => write!(f, "NotNan parser encounter a NaN"), |
| 1496 |
} |
| 1497 |
} |
| 1498 |
} |
| 1499 |
|
| 1500 |
impl<T: Float> Num for NotNan<T> { |
| 1501 |
type FromStrRadixErr = ParseNotNanError<T::FromStrRadixErr>; |
| 1502 |
|
| 1503 |
fn from_str_radix(src: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> { |
| 1504 |
T::from_str_radix(src, radix) |
| 1505 |
.map_err(ParseNotNanError::ParseFloatError) |
| 1506 |
.and_then(|n| NotNan::new(n).map_err(|_| ParseNotNanError::IsNaN)) |
| 1507 |
} |
| 1508 |
} |
| 1509 |
|
| 1510 |
impl<T: Float + Signed> Signed for NotNan<T> { |
| 1511 |
#[inline] |
| 1512 |
fn abs(&self) -> Self { |
| 1513 |
NotNan(self.0.abs()) |
| 1514 |
} |
| 1515 |
|
| 1516 |
fn abs_sub(&self, other: &Self) -> Self { |
| 1517 |
NotNan::new(Signed::abs_sub(&self.0, &other.0)).expect("Subtraction resulted in NaN") |
| 1518 |
} |
| 1519 |
|
| 1520 |
#[inline] |
| 1521 |
fn signum(&self) -> Self { |
| 1522 |
NotNan(self.0.signum()) |
| 1523 |
} |
| 1524 |
#[inline] |
| 1525 |
fn is_positive(&self) -> bool { |
| 1526 |
self.0.is_positive() |
| 1527 |
} |
| 1528 |
#[inline] |
| 1529 |
fn is_negative(&self) -> bool { |
| 1530 |
self.0.is_negative() |
| 1531 |
} |
| 1532 |
} |
| 1533 |
|
| 1534 |
impl<T: Float> NumCast for NotNan<T> { |
| 1535 |
fn from<F: ToPrimitive>(n: F) -> Option<Self> { |
| 1536 |
T::from(n).and_then(|n| NotNan::new(n).ok()) |
| 1537 |
} |
| 1538 |
} |
| 1539 |
|
| 1540 |
#[cfg(feature = "serde")] |
| 1541 |
mod impl_serde { |
| 1542 |
extern crate serde; |
| 1543 |
use self::serde::de::{Error, Unexpected}; |
| 1544 |
use self::serde::{Deserialize, Deserializer, Serialize, Serializer}; |
| 1545 |
use super::{NotNan, OrderedFloat}; |
| 1546 |
use core::f64; |
| 1547 |
#[cfg(not(feature = "std"))] |
| 1548 |
use num_traits::float::FloatCore as Float; |
| 1549 |
#[cfg(feature = "std")] |
| 1550 |
use num_traits::Float; |
| 1551 |
|
| 1552 |
#[cfg(test)] |
| 1553 |
extern crate serde_test; |
| 1554 |
#[cfg(test)] |
| 1555 |
use self::serde_test::{assert_de_tokens_error, assert_tokens, Token}; |
| 1556 |
|
| 1557 |
impl<T: Float + Serialize> Serialize for OrderedFloat<T> { |
| 1558 |
#[inline] |
| 1559 |
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { |
| 1560 |
self.0.serialize(s) |
| 1561 |
} |
| 1562 |
} |
| 1563 |
|
| 1564 |
impl<'de, T: Float + Deserialize<'de>> Deserialize<'de> for OrderedFloat<T> { |
| 1565 |
#[inline] |
| 1566 |
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { |
| 1567 |
T::deserialize(d).map(OrderedFloat) |
| 1568 |
} |
| 1569 |
} |
| 1570 |
|
| 1571 |
impl<T: Float + Serialize> Serialize for NotNan<T> { |
| 1572 |
#[inline] |
| 1573 |
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { |
| 1574 |
self.0.serialize(s) |
| 1575 |
} |
| 1576 |
} |
| 1577 |
|
| 1578 |
impl<'de, T: Float + Deserialize<'de>> Deserialize<'de> for NotNan<T> { |
| 1579 |
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { |
| 1580 |
let float = T::deserialize(d)?; |
| 1581 |
NotNan::new(float).map_err(|_| { |
| 1582 |
Error::invalid_value(Unexpected::Float(f64::NAN), &"float (but not NaN)") |
| 1583 |
}) |
| 1584 |
} |
| 1585 |
} |
| 1586 |
|
| 1587 |
#[test] |
| 1588 |
fn test_ordered_float() { |
| 1589 |
let float = OrderedFloat(1.0f64); |
| 1590 |
assert_tokens(&float, &[Token::F64(1.0)]); |
| 1591 |
} |
| 1592 |
|
| 1593 |
#[test] |
| 1594 |
fn test_not_nan() { |
| 1595 |
let float = NotNan(1.0f64); |
| 1596 |
assert_tokens(&float, &[Token::F64(1.0)]); |
| 1597 |
} |
| 1598 |
|
| 1599 |
#[test] |
| 1600 |
fn test_fail_on_nan() { |
| 1601 |
assert_de_tokens_error::<NotNan<f64>>( |
| 1602 |
&[Token::F64(f64::NAN)], |
| 1603 |
"invalid value: floating point `NaN`, expected float (but not NaN)", |
| 1604 |
); |
| 1605 |
} |
| 1606 |
} |
| 1607 |
|
| 1608 |
#[cfg(feature = "rkyv")] |
| 1609 |
mod impl_rkyv { |
| 1610 |
use super::{NotNan, OrderedFloat}; |
| 1611 |
#[cfg(not(feature = "std"))] |
| 1612 |
use num_traits::float::FloatCore as Float; |
| 1613 |
#[cfg(feature = "std")] |
| 1614 |
use num_traits::Float; |
| 1615 |
#[cfg(test)] |
| 1616 |
use rkyv::{archived_root, ser::Serializer}; |
| 1617 |
use rkyv::{from_archived, Archive, Deserialize, Fallible, Serialize}; |
| 1618 |
|
| 1619 |
#[cfg(test)] |
| 1620 |
type DefaultSerializer = rkyv::ser::serializers::CoreSerializer<16, 16>; |
| 1621 |
#[cfg(test)] |
| 1622 |
type DefaultDeserializer = rkyv::Infallible; |
| 1623 |
|
| 1624 |
impl<T: Float + Archive> Archive for OrderedFloat<T> { |
| 1625 |
type Archived = OrderedFloat<T>; |
| 1626 |
|
| 1627 |
type Resolver = (); |
| 1628 |
|
| 1629 |
unsafe fn resolve(&self, _: usize, _: Self::Resolver, out: *mut Self::Archived) { |
| 1630 |
out.write(*self); |
| 1631 |
} |
| 1632 |
} |
| 1633 |
|
| 1634 |
impl<T: Float + Serialize<S>, S: Fallible + ?Sized> Serialize<S> for OrderedFloat<T> { |
| 1635 |
fn serialize(&self, _: &mut S) -> Result<Self::Resolver, S::Error> { |
| 1636 |
Ok(()) |
| 1637 |
} |
| 1638 |
} |
| 1639 |
|
| 1640 |
impl<T: Float + Deserialize<T, D>, D: Fallible + ?Sized> Deserialize<OrderedFloat<T>, D> |
| 1641 |
for OrderedFloat<T> |
| 1642 |
{ |
| 1643 |
fn deserialize(&self, _: &mut D) -> Result<OrderedFloat<T>, D::Error> { |
| 1644 |
Ok(from_archived!(*self)) |
| 1645 |
} |
| 1646 |
} |
| 1647 |
|
| 1648 |
impl<T: Float + Archive> Archive for NotNan<T> { |
| 1649 |
type Archived = NotNan<T>; |
| 1650 |
|
| 1651 |
type Resolver = (); |
| 1652 |
|
| 1653 |
unsafe fn resolve(&self, _: usize, _: Self::Resolver, out: *mut Self::Archived) { |
| 1654 |
out.write(*self); |
| 1655 |
} |
| 1656 |
} |
| 1657 |
|
| 1658 |
impl<T: Float + Serialize<S>, S: Fallible + ?Sized> Serialize<S> for NotNan<T> { |
| 1659 |
fn serialize(&self, _: &mut S) -> Result<Self::Resolver, S::Error> { |
| 1660 |
Ok(()) |
| 1661 |
} |
| 1662 |
} |
| 1663 |
|
| 1664 |
impl<T: Float + Deserialize<T, D>, D: Fallible + ?Sized> Deserialize<NotNan<T>, D> for NotNan<T> { |
| 1665 |
fn deserialize(&self, _: &mut D) -> Result<NotNan<T>, D::Error> { |
| 1666 |
Ok(from_archived!(*self)) |
| 1667 |
} |
| 1668 |
} |
| 1669 |
|
| 1670 |
#[test] |
| 1671 |
fn test_ordered_float() { |
| 1672 |
let float = OrderedFloat(1.0f64); |
| 1673 |
let mut serializer = DefaultSerializer::default(); |
| 1674 |
serializer |
| 1675 |
.serialize_value(&float) |
| 1676 |
.expect("failed to archive value"); |
| 1677 |
let len = serializer.pos(); |
| 1678 |
let buffer = serializer.into_serializer().into_inner(); |
| 1679 |
|
| 1680 |
let archived_value = unsafe { archived_root::<OrderedFloat<f64>>(&buffer[0..len]) }; |
| 1681 |
assert_eq!(archived_value, &float); |
| 1682 |
let mut deserializer = DefaultDeserializer::default(); |
| 1683 |
let deser_float: OrderedFloat<f64> = archived_value.deserialize(&mut deserializer).unwrap(); |
| 1684 |
assert_eq!(deser_float, float); |
| 1685 |
} |
| 1686 |
|
| 1687 |
#[test] |
| 1688 |
fn test_not_nan() { |
| 1689 |
let float = NotNan(1.0f64); |
| 1690 |
let mut serializer = DefaultSerializer::default(); |
| 1691 |
serializer |
| 1692 |
.serialize_value(&float) |
| 1693 |
.expect("failed to archive value"); |
| 1694 |
let len = serializer.pos(); |
| 1695 |
let buffer = serializer.into_serializer().into_inner(); |
| 1696 |
|
| 1697 |
let archived_value = unsafe { archived_root::<NotNan<f64>>(&buffer[0..len]) }; |
| 1698 |
assert_eq!(archived_value, &float); |
| 1699 |
let mut deserializer = DefaultDeserializer::default(); |
| 1700 |
let deser_float: NotNan<f64> = archived_value.deserialize(&mut deserializer).unwrap(); |
| 1701 |
assert_eq!(deser_float, float); |
| 1702 |
} |
| 1703 |
} |
| 1704 |
|
| 1705 |
#[cfg(feature = "speedy")] |
| 1706 |
mod impl_speedy { |
| 1707 |
use super::{NotNan, OrderedFloat}; |
| 1708 |
use num_traits::Float; |
| 1709 |
use speedy::{Context, Readable, Reader, Writable, Writer}; |
| 1710 |
|
| 1711 |
impl<C, T> Writable<C> for OrderedFloat<T> |
| 1712 |
where |
| 1713 |
C: Context, |
| 1714 |
T: Writable<C>, |
| 1715 |
{ |
| 1716 |
fn write_to<W: ?Sized + Writer<C>>(&self, writer: &mut W) -> Result<(), C::Error> { |
| 1717 |
self.0.write_to(writer) |
| 1718 |
} |
| 1719 |
|
| 1720 |
fn bytes_needed(&self) -> Result<usize, C::Error> { |
| 1721 |
self.0.bytes_needed() |
| 1722 |
} |
| 1723 |
} |
| 1724 |
|
| 1725 |
impl<C, T> Writable<C> for NotNan<T> |
| 1726 |
where |
| 1727 |
C: Context, |
| 1728 |
T: Writable<C>, |
| 1729 |
{ |
| 1730 |
fn write_to<W: ?Sized + Writer<C>>(&self, writer: &mut W) -> Result<(), C::Error> { |
| 1731 |
self.0.write_to(writer) |
| 1732 |
} |
| 1733 |
|
| 1734 |
fn bytes_needed(&self) -> Result<usize, C::Error> { |
| 1735 |
self.0.bytes_needed() |
| 1736 |
} |
| 1737 |
} |
| 1738 |
|
| 1739 |
impl<'a, T, C: Context> Readable<'a, C> for OrderedFloat<T> |
| 1740 |
where |
| 1741 |
T: Readable<'a, C>, |
| 1742 |
{ |
| 1743 |
fn read_from<R: Reader<'a, C>>(reader: &mut R) -> Result<Self, C::Error> { |
| 1744 |
T::read_from(reader).map(OrderedFloat) |
| 1745 |
} |
| 1746 |
|
| 1747 |
fn minimum_bytes_needed() -> usize { |
| 1748 |
T::minimum_bytes_needed() |
| 1749 |
} |
| 1750 |
} |
| 1751 |
|
| 1752 |
impl<'a, T: Float, C: Context> Readable<'a, C> for NotNan<T> |
| 1753 |
where |
| 1754 |
T: Readable<'a, C>, |
| 1755 |
{ |
| 1756 |
fn read_from<R: Reader<'a, C>>(reader: &mut R) -> Result<Self, C::Error> { |
| 1757 |
let value: T = reader.read_value()?; |
| 1758 |
Self::new(value).map_err(|error| { |
| 1759 |
speedy::Error::custom(std::format!("failed to read NotNan: {}", error)).into() |
| 1760 |
}) |
| 1761 |
} |
| 1762 |
|
| 1763 |
fn minimum_bytes_needed() -> usize { |
| 1764 |
T::minimum_bytes_needed() |
| 1765 |
} |
| 1766 |
} |
| 1767 |
|
| 1768 |
#[test] |
| 1769 |
fn test_ordered_float() { |
| 1770 |
let float = OrderedFloat(1.0f64); |
| 1771 |
let buffer = float.write_to_vec().unwrap(); |
| 1772 |
let deser_float: OrderedFloat<f64> = OrderedFloat::read_from_buffer(&buffer).unwrap(); |
| 1773 |
assert_eq!(deser_float, float); |
| 1774 |
} |
| 1775 |
|
| 1776 |
#[test] |
| 1777 |
fn test_not_nan() { |
| 1778 |
let float = NotNan(1.0f64); |
| 1779 |
let buffer = float.write_to_vec().unwrap(); |
| 1780 |
let deser_float: NotNan<f64> = NotNan::read_from_buffer(&buffer).unwrap(); |
| 1781 |
assert_eq!(deser_float, float); |
| 1782 |
} |
| 1783 |
|
| 1784 |
#[test] |
| 1785 |
fn test_not_nan_with_nan() { |
| 1786 |
let nan_buf = f64::nan().write_to_vec().unwrap(); |
| 1787 |
let nan_err: Result<NotNan<f64>, _> = NotNan::read_from_buffer(&nan_buf); |
| 1788 |
assert!(nan_err.is_err()); |
| 1789 |
} |
| 1790 |
} |
| 1791 |
|
| 1792 |
#[cfg(all(feature = "std", feature = "schemars"))] |
| 1793 |
mod impl_schemars { |
| 1794 |
extern crate schemars; |
| 1795 |
use self::schemars::gen::SchemaGenerator; |
| 1796 |
use self::schemars::schema::{InstanceType, Schema, SchemaObject}; |
| 1797 |
use super::{NotNan, OrderedFloat}; |
| 1798 |
|
| 1799 |
macro_rules! primitive_float_impl { |
| 1800 |
($type:ty, $schema_name:literal) => { |
| 1801 |
impl schemars::JsonSchema for $type { |
| 1802 |
fn is_referenceable() -> bool { |
| 1803 |
false |
| 1804 |
} |
| 1805 |
|
| 1806 |
fn schema_name() -> std::string::String { |
| 1807 |
std::string::String::from($schema_name) |
| 1808 |
} |
| 1809 |
|
| 1810 |
fn json_schema(_: &mut SchemaGenerator) -> Schema { |
| 1811 |
SchemaObject { |
| 1812 |
instance_type: Some(InstanceType::Number.into()), |
| 1813 |
format: Some(std::string::String::from($schema_name)), |
| 1814 |
..Default::default() |
| 1815 |
} |
| 1816 |
.into() |
| 1817 |
} |
| 1818 |
} |
| 1819 |
}; |
| 1820 |
} |
| 1821 |
|
| 1822 |
primitive_float_impl!(OrderedFloat<f32>, "float"); |
| 1823 |
primitive_float_impl!(OrderedFloat<f64>, "double"); |
| 1824 |
primitive_float_impl!(NotNan<f32>, "float"); |
| 1825 |
primitive_float_impl!(NotNan<f64>, "double"); |
| 1826 |
|
| 1827 |
#[test] |
| 1828 |
fn schema_generation_does_not_panic_for_common_floats() { |
| 1829 |
{ |
| 1830 |
let schema = schemars::gen::SchemaGenerator::default() |
| 1831 |
.into_root_schema_for::<OrderedFloat<f32>>(); |
| 1832 |
assert_eq!( |
| 1833 |
schema.schema.instance_type, |
| 1834 |
Some(schemars::schema::SingleOrVec::Single(std::boxed::Box::new( |
| 1835 |
schemars::schema::InstanceType::Number |
| 1836 |
))) |
| 1837 |
); |
| 1838 |
assert_eq!( |
| 1839 |
schema.schema.metadata.unwrap().title.unwrap(), |
| 1840 |
std::string::String::from("float") |
| 1841 |
); |
| 1842 |
} |
| 1843 |
{ |
| 1844 |
let schema = schemars::gen::SchemaGenerator::default() |
| 1845 |
.into_root_schema_for::<OrderedFloat<f64>>(); |
| 1846 |
assert_eq!( |
| 1847 |
schema.schema.instance_type, |
| 1848 |
Some(schemars::schema::SingleOrVec::Single(std::boxed::Box::new( |
| 1849 |
schemars::schema::InstanceType::Number |
| 1850 |
))) |
| 1851 |
); |
| 1852 |
assert_eq!( |
| 1853 |
schema.schema.metadata.unwrap().title.unwrap(), |
| 1854 |
std::string::String::from("double") |
| 1855 |
); |
| 1856 |
} |
| 1857 |
{ |
| 1858 |
let schema = |
| 1859 |
schemars::gen::SchemaGenerator::default().into_root_schema_for::<NotNan<f32>>(); |
| 1860 |
assert_eq!( |
| 1861 |
schema.schema.instance_type, |
| 1862 |
Some(schemars::schema::SingleOrVec::Single(std::boxed::Box::new( |
| 1863 |
schemars::schema::InstanceType::Number |
| 1864 |
))) |
| 1865 |
); |
| 1866 |
assert_eq!( |
| 1867 |
schema.schema.metadata.unwrap().title.unwrap(), |
| 1868 |
std::string::String::from("float") |
| 1869 |
); |
| 1870 |
} |
| 1871 |
{ |
| 1872 |
let schema = |
| 1873 |
schemars::gen::SchemaGenerator::default().into_root_schema_for::<NotNan<f64>>(); |
| 1874 |
assert_eq!( |
| 1875 |
schema.schema.instance_type, |
| 1876 |
Some(schemars::schema::SingleOrVec::Single(std::boxed::Box::new( |
| 1877 |
schemars::schema::InstanceType::Number |
| 1878 |
))) |
| 1879 |
); |
| 1880 |
assert_eq!( |
| 1881 |
schema.schema.metadata.unwrap().title.unwrap(), |
| 1882 |
std::string::String::from("double") |
| 1883 |
); |
| 1884 |
} |
| 1885 |
} |
| 1886 |
#[test] |
| 1887 |
fn ordered_float_schema_match_primitive_schema() { |
| 1888 |
{ |
| 1889 |
let of_schema = schemars::gen::SchemaGenerator::default() |
| 1890 |
.into_root_schema_for::<OrderedFloat<f32>>(); |
| 1891 |
let prim_schema = |
| 1892 |
schemars::gen::SchemaGenerator::default().into_root_schema_for::<f32>(); |
| 1893 |
assert_eq!(of_schema, prim_schema); |
| 1894 |
} |
| 1895 |
{ |
| 1896 |
let of_schema = schemars::gen::SchemaGenerator::default() |
| 1897 |
.into_root_schema_for::<OrderedFloat<f64>>(); |
| 1898 |
let prim_schema = |
| 1899 |
schemars::gen::SchemaGenerator::default().into_root_schema_for::<f64>(); |
| 1900 |
assert_eq!(of_schema, prim_schema); |
| 1901 |
} |
| 1902 |
{ |
| 1903 |
let of_schema = |
| 1904 |
schemars::gen::SchemaGenerator::default().into_root_schema_for::<NotNan<f32>>(); |
| 1905 |
let prim_schema = |
| 1906 |
schemars::gen::SchemaGenerator::default().into_root_schema_for::<f32>(); |
| 1907 |
assert_eq!(of_schema, prim_schema); |
| 1908 |
} |
| 1909 |
{ |
| 1910 |
let of_schema = |
| 1911 |
schemars::gen::SchemaGenerator::default().into_root_schema_for::<NotNan<f64>>(); |
| 1912 |
let prim_schema = |
| 1913 |
schemars::gen::SchemaGenerator::default().into_root_schema_for::<f64>(); |
| 1914 |
assert_eq!(of_schema, prim_schema); |
| 1915 |
} |
| 1916 |
} |
| 1917 |
} |
| 1918 |
|
| 1919 |
#[cfg(feature = "rand")] |
| 1920 |
mod impl_rand { |
| 1921 |
use super::{NotNan, OrderedFloat}; |
| 1922 |
use rand::distributions::uniform::*; |
| 1923 |
use rand::distributions::{Distribution, Open01, OpenClosed01, Standard}; |
| 1924 |
use rand::Rng; |
| 1925 |
|
| 1926 |
macro_rules! impl_distribution { |
| 1927 |
($dist:ident, $($f:ty),+) => { |
| 1928 |
$( |
| 1929 |
impl Distribution<NotNan<$f>> for $dist { |
| 1930 |
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> NotNan<$f> { |
| 1931 |
// 'rand' never generates NaN values in the Standard, Open01, or |
| 1932 |
// OpenClosed01 distributions. Using 'new_unchecked' is therefore |
| 1933 |
// safe. |
| 1934 |
unsafe { NotNan::new_unchecked(self.sample(rng)) } |
| 1935 |
} |
| 1936 |
} |
| 1937 |
|
| 1938 |
impl Distribution<OrderedFloat<$f>> for $dist { |
| 1939 |
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> OrderedFloat<$f> { |
| 1940 |
OrderedFloat(self.sample(rng)) |
| 1941 |
} |
| 1942 |
} |
| 1943 |
)* |
| 1944 |
} |
| 1945 |
} |
| 1946 |
|
| 1947 |
impl_distribution! { Standard, f32, f64 } |
| 1948 |
impl_distribution! { Open01, f32, f64 } |
| 1949 |
impl_distribution! { OpenClosed01, f32, f64 } |
| 1950 |
|
| 1951 |
pub struct UniformNotNan<T>(UniformFloat<T>); |
| 1952 |
impl SampleUniform for NotNan<f32> { |
| 1953 |
type Sampler = UniformNotNan<f32>; |
| 1954 |
} |
| 1955 |
impl SampleUniform for NotNan<f64> { |
| 1956 |
type Sampler = UniformNotNan<f64>; |
| 1957 |
} |
| 1958 |
|
| 1959 |
pub struct UniformOrdered<T>(UniformFloat<T>); |
| 1960 |
impl SampleUniform for OrderedFloat<f32> { |
| 1961 |
type Sampler = UniformOrdered<f32>; |
| 1962 |
} |
| 1963 |
impl SampleUniform for OrderedFloat<f64> { |
| 1964 |
type Sampler = UniformOrdered<f64>; |
| 1965 |
} |
| 1966 |
|
| 1967 |
macro_rules! impl_uniform_sampler { |
| 1968 |
($f:ty) => { |
| 1969 |
impl UniformSampler for UniformNotNan<$f> { |
| 1970 |
type X = NotNan<$f>; |
| 1971 |
fn new<B1, B2>(low: B1, high: B2) -> Self |
| 1972 |
where |
| 1973 |
B1: SampleBorrow<Self::X> + Sized, |
| 1974 |
B2: SampleBorrow<Self::X> + Sized, |
| 1975 |
{ |
| 1976 |
UniformNotNan(UniformFloat::<$f>::new(low.borrow().0, high.borrow().0)) |
| 1977 |
} |
| 1978 |
fn new_inclusive<B1, B2>(low: B1, high: B2) -> Self |
| 1979 |
where |
| 1980 |
B1: SampleBorrow<Self::X> + Sized, |
| 1981 |
B2: SampleBorrow<Self::X> + Sized, |
| 1982 |
{ |
| 1983 |
UniformSampler::new(low, high) |
| 1984 |
} |
| 1985 |
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X { |
| 1986 |
// UniformFloat.sample() will never return NaN. |
| 1987 |
unsafe { NotNan::new_unchecked(self.0.sample(rng)) } |
| 1988 |
} |
| 1989 |
} |
| 1990 |
|
| 1991 |
impl UniformSampler for UniformOrdered<$f> { |
| 1992 |
type X = OrderedFloat<$f>; |
| 1993 |
fn new<B1, B2>(low: B1, high: B2) -> Self |
| 1994 |
where |
| 1995 |
B1: SampleBorrow<Self::X> + Sized, |
| 1996 |
B2: SampleBorrow<Self::X> + Sized, |
| 1997 |
{ |
| 1998 |
UniformOrdered(UniformFloat::<$f>::new(low.borrow().0, high.borrow().0)) |
| 1999 |
} |
| 2000 |
fn new_inclusive<B1, B2>(low: B1, high: B2) -> Self |
| 2001 |
where |
| 2002 |
B1: SampleBorrow<Self::X> + Sized, |
| 2003 |
B2: SampleBorrow<Self::X> + Sized, |
| 2004 |
{ |
| 2005 |
UniformSampler::new(low, high) |
| 2006 |
} |
| 2007 |
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X { |
| 2008 |
OrderedFloat(self.0.sample(rng)) |
| 2009 |
} |
| 2010 |
} |
| 2011 |
}; |
| 2012 |
} |
| 2013 |
|
| 2014 |
impl_uniform_sampler! { f32 } |
| 2015 |
impl_uniform_sampler! { f64 } |
| 2016 |
|
| 2017 |
#[cfg(all(test, feature = "randtest"))] |
| 2018 |
mod tests { |
| 2019 |
use super::*; |
| 2020 |
|
| 2021 |
fn sample_fuzz<T>() |
| 2022 |
where |
| 2023 |
Standard: Distribution<NotNan<T>>, |
| 2024 |
Open01: Distribution<NotNan<T>>, |
| 2025 |
OpenClosed01: Distribution<NotNan<T>>, |
| 2026 |
Standard: Distribution<OrderedFloat<T>>, |
| 2027 |
Open01: Distribution<OrderedFloat<T>>, |
| 2028 |
OpenClosed01: Distribution<OrderedFloat<T>>, |
| 2029 |
T: crate::Float, |
| 2030 |
{ |
| 2031 |
let mut rng = rand::thread_rng(); |
| 2032 |
let f1: NotNan<T> = rng.sample(Standard); |
| 2033 |
let f2: NotNan<T> = rng.sample(Open01); |
| 2034 |
let f3: NotNan<T> = rng.sample(OpenClosed01); |
| 2035 |
let _: OrderedFloat<T> = rng.sample(Standard); |
| 2036 |
let _: OrderedFloat<T> = rng.sample(Open01); |
| 2037 |
let _: OrderedFloat<T> = rng.sample(OpenClosed01); |
| 2038 |
assert!(!f1.into_inner().is_nan()); |
| 2039 |
assert!(!f2.into_inner().is_nan()); |
| 2040 |
assert!(!f3.into_inner().is_nan()); |
| 2041 |
} |
| 2042 |
|
| 2043 |
#[test] |
| 2044 |
fn sampling_f32_does_not_panic() { |
| 2045 |
sample_fuzz::<f32>(); |
| 2046 |
} |
| 2047 |
|
| 2048 |
#[test] |
| 2049 |
fn sampling_f64_does_not_panic() { |
| 2050 |
sample_fuzz::<f64>(); |
| 2051 |
} |
| 2052 |
|
| 2053 |
#[test] |
| 2054 |
#[should_panic] |
| 2055 |
fn uniform_sampling_panic_on_infinity_notnan() { |
| 2056 |
let (low, high) = ( |
| 2057 |
NotNan::new(0f64).unwrap(), |
| 2058 |
NotNan::new(core::f64::INFINITY).unwrap(), |
| 2059 |
); |
| 2060 |
let uniform = Uniform::new(low, high); |
| 2061 |
let _ = uniform.sample(&mut rand::thread_rng()); |
| 2062 |
} |
| 2063 |
|
| 2064 |
#[test] |
| 2065 |
#[should_panic] |
| 2066 |
fn uniform_sampling_panic_on_infinity_ordered() { |
| 2067 |
let (low, high) = (OrderedFloat(0f64), OrderedFloat(core::f64::INFINITY)); |
| 2068 |
let uniform = Uniform::new(low, high); |
| 2069 |
let _ = uniform.sample(&mut rand::thread_rng()); |
| 2070 |
} |
| 2071 |
|
| 2072 |
#[test] |
| 2073 |
#[should_panic] |
| 2074 |
fn uniform_sampling_panic_on_nan_ordered() { |
| 2075 |
let (low, high) = (OrderedFloat(0f64), OrderedFloat(core::f64::NAN)); |
| 2076 |
let uniform = Uniform::new(low, high); |
| 2077 |
let _ = uniform.sample(&mut rand::thread_rng()); |
| 2078 |
} |
| 2079 |
} |
| 2080 |
} |
| 2081 |
|
| 2082 |
#[cfg(feature = "proptest")] |
| 2083 |
mod impl_proptest { |
| 2084 |
use super::{NotNan, OrderedFloat}; |
| 2085 |
use proptest::arbitrary::{Arbitrary, StrategyFor}; |
| 2086 |
use proptest::num::{f32, f64}; |
| 2087 |
use proptest::strategy::{FilterMap, Map, Strategy}; |
| 2088 |
use std::convert::TryFrom; |
| 2089 |
|
| 2090 |
macro_rules! impl_arbitrary { |
| 2091 |
($($f:ident),+) => { |
| 2092 |
$( |
| 2093 |
impl Arbitrary for NotNan<$f> { |
| 2094 |
type Strategy = FilterMap<StrategyFor<$f>, fn(_: $f) -> Option<NotNan<$f>>>; |
| 2095 |
type Parameters = <$f as Arbitrary>::Parameters; |
| 2096 |
fn arbitrary_with(params: Self::Parameters) -> Self::Strategy { |
| 2097 |
<$f>::arbitrary_with(params) |
| 2098 |
.prop_filter_map("filter nan values", |f| NotNan::try_from(f).ok()) |
| 2099 |
} |
| 2100 |
} |
| 2101 |
|
| 2102 |
impl Arbitrary for OrderedFloat<$f> { |
| 2103 |
type Strategy = Map<StrategyFor<$f>, fn(_: $f) -> OrderedFloat<$f>>; |
| 2104 |
type Parameters = <$f as Arbitrary>::Parameters; |
| 2105 |
fn arbitrary_with(params: Self::Parameters) -> Self::Strategy { |
| 2106 |
<$f>::arbitrary_with(params).prop_map(|f| OrderedFloat::from(f)) |
| 2107 |
} |
| 2108 |
} |
| 2109 |
)* |
| 2110 |
} |
| 2111 |
} |
| 2112 |
impl_arbitrary! { f32, f64 } |
| 2113 |
} |
| 2114 |
|
| 2115 |
#[cfg(feature = "arbitrary")] |
| 2116 |
mod impl_arbitrary { |
| 2117 |
use super::{FloatIsNan, NotNan, OrderedFloat}; |
| 2118 |
use arbitrary::{Arbitrary, Unstructured}; |
| 2119 |
use num_traits::FromPrimitive; |
| 2120 |
|
| 2121 |
macro_rules! impl_arbitrary { |
| 2122 |
($($f:ident),+) => { |
| 2123 |
$( |
| 2124 |
impl<'a> Arbitrary<'a> for NotNan<$f> { |
| 2125 |
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> { |
| 2126 |
let float: $f = u.arbitrary()?; |
| 2127 |
match NotNan::new(float) { |
| 2128 |
Ok(notnan_value) => Ok(notnan_value), |
| 2129 |
Err(FloatIsNan) => { |
| 2130 |
// If our arbitrary float input was a NaN (encoded by exponent = max |
| 2131 |
// value), then replace it with a finite float, reusing the mantissa |
| 2132 |
// bits. |
| 2133 |
// |
| 2134 |
// This means the output is not uniformly distributed among all |
| 2135 |
// possible float values, but Arbitrary makes no promise that that |
| 2136 |
// is true. |
| 2137 |
// |
| 2138 |
// An alternative implementation would be to return an |
| 2139 |
// `arbitrary::Error`, but that is not as useful since it forces the |
| 2140 |
// caller to retry with new random/fuzzed data; and the precendent of |
| 2141 |
// `arbitrary`'s built-in implementations is to prefer the approach of |
| 2142 |
// mangling the input bits to fit. |
| 2143 |
|
| 2144 |
let (mantissa, _exponent, sign) = |
| 2145 |
num_traits::Float::integer_decode(float); |
| 2146 |
let revised_float = <$f>::from_i64( |
| 2147 |
i64::from(sign) * mantissa as i64 |
| 2148 |
).unwrap(); |
| 2149 |
|
| 2150 |
// If this unwrap() fails, then there is a bug in the above code. |
| 2151 |
Ok(NotNan::new(revised_float).unwrap()) |
| 2152 |
} |
| 2153 |
} |
| 2154 |
} |
| 2155 |
|
| 2156 |
fn size_hint(depth: usize) -> (usize, Option<usize>) { |
| 2157 |
<$f as Arbitrary>::size_hint(depth) |
| 2158 |
} |
| 2159 |
} |
| 2160 |
|
| 2161 |
impl<'a> Arbitrary<'a> for OrderedFloat<$f> { |
| 2162 |
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> { |
| 2163 |
let float: $f = u.arbitrary()?; |
| 2164 |
Ok(OrderedFloat::from(float)) |
| 2165 |
} |
| 2166 |
|
| 2167 |
fn size_hint(depth: usize) -> (usize, Option<usize>) { |
| 2168 |
<$f as Arbitrary>::size_hint(depth) |
| 2169 |
} |
| 2170 |
} |
| 2171 |
)* |
| 2172 |
} |
| 2173 |
} |
| 2174 |
impl_arbitrary! { f32, f64 } |
| 2175 |
} |
| 2176 |
|
| 2177 |
#[cfg(feature = "bytemuck")] |
| 2178 |
mod impl_bytemuck { |
| 2179 |
use super::{Float, NotNan, OrderedFloat}; |
| 2180 |
use bytemuck::{AnyBitPattern, CheckedBitPattern, NoUninit, Pod, Zeroable}; |
| 2181 |
|
| 2182 |
unsafe impl<T: Zeroable> Zeroable for OrderedFloat<T> {} |
| 2183 |
|
| 2184 |
// The zero bit pattern is indeed not a NaN bit pattern. |
| 2185 |
unsafe impl<T: Zeroable> Zeroable for NotNan<T> {} |
| 2186 |
|
| 2187 |
unsafe impl<T: Pod> Pod for OrderedFloat<T> {} |
| 2188 |
|
| 2189 |
// `NotNan<T>` can only implement `NoUninit` and not `Pod`, since not every bit pattern is |
| 2190 |
// valid (NaN bit patterns are invalid). `NoUninit` guarantees that we can read any bit pattern |
| 2191 |
// from the value, which is fine in this case. |
| 2192 |
unsafe impl<T: NoUninit> NoUninit for NotNan<T> {} |
| 2193 |
|
| 2194 |
unsafe impl<T: Float + AnyBitPattern> CheckedBitPattern for NotNan<T> { |
| 2195 |
type Bits = T; |
| 2196 |
|
| 2197 |
fn is_valid_bit_pattern(bits: &Self::Bits) -> bool { |
| 2198 |
!bits.is_nan() |
| 2199 |
} |
| 2200 |
} |
| 2201 |
|
| 2202 |
#[test] |
| 2203 |
fn test_not_nan_bit_pattern() { |
| 2204 |
use bytemuck::checked::{try_cast, CheckedCastError}; |
| 2205 |
|
| 2206 |
let nan = f64::NAN; |
| 2207 |
assert_eq!( |
| 2208 |
try_cast::<f64, NotNan<f64>>(nan), |
| 2209 |
Err(CheckedCastError::InvalidBitPattern), |
| 2210 |
); |
| 2211 |
|
| 2212 |
let pi = core::f64::consts::PI; |
| 2213 |
assert!(try_cast::<f64, NotNan<f64>>(pi).is_ok()); |
| 2214 |
} |
| 2215 |
} |