From e5cc9193f8b91f8d21621b452e45d0e37c200757 Mon Sep 17 00:00:00 2001 From: Tomoki Aonuma Date: Mon, 13 Feb 2012 04:32:33 +0900 Subject: [PATCH] Avoid extra memory allocations in core::str::from_cstr_len --- src/libcore/str.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/libcore/str.rs b/src/libcore/str.rs index 5d39fb72b7e..d1a606d5177 100644 --- a/src/libcore/str.rs +++ b/src/libcore/str.rs @@ -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; } /*