From c9bff92c1fc750bc6e71af15ecb9498cb75b1cf5 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Mon, 27 Mar 2023 09:47:21 -0700 Subject: [PATCH] Fix PartialEq between Value and f32 Caught by test_partialeq_number: thread 'test_partialeq_number' panicked at 'assertion failed: `(left == right)` left: `-3.4028235e38`, right: `Number(-3.4028235e38)`', tests/test.rs:2033:5 --- src/number.rs | 11 +++++++++++ src/value/partial_eq.rs | 10 +++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/number.rs b/src/number.rs index ca2fd55fd..5ecbde873 100644 --- a/src/number.rs +++ b/src/number.rs @@ -279,6 +279,17 @@ impl Number { } } + pub(crate) fn as_f32(&self) -> Option { + #[cfg(not(feature = "arbitrary_precision"))] + match self.n { + N::PosInt(n) => Some(n as f32), + N::NegInt(n) => Some(n as f32), + N::Float(n) => Some(n as f32), + } + #[cfg(feature = "arbitrary_precision")] + self.n.parse::().ok().filter(|float| float.is_finite()) + } + pub(crate) fn from_f32(f: f32) -> Option { if f.is_finite() { let n = { diff --git a/src/value/partial_eq.rs b/src/value/partial_eq.rs index b4ef84c4f..6b2e350b6 100644 --- a/src/value/partial_eq.rs +++ b/src/value/partial_eq.rs @@ -9,6 +9,13 @@ fn eq_u64(value: &Value, other: u64) -> bool { value.as_u64().map_or(false, |i| i == other) } +fn eq_f32(value: &Value, other: f32) -> bool { + match value { + Value::Number(n) => n.as_f32().map_or(false, |i| i == other), + _ => false, + } +} + fn eq_f64(value: &Value, other: f64) -> bool { value.as_f64().map_or(false, |i| i == other) } @@ -90,6 +97,7 @@ macro_rules! partialeq_numeric { partialeq_numeric! { eq_i64[i8 i16 i32 i64 isize] eq_u64[u8 u16 u32 u64 usize] - eq_f64[f32 f64] + eq_f32[f32] + eq_f64[f64] eq_bool[bool] }