Skip to content

Avoid extra memory allocations in core::str::from_cstr{,_len} #1827

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 13, 2012
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 13 additions & 15 deletions src/libcore/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,35 +194,33 @@ 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);
}

/*
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;
}

/*
Expand Down