diff --git a/common/src/cformat.rs b/common/src/cformat.rs index 4f691e267..2c1eda5c4 100644 --- a/common/src/cformat.rs +++ b/common/src/cformat.rs @@ -551,11 +551,9 @@ where if let Some(&(_, c)) = iter.peek() { if c.into() == '.' { iter.next().unwrap(); - return Ok(Some( - parse_quantity(iter)? - .map(CFormatPrecision::Quantity) - .unwrap_or(CFormatPrecision::Dot), - )); + let quantity = parse_quantity(iter)?; + let precision = quantity.map_or(CFormatPrecision::Dot, CFormatPrecision::Quantity); + return Ok(Some(precision)); } } Ok(None) diff --git a/vm/src/cformat.rs b/vm/src/cformat.rs index 41e780e4f..3148975a8 100644 --- a/vm/src/cformat.rs +++ b/vm/src/cformat.rs @@ -201,26 +201,34 @@ fn spec_format_string( } } +fn try_update_quantity_from_element( + vm: &VirtualMachine, + element: Option<&PyObjectRef>, +) -> PyResult { + match element { + Some(width_obj) => { + if let Some(i) = width_obj.payload::() { + let i = i.try_to_primitive::(vm)?.unsigned_abs(); + Ok(CFormatQuantity::Amount(i as usize)) + } else { + Err(vm.new_type_error("* wants int".to_owned())) + } + } + None => Err(vm.new_type_error("not enough arguments for format string".to_owned())), + } +} + fn try_update_quantity_from_tuple<'a, I: Iterator>( vm: &VirtualMachine, elements: &mut I, q: &mut Option, ) -> PyResult<()> { - match q { - Some(CFormatQuantity::FromValuesTuple) => match elements.next() { - Some(width_obj) => { - if let Some(i) = width_obj.payload::() { - let i = i.try_to_primitive::(vm)?.unsigned_abs(); - *q = Some(CFormatQuantity::Amount(i as usize)); - Ok(()) - } else { - Err(vm.new_type_error("* wants int".to_owned())) - } - } - None => Err(vm.new_type_error("not enough arguments for format string".to_owned())), - }, - _ => Ok(()), - } + let Some(CFormatQuantity::FromValuesTuple) = q else { + return Ok(()); + }; + let quantity = try_update_quantity_from_element(vm, elements.next())?; + *q = Some(quantity); + Ok(()) } fn try_update_precision_from_tuple<'a, I: Iterator>( @@ -228,24 +236,12 @@ fn try_update_precision_from_tuple<'a, I: Iterator>( elements: &mut I, p: &mut Option, ) -> PyResult<()> { - match p { - Some(CFormatPrecision::Quantity(CFormatQuantity::FromValuesTuple)) => match elements.next() - { - Some(width_obj) => { - if let Some(i) = width_obj.payload::() { - let i = i.try_to_primitive::(vm)?.unsigned_abs(); - *p = Some(CFormatPrecision::Quantity(CFormatQuantity::Amount( - i as usize, - ))); - Ok(()) - } else { - Err(vm.new_type_error("* wants int".to_owned())) - } - } - None => Err(vm.new_type_error("not enough arguments for format string".to_owned())), - }, - _ => Ok(()), - } + let Some(CFormatPrecision::Quantity(CFormatQuantity::FromValuesTuple)) = p else { + return Ok(()); + }; + let quantity = try_update_quantity_from_element(vm, elements.next())?; + *p = Some(CFormatPrecision::Quantity(quantity)); + Ok(()) } fn specifier_error(vm: &VirtualMachine) -> PyBaseExceptionRef {