Skip to content

Commit

Permalink
Avoid extra memory allocations in core::str::from_cstr_len
Browse files Browse the repository at this point in the history
  • Loading branch information
uasi committed Feb 13, 2012
1 parent 4eeb706 commit e5cc919
Showing 1 changed file with 10 additions and 10 deletions.
20 changes: 10 additions & 10 deletions src/libcore/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,16 +213,16 @@ 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);
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

0 comments on commit e5cc919

Please sign in to comment.