Skip to content

Commit ad5c4ed

Browse files
committed
Make push_str overallocate. Use it in some places that were still doing +=.
1 parent 9728d14 commit ad5c4ed

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

src/libcore/str.rs

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ export
2626
unpack_slice,
2727

2828
// Adding things to and removing things from a string
29+
push_str_no_overallocate,
2930
push_str,
3031
push_char,
3132
pop_char,
@@ -235,13 +236,29 @@ pure fn from_chars(chs: &[const char]) -> str {
235236
ret buf;
236237
}
237238

239+
/// Appends a string slice to the back of a string, without overallocating
240+
#[inline(always)]
241+
fn push_str_no_overallocate(&lhs: str, rhs: str/&) {
242+
unsafe {
243+
let llen = lhs.len();
244+
let rlen = rhs.len();
245+
reserve(lhs, llen + rlen);
246+
do as_buf(lhs) |lbuf| {
247+
do unpack_slice(rhs) |rbuf, _rlen| {
248+
let dst = ptr::offset(lbuf, llen);
249+
ptr::memcpy(dst, rbuf, rlen);
250+
}
251+
}
252+
unsafe::set_len(lhs, llen + rlen);
253+
}
254+
}
238255
/// Appends a string slice to the back of a string
239256
#[inline(always)]
240257
fn push_str(&lhs: str, rhs: str/&) {
241258
unsafe {
242259
let llen = lhs.len();
243260
let rlen = rhs.len();
244-
reserve(lhs, llen + rlen);
261+
reserve_at_least(lhs, llen + rlen);
245262
do as_buf(lhs) |lbuf| {
246263
do unpack_slice(rhs) |rbuf, _rlen| {
247264
let dst = ptr::offset(lbuf, llen);
@@ -257,7 +274,7 @@ fn push_str(&lhs: str, rhs: str/&) {
257274
pure fn append(+lhs: str, rhs: str/&) -> str {
258275
let mut v <- lhs;
259276
unchecked {
260-
push_str(v, rhs);
277+
push_str_no_overallocate(v, rhs);
261278
}
262279
ret v;
263280
}

src/libstd/sha1.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ mod tests {
265265
fn a_million_letter_a() -> str {
266266
let mut i = 0;
267267
let mut rs = "";
268-
while i < 100000 { rs += "aaaaaaaaaa"; i += 1; }
268+
while i < 100000 { str::push_str(rs, "aaaaaaaaaa"); i += 1; }
269269
ret rs;
270270
}
271271
// Test messages from FIPS 180-1

0 commit comments

Comments
 (0)