Skip to content

Commit 9caca02

Browse files
committed
Merge pull request #1827 from uasi/from-cstr
Avoid extra memory allocations in core::str::from_cstr{,_len}
2 parents 94d4dcd + 4d788be commit 9caca02

File tree

1 file changed

+13
-15
lines changed

1 file changed

+13
-15
lines changed

src/libcore/str.rs

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -194,35 +194,33 @@ Function: from_cstr
194194
195195
Create a Rust string from a null-terminated C string
196196
*/
197-
unsafe fn from_cstr(cstr: sbuf) -> str {
198-
let res = [];
197+
fn from_cstr(cstr: sbuf) -> str unsafe {
199198
let start = cstr;
200199
let curr = start;
201200
let i = 0u;
202201
while *curr != 0u8 {
203-
vec::push(res, *curr);
204202
i += 1u;
205203
curr = ptr::offset(start, i);
206204
}
207-
ret from_bytes(res);
205+
ret from_cstr_len(cstr, i);
208206
}
209207

210208
/*
211209
Function: from_cstr_len
212210
213211
Create a Rust string from a C string of the given length
214212
*/
215-
unsafe fn from_cstr_len(cstr: sbuf, len: uint) -> str {
216-
let res = [];
217-
let start = cstr;
218-
let curr = start;
219-
let i = 0u;
220-
while i < len {
221-
vec::push(res, *curr);
222-
i += 1u;
223-
curr = ptr::offset(start, i);
224-
}
225-
ret from_bytes(res);
213+
fn from_cstr_len(cstr: sbuf, len: uint) -> str unsafe {
214+
let buf: [u8] = [];
215+
vec::reserve(buf, len + 1u);
216+
vec::as_buf(buf) {|b| ptr::memcpy(b, cstr, len); }
217+
vec::unsafe::set_len(buf, len);
218+
buf += [0u8];
219+
220+
assert is_utf8(buf);
221+
let s: str = ::unsafe::reinterpret_cast(buf);
222+
::unsafe::leak(buf);
223+
ret s;
226224
}
227225

228226
/*

0 commit comments

Comments
 (0)