Skip to content

Commit e87c62f

Browse files
committed
Modify String::push to reallocate more conservatively in case of the character's UTF-8 representation is bigger than 1 byte
1 parent c5d0e2a commit e87c62f

File tree

1 file changed

+17
-17
lines changed

1 file changed

+17
-17
lines changed

src/libcollections/string.rs

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -468,24 +468,24 @@ impl String {
468468
#[inline]
469469
#[stable(feature = "rust1", since = "1.0.0")]
470470
pub fn push(&mut self, ch: char) {
471-
if (ch as u32) < 0x80 {
472-
self.vec.push(ch as u8);
473-
return;
474-
}
475-
476-
let cur_len = self.len();
477-
// This may use up to 4 bytes.
478-
self.vec.reserve(4);
471+
match ch.len_utf8() {
472+
1 => self.vec.push(ch as u8),
473+
ch_len => {
474+
let cur_len = self.len();
475+
// This may use up to 4 bytes.
476+
self.vec.reserve(ch_len);
479477

480-
unsafe {
481-
// Attempt to not use an intermediate buffer by just pushing bytes
482-
// directly onto this string.
483-
let slice = slice::from_raw_parts_mut (
484-
self.vec.as_mut_ptr().offset(cur_len as isize),
485-
4
486-
);
487-
let used = ch.encode_utf8(slice).unwrap_or(0);
488-
self.vec.set_len(cur_len + used);
478+
unsafe {
479+
// Attempt to not use an intermediate buffer by just pushing bytes
480+
// directly onto this string.
481+
let slice = slice::from_raw_parts_mut (
482+
self.vec.as_mut_ptr().offset(cur_len as isize),
483+
ch_len
484+
);
485+
let used = ch.encode_utf8(slice).unwrap_or(0);
486+
self.vec.set_len(cur_len + used);
487+
}
488+
}
489489
}
490490
}
491491

0 commit comments

Comments
 (0)