Skip to content

Commit 61975f1

Browse files
Add lossy conversion for NotNan<f64> to NotNan<f32> (#109)
1 parent 158a3ae commit 61975f1

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

src/lib.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -954,6 +954,18 @@ impl<T: Float + fmt::Display> fmt::Display for NotNan<T> {
954954
}
955955
}
956956

957+
impl NotNan<f64> {
958+
/// Converts this [`NotNan`]`<`[`f64`]`>` to a [`NotNan`]`<`[`f32`]`>` while giving up on
959+
/// precision, [using `roundTiesToEven` as rounding mode, yielding `Infinity` on
960+
/// overflow](https://doc.rust-lang.org/reference/expressions/operator-expr.html#semantics).
961+
pub fn as_f32(self) -> NotNan<f32> {
962+
// This is not destroying invariants, as it is a pure rounding operation. The only two special
963+
// cases are where f32 would be overflowing, then the operation yields Infinity, or where
964+
// the input is already NaN, in which case the invariant is already broken elsewhere.
965+
NotNan(self.0 as f32)
966+
}
967+
}
968+
957969
impl From<NotNan<f32>> for f32 {
958970
#[inline]
959971
fn from(value: NotNan<f32>) -> Self {

0 commit comments

Comments
 (0)