Skip to content

Commit 2d87803

Browse files
committed
std: add micro optimization to vec.with_c_str_unchecked
before: test c_str::bench::bench_with_c_str_unchecked_long ... bench: 361 ns/iter (+/- 9) test c_str::bench::bench_with_c_str_unchecked_medium ... bench: 75 ns/iter (+/- 2) test c_str::bench::bench_with_c_str_unchecked_short ... bench: 60 ns/iter (+/- 9) after: test c_str::bench::bench_with_c_str_unchecked_long ... bench: 362 ns/iter (+/- test c_str::bench::bench_with_c_str_unchecked_medium ... bench: 30 ns/iter (+/- 7) test c_str::bench::bench_with_c_str_unchecked_short ... bench: 12 ns/iter (+/- 4)
1 parent 4868273 commit 2d87803

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/libstd/c_str.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,11 @@ impl<'self> ToCStr for &'self str {
247247
fn with_c_str<T>(&self, f: &fn(*libc::c_char) -> T) -> T {
248248
self.as_bytes().with_c_str(f)
249249
}
250+
251+
#[inline]
252+
unsafe fn with_c_str_unchecked<T>(&self, f: &fn(*libc::c_char) -> T) -> T {
253+
self.as_bytes().with_c_str_unchecked(f)
254+
}
250255
}
251256

252257
// The length of the stack allocated buffer for `vec.with_c_str()`
@@ -297,6 +302,23 @@ impl<'self> ToCStr for &'self [u8] {
297302
self.to_c_str().with_ref(f)
298303
}
299304
}
305+
306+
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();
310+
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;
314+
315+
f(buf as *libc::c_char)
316+
}
317+
}
318+
} else {
319+
self.to_c_str().with_ref(f)
320+
}
321+
}
300322
}
301323

302324
#[inline]
@@ -616,4 +638,29 @@ mod bench {
616638
fn bench_with_c_str_long(bh: &mut BenchHarness) {
617639
bench_with_c_str(bh, s_long)
618640
}
641+
642+
fn bench_with_c_str_unchecked(bh: &mut BenchHarness, s: &str) {
643+
do bh.iter {
644+
unsafe {
645+
do s.with_c_str_unchecked |c_str_buf| {
646+
check(s, c_str_buf)
647+
}
648+
}
649+
}
650+
}
651+
652+
#[bench]
653+
fn bench_with_c_str_unchecked_short(bh: &mut BenchHarness) {
654+
bench_with_c_str_unchecked(bh, s_short)
655+
}
656+
657+
#[bench]
658+
fn bench_with_c_str_unchecked_medium(bh: &mut BenchHarness) {
659+
bench_with_c_str_unchecked(bh, s_medium)
660+
}
661+
662+
#[bench]
663+
fn bench_with_c_str_unchecked_long(bh: &mut BenchHarness) {
664+
bench_with_c_str_unchecked(bh, s_long)
665+
}
619666
}

0 commit comments

Comments
 (0)