Skip to content

Commit

Permalink
Fix PartialEq between Value and f32
Browse files Browse the repository at this point in the history
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
  • Loading branch information
dtolnay committed Mar 27, 2023
1 parent 06f3443 commit c9bff92
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/number.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,17 @@ impl Number {
}
}

pub(crate) fn as_f32(&self) -> Option<f32> {
#[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::<f32>().ok().filter(|float| float.is_finite())
}

pub(crate) fn from_f32(f: f32) -> Option<Number> {
if f.is_finite() {
let n = {
Expand Down
10 changes: 9 additions & 1 deletion src/value/partial_eq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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]
}

0 comments on commit c9bff92

Please sign in to comment.