Skip to content

Commit 02919c8

Browse files
committed
Replace ifs followed by unwrap with if-lets in impl From<Value>s
The changes in this commit take advantage of the [if-let scope] change in the Rust 2024 edition which enables code which independently borrows the same value in different if-else arms. [if-let scope]: https://doc.rust-lang.org/edition-guide/rust-2024/temporary-if-let-scope.html
1 parent ae44304 commit 02919c8

1 file changed

Lines changed: 12 additions & 14 deletions

File tree

src/types/value.rs

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -124,17 +124,17 @@ impl From<Value> for serde_json::Value {
124124
// those values.
125125
return Self::String(n.to_string());
126126
}
127-
let jn = if n.is_i64() {
127+
let jn = if let Some(num) = n.as_i64() {
128128
// While the lint is enabled generally, we don't care if we lose some precision
129129
// here. If this turns out to be a real problem, we can enable serde_json's
130130
// arbitrary precision numbers feature.
131131
#[allow(clippy::cast_precision_loss)]
132-
serde_json::Number::from_f64(n.as_i64().unwrap() as f64).unwrap()
133-
} else if n.is_u64() {
132+
serde_json::Number::from_f64(num as f64).unwrap()
133+
} else if let Some(num) = n.as_u64() {
134134
#[allow(clippy::cast_precision_loss)]
135-
serde_json::Number::from_f64(n.as_u64().unwrap() as f64).unwrap()
136-
} else if n.is_f64() {
137-
serde_json::Number::from_f64(n.as_f64().unwrap()).unwrap()
135+
serde_json::Number::from_f64(num as f64).unwrap()
136+
} else if let Some(num) = n.as_f64() {
137+
serde_json::Number::from_f64(num).unwrap()
138138
} else {
139139
unreachable!(
140140
"Serializing Number to JSON: {} is neither NaN, inf, or representable as i64, u64, or f64?",
@@ -470,14 +470,12 @@ impl Value {
470470
Value::Literal(s) | Value::String(s) => s.into_pyobject(py)?.into_any(),
471471
Value::Bool(b) => pyo3::types::PyBool::new(py, *b).to_owned().into_any(),
472472
Value::Number(n) => {
473-
if n.is_i64() {
474-
// NOTE(sg): We allow the missing panics doc because we already checked that
475-
// `as_i64()` can't panic here.
476-
n.as_i64().unwrap().into_pyobject(py)?.into_any()
477-
} else if n.is_u64() {
478-
n.as_u64().unwrap().into_pyobject(py)?.into_any()
479-
} else if n.is_f64() {
480-
n.as_f64().unwrap().into_pyobject(py)?.into_any()
473+
if let Some(num) = n.as_i64() {
474+
num.into_pyobject(py)?.into_any()
475+
} else if let Some(num) = n.as_u64() {
476+
num.into_pyobject(py)?.into_any()
477+
} else if let Some(num) = n.as_f64() {
478+
num.into_pyobject(py)?.into_any()
481479
} else {
482480
Option::<()>::None.into_pyobject(py)?.into_any()
483481
}

0 commit comments

Comments
 (0)