Skip to content

Commit

Permalink
fix: don't allocate for zero-length strings (#1309)
Browse files Browse the repository at this point in the history
  • Loading branch information
mmastrac authored Sep 1, 2023
1 parent aa203e0 commit 987d520
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -612,9 +618,15 @@ impl String {
scope: &mut Isolate,
buffer: &'a mut [MaybeUninit<u8>; 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.
Expand Down

0 comments on commit 987d520

Please sign in to comment.