Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,13 @@ pub(crate) fn ceil_f64(v: f64) -> f64 {
pub(crate) fn ceil_f64(v: f64) -> f64 {
debug_assert!(v >= 0.0);

Decimal::from_f64(v).unwrap().ceil().to_f64().unwrap()
// `Decimal::from_f64` returns `None` for non-finite values (e.g. infinity),
// so fall back to the input to mirror `f64::ceil` in the `std` path and
// avoid panicking.
match Decimal::from_f64(v) {
Some(d) => d.ceil().to_f64().unwrap_or(v),
None => v,
}
}

#[cfg(any(feature = "byte", feature = "bit"))]
Expand All @@ -54,7 +60,13 @@ pub(crate) fn ceil_f32(v: f32) -> f32 {
pub(crate) fn ceil_f32(v: f32) -> f32 {
debug_assert!(v >= 0.0);

Decimal::from_f32(v).unwrap().ceil().to_f32().unwrap()
// `Decimal::from_f32` returns `None` for non-finite values (e.g. infinity),
// so fall back to the input to mirror `f32::ceil` in the `std` path and
// avoid panicking.
match Decimal::from_f32(v) {
Some(d) => d.ceil().to_f32().unwrap_or(v),
None => v,
}
}

#[cfg(any(feature = "byte", feature = "bit"))]
Expand Down
10 changes: 10 additions & 0 deletions tests/byte.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,3 +170,13 @@ fn tests() {
assert_eq!(byte, serde_json::from_str::<Byte>(case.0).unwrap(), "{i}");
}
}

#[test]
fn from_non_finite_returns_none() {
// Non-finite inputs are "too large" and must return None instead of
// panicking, consistently across the `std` and `no_std` builds.
assert_eq!(Byte::from_f64(f64::INFINITY), None);
assert_eq!(Byte::from_f64(f64::NAN), None);
assert_eq!(Byte::from_f32(f32::INFINITY), None);
assert_eq!(Byte::from_f32(f32::NAN), None);
}