Skip to content

Commit

Permalink
Modify String::push to reallocate more conservatively in case of the …
Browse files Browse the repository at this point in the history
…character's UTF-8 representation is bigger than 1 byte
  • Loading branch information
pmarcelll committed Jun 10, 2015
1 parent c5d0e2a commit e87c62f
Showing 1 changed file with 17 additions and 17 deletions.
34 changes: 17 additions & 17 deletions src/libcollections/string.rs
Expand Up @@ -468,24 +468,24 @@ impl String {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn push(&mut self, ch: char) {
if (ch as u32) < 0x80 {
self.vec.push(ch as u8);
return;
}

let cur_len = self.len();
// This may use up to 4 bytes.
self.vec.reserve(4);
match ch.len_utf8() {
1 => self.vec.push(ch as u8),
ch_len => {
let cur_len = self.len();
// This may use up to 4 bytes.
self.vec.reserve(ch_len);

unsafe {
// Attempt to not use an intermediate buffer by just pushing bytes
// directly onto this string.
let slice = slice::from_raw_parts_mut (
self.vec.as_mut_ptr().offset(cur_len as isize),
4
);
let used = ch.encode_utf8(slice).unwrap_or(0);
self.vec.set_len(cur_len + used);
unsafe {
// Attempt to not use an intermediate buffer by just pushing bytes
// directly onto this string.
let slice = slice::from_raw_parts_mut (
self.vec.as_mut_ptr().offset(cur_len as isize),
ch_len
);
let used = ch.encode_utf8(slice).unwrap_or(0);
self.vec.set_len(cur_len + used);
}
}
}
}

Expand Down

0 comments on commit e87c62f

Please sign in to comment.