From 61975f18f3d2198326b56685922b8aa7cf8377a5 Mon Sep 17 00:00:00 2001 From: multisn8 Date: Sat, 30 Apr 2022 22:09:29 +0200 Subject: [PATCH] Add lossy conversion for `NotNan` to `NotNan` (#109) --- src/lib.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index c797699..f3ac064 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -954,6 +954,18 @@ impl fmt::Display for NotNan { } } +impl NotNan { + /// Converts this [`NotNan`]`<`[`f64`]`>` to a [`NotNan`]`<`[`f32`]`>` while giving up on + /// precision, [using `roundTiesToEven` as rounding mode, yielding `Infinity` on + /// overflow](https://doc.rust-lang.org/reference/expressions/operator-expr.html#semantics). + pub fn as_f32(self) -> NotNan { + // This is not destroying invariants, as it is a pure rounding operation. The only two special + // cases are where f32 would be overflowing, then the operation yields Infinity, or where + // the input is already NaN, in which case the invariant is already broken elsewhere. + NotNan(self.0 as f32) + } +} + impl From> for f32 { #[inline] fn from(value: NotNan) -> Self {