Format d bool support (#4948)

This commit is contained in:
Christopher Gambrell
2023-04-30 03:29:04 -04:00
committed by GitHub
parent f4b9bdfb29
commit fa79055821
2 changed files with 20 additions and 7 deletions

View File

@@ -416,6 +416,19 @@ impl FormatSpec {
}
}
pub fn format_bool(&self, input: bool) -> Result<String, FormatSpecError> {
let x = u8::from(input);
let result: Result<String, FormatSpecError> = match &self.format_type {
Some(FormatType::Decimal) => Ok(x.to_string()),
None => {
let first_letter = (input.to_string().as_bytes()[0] as char).to_uppercase();
Ok(first_letter.collect::<String>() + &input.to_string()[1..])
}
_ => Err(FormatSpecError::InvalidFormatSpecifier),
};
result
}
pub fn format_float(&self, num: f64) -> Result<String, FormatSpecError> {
self.validate_format(FormatType::FixedPoint(Case::Lower))?;
let precision = self.precision.unwrap_or(6);

View File

@@ -1,7 +1,8 @@
use super::{PyInt, PyStrRef, PyType, PyTypeRef};
use crate::{
class::PyClassImpl,
convert::{ToPyObject, ToPyResult},
common::format::FormatSpec,
convert::{IntoPyException, ToPyObject, ToPyResult},
function::OptionalArg,
identifier,
protocol::PyNumberMethods,
@@ -110,12 +111,11 @@ impl Constructor for PyBool {
#[pyclass(with(Constructor, AsNumber, Representable))]
impl PyBool {
#[pymethod(magic)]
fn format(obj: PyObjectRef, format_spec: PyStrRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
if format_spec.is_empty() {
obj.str(vm)
} else {
Err(vm.new_type_error("unsupported format string passed to bool.__format__".to_owned()))
}
fn format(obj: PyObjectRef, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
let new_bool = obj.try_to_bool(vm)?;
FormatSpec::parse(spec.as_str())
.and_then(|format_spec| format_spec.format_bool(new_bool))
.map_err(|err| err.into_pyexception(vm))
}
#[pymethod(name = "__ror__")]