Skip to content

Commit f84dd2e

Browse files
committed
Implement format validation
1 parent 2f94c07 commit f84dd2e

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

common/src/format.rs

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -608,7 +608,8 @@ impl FormatSpec {
608608
.map_err(|msg| msg.to_owned())
609609
}
610610

611-
pub fn format_string(&self, s: &BorrowedStr) -> Result<String, &'static str> {
611+
pub fn format_string(&self, s: &BorrowedStr) -> Result<String, String> {
612+
self.validate_format(FormatType::String)?;
612613
match self.format_type {
613614
Some(FormatType::String) | None => self
614615
.format_sign_and_align(s, "", FormatAlign::Left)
@@ -617,8 +618,15 @@ impl FormatSpec {
617618
value.truncate(precision);
618619
}
619620
value
620-
}),
621-
_ => Err("Unknown format code for object of type 'str'"),
621+
})
622+
.map_err(|msg| msg.to_owned()),
623+
_ => {
624+
let ch = char::from(self.format_type.as_ref().unwrap());
625+
Err(format!(
626+
"Unknown format code '{}' for object of type 'str'",
627+
ch
628+
))
629+
}
622630
}
623631
}
624632

vm/src/builtins/str.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -730,9 +730,11 @@ impl PyStr {
730730

731731
#[pymethod(name = "__format__")]
732732
fn format_str(&self, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
733-
FormatSpec::parse(spec.as_str())
734-
.and_then(|format_spec| format_spec.format_string(self.borrow()))
735-
.map_err(|err| vm.new_value_error(err.to_string()))
733+
let format_spec =
734+
FormatSpec::parse(spec.as_str()).map_err(|err| vm.new_value_error(err.to_string()))?;
735+
format_spec
736+
.format_string(self.borrow())
737+
.map_err(|msg| vm.new_value_error(msg))
736738
}
737739

738740
/// Return a titlecased version of the string where words start with an

0 commit comments

Comments
 (0)