mirror of
https://github.com/RustPython/RustPython.git
synced 2026-10-28 18:59:04 +08:00
Implement format validation
This commit is contained in:
1 parent
2f94c07609
commit
f84dd2e84f
2 files changed
+16
-6
No files matched your search
+11
-3
@@ -608,7 +608,8 @@ impl FormatSpec {
|
||||
.map_err(|msg| msg.to_owned())
|
||||
}
|
||||
|
||||
pub fn format_string(&self, s: &BorrowedStr) -> Result<String, &'static str> {
|
||||
pub fn format_string(&self, s: &BorrowedStr) -> Result<String, String> {
|
||||
self.validate_format(FormatType::String)?;
|
||||
match self.format_type {
|
||||
Some(FormatType::String) | None => self
|
||||
.format_sign_and_align(s, "", FormatAlign::Left)
|
||||
@@ -617,8 +618,15 @@ impl FormatSpec {
|
||||
value.truncate(precision);
|
||||
}
|
||||
value
|
||||
}),
|
||||
_ => Err("Unknown format code for object of type 'str'"),
|
||||
})
|
||||
.map_err(|msg| msg.to_owned()),
|
||||
_ => {
|
||||
let ch = char::from(self.format_type.as_ref().unwrap());
|
||||
Err(format!(
|
||||
"Unknown format code '{}' for object of type 'str'",
|
||||
ch
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -730,9 +730,11 @@ impl PyStr {
|
||||
|
||||
#[pymethod(name = "__format__")]
|
||||
fn format_str(&self, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
|
||||
FormatSpec::parse(spec.as_str())
|
||||
.and_then(|format_spec| format_spec.format_string(self.borrow()))
|
||||
.map_err(|err| vm.new_value_error(err.to_string()))
|
||||
let format_spec =
|
||||
FormatSpec::parse(spec.as_str()).map_err(|err| vm.new_value_error(err.to_string()))?;
|
||||
format_spec
|
||||
.format_string(self.borrow())
|
||||
.map_err(|msg| vm.new_value_error(msg))
|
||||
}
|
||||
|
||||
/// Return a titlecased version of the string where words start with an
|
||||
|
||||
Reference in new issue
Block a user