From dc47941e689f71be0b1d8661196789eaf7e04937 Mon Sep 17 00:00:00 2001 From: Stiopa Koltsov Date: Tue, 10 Oct 2023 14:10:40 -0700 Subject: [PATCH] StarlarkStr::repr Summary: Format `&str` as `repr(s)`. Used later in D50105958. Reviewed By: JakobDegen Differential Revision: D50104777 fbshipit-source-id: 713fe0b7a6c233ee72425c3c276f3ecca9403e48 --- starlark/src/values/types/string/mod.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/starlark/src/values/types/string/mod.rs b/starlark/src/values/types/string/mod.rs index 3d93ae8c1..bea3c3b68 100644 --- a/starlark/src/values/types/string/mod.rs +++ b/starlark/src/values/types/string/mod.rs @@ -195,6 +195,13 @@ impl StarlarkStr { pub(crate) fn offset_of_content() -> usize { memoffset::offset_of!(StarlarkStrN<0>, body) } + + /// Format a Rust string like `repr(s)`. + pub fn repr(s: &str) -> String { + let mut buffer = String::new(); + string_repr(s, &mut buffer); + buffer + } } /// How to hash a string in a way that is compatible with Value @@ -208,9 +215,7 @@ impl Display for StarlarkStr { // We could either accumulate straight into the buffer (can't preallocate, virtual call on each character) // or accumulate into a String buffer first. Not sure which is faster, but string buffer lets us // share code with collect_repr more easily. - let mut buffer = String::new(); - string_repr(self.as_str(), &mut buffer); - f.write_str(&buffer) + f.write_str(&StarlarkStr::repr(self.as_str())) } }