Skip to content

Commit 07940cd

Browse files
authored
format_int precision error handling (RustPython#3813)
1 parent 02a1d1d commit 07940cd

File tree

1 file changed

+22
-11
lines changed

1 file changed

+22
-11
lines changed

vm/src/format.rs

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,14 @@ impl FormatSpec {
427427
self.format_sign_and_align(&magnitude_string, sign_str)
428428
}
429429

430+
#[inline]
431+
fn format_int_radix(&self, magnitude: BigInt, radix: u32) -> Result<String, &'static str> {
432+
match self.precision {
433+
Some(_) => Err("Precision not allowed in integer format specifier"),
434+
None => Ok(magnitude.to_str_radix(radix)),
435+
}
436+
}
437+
430438
pub(crate) fn format_int(&self, num: &BigInt) -> Result<String, &'static str> {
431439
let magnitude = num.abs();
432440
let prefix = if self.alternate_form {
@@ -441,16 +449,19 @@ impl FormatSpec {
441449
""
442450
};
443451
let raw_magnitude_string_result: Result<String, &'static str> = match self.format_type {
444-
Some(FormatType::Binary) => Ok(magnitude.to_str_radix(2)),
445-
Some(FormatType::Decimal) => Ok(magnitude.to_str_radix(10)),
446-
Some(FormatType::Octal) => Ok(magnitude.to_str_radix(8)),
447-
Some(FormatType::HexLower) => Ok(magnitude.to_str_radix(16)),
448-
Some(FormatType::HexUpper) => {
449-
let mut result = magnitude.to_str_radix(16);
450-
result.make_ascii_uppercase();
451-
Ok(result)
452-
}
453-
Some(FormatType::Number) => Ok(magnitude.to_str_radix(10)),
452+
Some(FormatType::Binary) => self.format_int_radix(magnitude, 2),
453+
Some(FormatType::Decimal) => self.format_int_radix(magnitude, 10),
454+
Some(FormatType::Octal) => self.format_int_radix(magnitude, 8),
455+
Some(FormatType::HexLower) => self.format_int_radix(magnitude, 16),
456+
Some(FormatType::HexUpper) => match self.precision {
457+
Some(_) => Err("Precision not allowed in integer format specifier"),
458+
None => {
459+
let mut result = magnitude.to_str_radix(16);
460+
result.make_ascii_uppercase();
461+
Ok(result)
462+
}
463+
},
464+
Some(FormatType::Number) => self.format_int_radix(magnitude, 10),
454465
Some(FormatType::String) => Err("Unknown format code 's' for object of type 'int'"),
455466
Some(FormatType::Character) => Err("Unknown format code 'c' for object of type 'int'"),
456467
Some(FormatType::GeneralFormatUpper) => {
@@ -467,7 +478,7 @@ impl FormatSpec {
467478
Some(float) => return self.format_float(float),
468479
_ => Err("Unable to convert int to float"),
469480
},
470-
None => Ok(magnitude.to_str_radix(10)),
481+
None => self.format_int_radix(magnitude, 10),
471482
};
472483
let magnitude_string = format!(
473484
"{}{}",

0 commit comments

Comments
 (0)