Skip to content

Commit b1ee87f

Browse files
committed
std: simplify vec.with_c_str
This also fixes a bug in `vec.with_c_str_unchecked` where we were not calling `.to_c_str_unchecked()` for long strings.
1 parent 2d87803 commit b1ee87f

File tree

1 file changed

+20
-28
lines changed

1 file changed

+20
-28
lines changed

src/libstd/c_str.rs

Lines changed: 20 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ use ptr;
7171
use str::StrSlice;
7272
use str;
7373
use vec::{CopyableVector, ImmutableVector, MutableVector};
74+
use vec;
7475
use unstable::intrinsics;
7576

7677
/// Resolution options for the `null_byte` condition
@@ -283,41 +284,32 @@ impl<'self> ToCStr for &'self [u8] {
283284
}
284285

285286
fn with_c_str<T>(&self, f: &fn(*libc::c_char) -> T) -> T {
286-
if self.len() < BUF_LEN {
287-
do self.as_imm_buf |self_buf, self_len| {
288-
unsafe {
289-
let mut buf: [u8, .. BUF_LEN] = intrinsics::uninit();
290-
291-
do buf.as_mut_buf |buf, _| {
292-
ptr::copy_memory(buf, self_buf, self_len);
293-
*ptr::mut_offset(buf, self_len as int) = 0;
294-
295-
check_for_null(*self, buf as *mut libc::c_char);
296-
297-
f(buf as *libc::c_char)
298-
}
299-
}
300-
}
301-
} else {
302-
self.to_c_str().with_ref(f)
303-
}
287+
unsafe { with_c_str(*self, true, f) }
304288
}
305289

306290
unsafe fn with_c_str_unchecked<T>(&self, f: &fn(*libc::c_char) -> T) -> T {
307-
if self.len() < BUF_LEN {
308-
do self.as_imm_buf |self_buf, self_len| {
309-
let mut buf: [u8, .. BUF_LEN] = intrinsics::uninit();
291+
with_c_str(*self, false, f)
292+
}
293+
}
310294

311-
do buf.as_mut_buf |buf, _| {
312-
ptr::copy_memory(buf, self_buf, self_len);
313-
*ptr::mut_offset(buf, self_len as int) = 0;
295+
// Unsafe function that handles possibly copying the &[u8] into a stack array.
296+
unsafe fn with_c_str<T>(v: &[u8], checked: bool, f: &fn(*libc::c_char) -> T) -> T {
297+
if v.len() < BUF_LEN {
298+
let mut buf: [u8, .. BUF_LEN] = intrinsics::uninit();
299+
vec::bytes::copy_memory(buf, v, v.len());
300+
buf[v.len()] = 0;
314301

315-
f(buf as *libc::c_char)
316-
}
302+
do buf.as_mut_buf |buf, _| {
303+
if checked {
304+
check_for_null(v, buf as *mut libc::c_char);
317305
}
318-
} else {
319-
self.to_c_str().with_ref(f)
306+
307+
f(buf as *libc::c_char)
320308
}
309+
} else if checked {
310+
v.to_c_str().with_ref(f)
311+
} else {
312+
v.to_c_str_unchecked().with_ref(f)
321313
}
322314
}
323315

0 commit comments

Comments
 (0)