Avoid extra memory allocations in core::str::from_cstr_len

This commit is contained in:
Tomoki Aonuma 2012-02-13 04:32:33 +09:00
parent 4eeb706e84
commit e5cc9193f8

View file

@ -213,16 +213,16 @@ Function: from_cstr_len
Create a Rust string from a C string of the given length Create a Rust string from a C string of the given length
*/ */
unsafe fn from_cstr_len(cstr: sbuf, len: uint) -> str { unsafe fn from_cstr_len(cstr: sbuf, len: uint) -> str {
let res = []; let buf: [u8] = [];
let start = cstr; vec::reserve(buf, len + 1u);
let curr = start; vec::as_buf(buf) {|b| ptr::memcpy(b, cstr, len); }
let i = 0u; vec::unsafe::set_len(buf, len);
while i < len { buf += [0u8];
vec::push(res, *curr);
i += 1u; assert is_utf8(buf);
curr = ptr::offset(start, i); let s: str = ::unsafe::reinterpret_cast(buf);
} ::unsafe::leak(buf);
ret from_bytes(res); ret s;
} }
/* /*