Skip to content

Commit e5cc919

Browse files
committed
Avoid extra memory allocations in core::str::from_cstr_len
1 parent 4eeb706 commit e5cc919

File tree

1 file changed

+10
-10
lines changed

1 file changed

+10
-10
lines changed

src/libcore/str.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -213,16 +213,16 @@ Function: from_cstr_len
213213
Create a Rust string from a C string of the given length
214214
*/
215215
unsafe fn from_cstr_len(cstr: sbuf, len: uint) -> str {
216-
let res = [];
217-
let start = cstr;
218-
let curr = start;
219-
let i = 0u;
220-
while i < len {
221-
vec::push(res, *curr);
222-
i += 1u;
223-
curr = ptr::offset(start, i);
224-
}
225-
ret from_bytes(res);
216+
let buf: [u8] = [];
217+
vec::reserve(buf, len + 1u);
218+
vec::as_buf(buf) {|b| ptr::memcpy(b, cstr, len); }
219+
vec::unsafe::set_len(buf, len);
220+
buf += [0u8];
221+
222+
assert is_utf8(buf);
223+
let s: str = ::unsafe::reinterpret_cast(buf);
224+
::unsafe::leak(buf);
225+
ret s;
226226
}
227227

228228
/*

0 commit comments

Comments
 (0)