From 987d520221ca0e8349441a72a0af8e68015aa239 Mon Sep 17 00:00:00 2001 From: Matt Mastracci Date: Fri, 1 Sep 2023 08:54:52 -0400 Subject: [PATCH] fix: don't allocate for zero-length strings (#1309) --- src/string.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/string.rs b/src/string.rs index 965187fea7..0fce1fbc6b 100644 --- a/src/string.rs +++ b/src/string.rs @@ -552,9 +552,15 @@ impl String { &self, scope: &mut Isolate, ) -> std::string::String { - let len_utf8 = self.utf8_length(scope); let len_utf16 = self.length(); + // No need to allocate or do any work for zero-length strings + if len_utf16 == 0 { + return std::string::String::new(); + } + + let len_utf8 = self.utf8_length(scope); + // If len_utf8 == len_utf16 and the string is one-byte, we can take the fast memcpy path. This is true iff the // string is 100% 7-bit ASCII. if self.is_onebyte() && len_utf8 == len_utf16 { @@ -612,9 +618,15 @@ impl String { scope: &mut Isolate, buffer: &'a mut [MaybeUninit; N], ) -> Cow<'a, str> { + let len_utf16 = self.length(); + + // No need to allocate or do any work for zero-length strings + if len_utf16 == 0 { + return "".into(); + } + // TODO(mmastrac): Ideally we should be able to access the string's internal representation let len_utf8 = self.utf8_length(scope); - let len_utf16 = self.length(); // If len_utf8 == len_utf16 and the string is one-byte, we can take the fast memcpy path. This is true iff the // string is 100% 7-bit ASCII.