Merge pull request #1827 from uasi/from-cstr

Avoid extra memory allocations in core::str::from_cstr{,_len}
This commit is contained in:
Graydon Hoare 2012-02-13 11:29:58 -08:00
commit 9caca02dac

View file

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