Skip to content

Commit f24df1f

Browse files
committed
Better repr construction for string
1 parent 8370d03 commit f24df1f

2 files changed

Lines changed: 22 additions & 8 deletions

File tree

codegen/table.rs

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -627,6 +627,13 @@ impl<'a> TableBindGenerator<'a> {
627627
.fields
628628
.iter()
629629
.map(|(field_name, field_info)| match &field_info.type_.kind {
630+
TypeKind::String => {
631+
if matches!(field_info.assign_mode, AssignMode::Optional) {
632+
format!("{field_name}={{}}")
633+
} else {
634+
format!("{field_name}={{:?}}")
635+
}
636+
}
630637
TypeKind::Vector(inner_type) => match inner_type.kind {
631638
TypeKind::SimpleType(SimpleType::Integer(IntegerType::U8)) => {
632639
format!("{field_name}=bytes([{{}}])")
@@ -679,24 +686,23 @@ impl<'a> TableBindGenerator<'a> {
679686
write_fmt!(self, " self.{field_name}.__repr__(),")
680687
}
681688
},
682-
TypeKind::String => match field_info.assign_mode {
683-
AssignMode::Optional => {
689+
TypeKind::String => {
690+
if matches!(field_info.assign_mode, AssignMode::Optional) {
684691
write_fmt!(self, " self.{field_name}");
685692
write_str!(self, " .as_ref()");
686693
write_str!(self, " .map_or_else(crate::none_str, |i| {");
687694
write_str!(
688695
self,
689-
" format!(\"{:?}\", i.to_str(py).unwrap().to_string())"
696+
" crate::format_string(i.to_str(py).unwrap().to_string())"
690697
);
691698
write_str!(self, " }),");
692-
}
693-
_ => {
699+
} else {
694700
write_fmt!(
695701
self,
696-
" format!(\"{{:?}}\", self.{field_name}.bind(py).to_cow().unwrap()),"
702+
" self.{field_name}.bind(py).to_cow().unwrap(),"
697703
);
698704
}
699-
},
705+
}
700706
TypeKind::Table(_) => match field_info.assign_mode {
701707
AssignMode::Optional => {
702708
write_fmt!(self, " self.{field_name}");
@@ -758,7 +764,7 @@ impl<'a> TableBindGenerator<'a> {
758764
write_str!(self, " .iter()");
759765
write_str!(
760766
self,
761-
" .map(|s| format!(\"{:?}\", crate::from_pystring_into(s)))"
767+
" .map(|s| crate::format_string(crate::from_pystring_into(s)))"
762768
);
763769
}
764770
TypeKind::Table(idx) => {

src/lib.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,14 @@ fn from_pystring_into(obj: Bound<PyAny>) -> String {
9090
.to_string()
9191
}
9292

93+
#[inline(never)]
94+
fn format_string(mut string: String) -> String {
95+
const PYTHON_STRING_CHAR: char = '\"';
96+
string.insert(0, PYTHON_STRING_CHAR);
97+
string.push(PYTHON_STRING_CHAR);
98+
string
99+
}
100+
93101
pub trait PyDefault: Sized + PyClass {
94102
fn py_default(py: Python) -> Py<Self>;
95103
}

0 commit comments

Comments
 (0)