]> git.lizzy.rs Git - rust.git/blob - src/librustrt/c_str.rs
auto merge of #14717 : zwarich/rust/borrowck-tests, r=cmr
[rust.git] / src / librustrt / c_str.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 /*!
12
13 C-string manipulation and management
14
15 This modules provides the basic methods for creating and manipulating
16 null-terminated strings for use with FFI calls (back to C). Most C APIs require
17 that the string being passed to them is null-terminated, and by default rust's
18 string types are *not* null terminated.
19
20 The other problem with translating Rust strings to C strings is that Rust
21 strings can validly contain a null-byte in the middle of the string (0 is a
22 valid unicode codepoint). This means that not all Rust strings can actually be
23 translated to C strings.
24
25 # Creation of a C string
26
27 A C string is managed through the `CString` type defined in this module. It
28 "owns" the internal buffer of characters and will automatically deallocate the
29 buffer when the string is dropped. The `ToCStr` trait is implemented for `&str`
30 and `&[u8]`, but the conversions can fail due to some of the limitations
31 explained above.
32
33 This also means that currently whenever a C string is created, an allocation
34 must be performed to place the data elsewhere (the lifetime of the C string is
35 not tied to the lifetime of the original string/data buffer). If C strings are
36 heavily used in applications, then caching may be advisable to prevent
37 unnecessary amounts of allocations.
38
39 An example of creating and using a C string would be:
40
41 ```rust
42 extern crate libc;
43
44 extern {
45     fn puts(s: *libc::c_char);
46 }
47
48 fn main() {
49     let my_string = "Hello, world!";
50
51     // Allocate the C string with an explicit local that owns the string. The
52     // `c_buffer` pointer will be deallocated when `my_c_string` goes out of scope.
53     let my_c_string = my_string.to_c_str();
54     my_c_string.with_ref(|c_buffer| {
55         unsafe { puts(c_buffer); }
56     });
57
58     // Don't save off the allocation of the C string, the `c_buffer` will be
59     // deallocated when this block returns!
60     my_string.with_c_str(|c_buffer| {
61         unsafe { puts(c_buffer); }
62     });
63 }
64 ```
65
66 */
67
68 use core::prelude::*;
69
70 use alloc::libc_heap::malloc_raw;
71 use collections::string::String;
72 use core::kinds::marker;
73 use core::mem;
74 use core::ptr;
75 use core::raw::Slice;
76 use core::slice;
77 use core::str;
78 use libc;
79
80 /// The representation of a C String.
81 ///
82 /// This structure wraps a `*libc::c_char`, and will automatically free the
83 /// memory it is pointing to when it goes out of scope.
84 pub struct CString {
85     buf: *libc::c_char,
86     owns_buffer_: bool,
87 }
88
89 impl Clone for CString {
90     /// Clone this CString into a new, uniquely owned CString. For safety
91     /// reasons, this is always a deep clone, rather than the usual shallow
92     /// clone.
93     fn clone(&self) -> CString {
94         if self.buf.is_null() {
95             CString { buf: self.buf, owns_buffer_: self.owns_buffer_ }
96         } else {
97             let len = self.len() + 1;
98             let buf = unsafe { malloc_raw(len) } as *mut libc::c_char;
99             unsafe { ptr::copy_nonoverlapping_memory(buf, self.buf, len); }
100             CString { buf: buf as *libc::c_char, owns_buffer_: true }
101         }
102     }
103 }
104
105 impl PartialEq for CString {
106     fn eq(&self, other: &CString) -> bool {
107         if self.buf as uint == other.buf as uint {
108             true
109         } else if self.buf.is_null() || other.buf.is_null() {
110             false
111         } else {
112             unsafe {
113                 libc::strcmp(self.buf, other.buf) == 0
114             }
115         }
116     }
117 }
118
119 impl CString {
120     /// Create a C String from a pointer.
121     pub unsafe fn new(buf: *libc::c_char, owns_buffer: bool) -> CString {
122         CString { buf: buf, owns_buffer_: owns_buffer }
123     }
124
125     /// Unwraps the wrapped `*libc::c_char` from the `CString` wrapper.
126     /// Any ownership of the buffer by the `CString` wrapper is forgotten.
127     pub unsafe fn unwrap(self) -> *libc::c_char {
128         let mut c_str = self;
129         c_str.owns_buffer_ = false;
130         c_str.buf
131     }
132
133     /// Calls a closure with a reference to the underlying `*libc::c_char`.
134     ///
135     /// # Failure
136     ///
137     /// Fails if the CString is null.
138     pub fn with_ref<T>(&self, f: |*libc::c_char| -> T) -> T {
139         if self.buf.is_null() { fail!("CString is null!"); }
140         f(self.buf)
141     }
142
143     /// Calls a closure with a mutable reference to the underlying `*libc::c_char`.
144     ///
145     /// # Failure
146     ///
147     /// Fails if the CString is null.
148     pub fn with_mut_ref<T>(&mut self, f: |*mut libc::c_char| -> T) -> T {
149         if self.buf.is_null() { fail!("CString is null!"); }
150         f(self.buf as *mut libc::c_char)
151     }
152
153     /// Returns true if the CString is a null.
154     pub fn is_null(&self) -> bool {
155         self.buf.is_null()
156     }
157
158     /// Returns true if the CString is not null.
159     pub fn is_not_null(&self) -> bool {
160         self.buf.is_not_null()
161     }
162
163     /// Returns whether or not the `CString` owns the buffer.
164     pub fn owns_buffer(&self) -> bool {
165         self.owns_buffer_
166     }
167
168     /// Converts the CString into a `&[u8]` without copying.
169     /// Includes the terminating NUL byte.
170     ///
171     /// # Failure
172     ///
173     /// Fails if the CString is null.
174     #[inline]
175     pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
176         if self.buf.is_null() { fail!("CString is null!"); }
177         unsafe {
178             mem::transmute(Slice { data: self.buf, len: self.len() + 1 })
179         }
180     }
181
182     /// Converts the CString into a `&[u8]` without copying.
183     /// Does not include the terminating NUL byte.
184     ///
185     /// # Failure
186     ///
187     /// Fails if the CString is null.
188     #[inline]
189     pub fn as_bytes_no_nul<'a>(&'a self) -> &'a [u8] {
190         if self.buf.is_null() { fail!("CString is null!"); }
191         unsafe {
192             mem::transmute(Slice { data: self.buf, len: self.len() })
193         }
194     }
195
196     /// Converts the CString into a `&str` without copying.
197     /// Returns None if the CString is not UTF-8.
198     ///
199     /// # Failure
200     ///
201     /// Fails if the CString is null.
202     #[inline]
203     pub fn as_str<'a>(&'a self) -> Option<&'a str> {
204         let buf = self.as_bytes_no_nul();
205         str::from_utf8(buf)
206     }
207
208     /// Return a CString iterator.
209     ///
210     /// # Failure
211     ///
212     /// Fails if the CString is null.
213     pub fn iter<'a>(&'a self) -> CChars<'a> {
214         if self.buf.is_null() { fail!("CString is null!"); }
215         CChars {
216             ptr: self.buf,
217             marker: marker::ContravariantLifetime,
218         }
219     }
220 }
221
222 impl Drop for CString {
223     fn drop(&mut self) {
224         if self.owns_buffer_ {
225             unsafe {
226                 libc::free(self.buf as *mut libc::c_void)
227             }
228         }
229     }
230 }
231
232 impl Container for CString {
233     /// Return the number of bytes in the CString (not including the NUL terminator).
234     ///
235     /// # Failure
236     ///
237     /// Fails if the CString is null.
238     #[inline]
239     fn len(&self) -> uint {
240         if self.buf.is_null() { fail!("CString is null!"); }
241         let mut cur = self.buf;
242         let mut len = 0;
243         unsafe {
244             while *cur != 0 {
245                 len += 1;
246                 cur = cur.offset(1);
247             }
248         }
249         return len;
250     }
251 }
252
253 /// A generic trait for converting a value to a CString.
254 pub trait ToCStr {
255     /// Copy the receiver into a CString.
256     ///
257     /// # Failure
258     ///
259     /// Fails the task if the receiver has an interior null.
260     fn to_c_str(&self) -> CString;
261
262     /// Unsafe variant of `to_c_str()` that doesn't check for nulls.
263     unsafe fn to_c_str_unchecked(&self) -> CString;
264
265     /// Work with a temporary CString constructed from the receiver.
266     /// The provided `*libc::c_char` will be freed immediately upon return.
267     ///
268     /// # Example
269     ///
270     /// ```rust
271     /// extern crate libc;
272     ///
273     /// fn main() {
274     ///     let s = "PATH".with_c_str(|path| unsafe {
275     ///         libc::getenv(path)
276     ///     });
277     /// }
278     /// ```
279     ///
280     /// # Failure
281     ///
282     /// Fails the task if the receiver has an interior null.
283     #[inline]
284     fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T {
285         self.to_c_str().with_ref(f)
286     }
287
288     /// Unsafe variant of `with_c_str()` that doesn't check for nulls.
289     #[inline]
290     unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T {
291         self.to_c_str_unchecked().with_ref(f)
292     }
293 }
294
295 // FIXME (#12938): Until DST lands, we cannot decompose &str into &
296 // and str, so we cannot usefully take ToCStr arguments by reference
297 // (without forcing an additional & around &str). So we are instead
298 // temporarily adding an instance for ~str and String, so that we can
299 // take ToCStr as owned. When DST lands, the string instances should
300 // be revisted, and arguments bound by ToCStr should be passed by
301 // reference.
302
303 impl<'a> ToCStr for &'a str {
304     #[inline]
305     fn to_c_str(&self) -> CString {
306         self.as_bytes().to_c_str()
307     }
308
309     #[inline]
310     unsafe fn to_c_str_unchecked(&self) -> CString {
311         self.as_bytes().to_c_str_unchecked()
312     }
313
314     #[inline]
315     fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T {
316         self.as_bytes().with_c_str(f)
317     }
318
319     #[inline]
320     unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T {
321         self.as_bytes().with_c_str_unchecked(f)
322     }
323 }
324
325 impl ToCStr for String {
326     #[inline]
327     fn to_c_str(&self) -> CString {
328         self.as_bytes().to_c_str()
329     }
330
331     #[inline]
332     unsafe fn to_c_str_unchecked(&self) -> CString {
333         self.as_bytes().to_c_str_unchecked()
334     }
335
336     #[inline]
337     fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T {
338         self.as_bytes().with_c_str(f)
339     }
340
341     #[inline]
342     unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T {
343         self.as_bytes().with_c_str_unchecked(f)
344     }
345 }
346
347 // The length of the stack allocated buffer for `vec.with_c_str()`
348 static BUF_LEN: uint = 128;
349
350 impl<'a> ToCStr for &'a [u8] {
351     fn to_c_str(&self) -> CString {
352         let mut cs = unsafe { self.to_c_str_unchecked() };
353         cs.with_mut_ref(|buf| check_for_null(*self, buf));
354         cs
355     }
356
357     unsafe fn to_c_str_unchecked(&self) -> CString {
358         let self_len = self.len();
359         let buf = malloc_raw(self_len + 1);
360
361         ptr::copy_memory(buf, self.as_ptr(), self_len);
362         *buf.offset(self_len as int) = 0;
363
364         CString::new(buf as *libc::c_char, true)
365     }
366
367     fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T {
368         unsafe { with_c_str(*self, true, f) }
369     }
370
371     unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T {
372         with_c_str(*self, false, f)
373     }
374 }
375
376 // Unsafe function that handles possibly copying the &[u8] into a stack array.
377 unsafe fn with_c_str<T>(v: &[u8], checked: bool, f: |*libc::c_char| -> T) -> T {
378     if v.len() < BUF_LEN {
379         let mut buf: [u8, .. BUF_LEN] = mem::uninitialized();
380         slice::bytes::copy_memory(buf, v);
381         buf[v.len()] = 0;
382
383         let buf = buf.as_mut_ptr();
384         if checked {
385             check_for_null(v, buf as *mut libc::c_char);
386         }
387
388         f(buf as *libc::c_char)
389     } else if checked {
390         v.to_c_str().with_ref(f)
391     } else {
392         v.to_c_str_unchecked().with_ref(f)
393     }
394 }
395
396 #[inline]
397 fn check_for_null(v: &[u8], buf: *mut libc::c_char) {
398     for i in range(0, v.len()) {
399         unsafe {
400             let p = buf.offset(i as int);
401             assert!(*p != 0);
402         }
403     }
404 }
405
406 /// External iterator for a CString's bytes.
407 ///
408 /// Use with the `std::iter` module.
409 pub struct CChars<'a> {
410     ptr: *libc::c_char,
411     marker: marker::ContravariantLifetime<'a>,
412 }
413
414 impl<'a> Iterator<libc::c_char> for CChars<'a> {
415     fn next(&mut self) -> Option<libc::c_char> {
416         let ch = unsafe { *self.ptr };
417         if ch == 0 {
418             None
419         } else {
420             self.ptr = unsafe { self.ptr.offset(1) };
421             Some(ch)
422         }
423     }
424 }
425
426 /// Parses a C "multistring", eg windows env values or
427 /// the req->ptr result in a uv_fs_readdir() call.
428 ///
429 /// Optionally, a `count` can be passed in, limiting the
430 /// parsing to only being done `count`-times.
431 ///
432 /// The specified closure is invoked with each string that
433 /// is found, and the number of strings found is returned.
434 pub unsafe fn from_c_multistring(buf: *libc::c_char,
435                                  count: Option<uint>,
436                                  f: |&CString|) -> uint {
437
438     let mut curr_ptr: uint = buf as uint;
439     let mut ctr = 0;
440     let (limited_count, limit) = match count {
441         Some(limit) => (true, limit),
442         None => (false, 0)
443     };
444     while ((limited_count && ctr < limit) || !limited_count)
445           && *(curr_ptr as *libc::c_char) != 0 as libc::c_char {
446         let cstr = CString::new(curr_ptr as *libc::c_char, false);
447         f(&cstr);
448         curr_ptr += cstr.len() + 1;
449         ctr += 1;
450     }
451     return ctr;
452 }
453
454 #[cfg(test)]
455 mod tests {
456     use std::prelude::*;
457     use std::ptr;
458     use std::task;
459     use libc;
460
461     use super::*;
462
463     #[test]
464     fn test_str_multistring_parsing() {
465         unsafe {
466             let input = bytes!("zero", "\x00", "one", "\x00", "\x00");
467             let ptr = input.as_ptr();
468             let expected = ["zero", "one"];
469             let mut it = expected.iter();
470             let result = from_c_multistring(ptr as *libc::c_char, None, |c| {
471                 let cbytes = c.as_bytes_no_nul();
472                 assert_eq!(cbytes, it.next().unwrap().as_bytes());
473             });
474             assert_eq!(result, 2);
475             assert!(it.next().is_none());
476         }
477     }
478
479     #[test]
480     fn test_str_to_c_str() {
481         "".to_c_str().with_ref(|buf| {
482             unsafe {
483                 assert_eq!(*buf.offset(0), 0);
484             }
485         });
486
487         "hello".to_c_str().with_ref(|buf| {
488             unsafe {
489                 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
490                 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
491                 assert_eq!(*buf.offset(2), 'l' as libc::c_char);
492                 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
493                 assert_eq!(*buf.offset(4), 'o' as libc::c_char);
494                 assert_eq!(*buf.offset(5), 0);
495             }
496         })
497     }
498
499     #[test]
500     fn test_vec_to_c_str() {
501         let b: &[u8] = [];
502         b.to_c_str().with_ref(|buf| {
503             unsafe {
504                 assert_eq!(*buf.offset(0), 0);
505             }
506         });
507
508         let _ = bytes!("hello").to_c_str().with_ref(|buf| {
509             unsafe {
510                 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
511                 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
512                 assert_eq!(*buf.offset(2), 'l' as libc::c_char);
513                 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
514                 assert_eq!(*buf.offset(4), 'o' as libc::c_char);
515                 assert_eq!(*buf.offset(5), 0);
516             }
517         });
518
519         let _ = bytes!("foo", 0xff).to_c_str().with_ref(|buf| {
520             unsafe {
521                 assert_eq!(*buf.offset(0), 'f' as libc::c_char);
522                 assert_eq!(*buf.offset(1), 'o' as libc::c_char);
523                 assert_eq!(*buf.offset(2), 'o' as libc::c_char);
524                 assert_eq!(*buf.offset(3), 0xff as i8);
525                 assert_eq!(*buf.offset(4), 0);
526             }
527         });
528     }
529
530     #[test]
531     fn test_is_null() {
532         let c_str = unsafe { CString::new(ptr::null(), false) };
533         assert!(c_str.is_null());
534         assert!(!c_str.is_not_null());
535     }
536
537     #[test]
538     fn test_unwrap() {
539         let c_str = "hello".to_c_str();
540         unsafe { libc::free(c_str.unwrap() as *mut libc::c_void) }
541     }
542
543     #[test]
544     fn test_with_ref() {
545         let c_str = "hello".to_c_str();
546         let len = unsafe { c_str.with_ref(|buf| libc::strlen(buf)) };
547         assert!(!c_str.is_null());
548         assert!(c_str.is_not_null());
549         assert_eq!(len, 5);
550     }
551
552     #[test]
553     #[should_fail]
554     fn test_with_ref_empty_fail() {
555         let c_str = unsafe { CString::new(ptr::null(), false) };
556         c_str.with_ref(|_| ());
557     }
558
559     #[test]
560     fn test_iterator() {
561         let c_str = "".to_c_str();
562         let mut iter = c_str.iter();
563         assert_eq!(iter.next(), None);
564
565         let c_str = "hello".to_c_str();
566         let mut iter = c_str.iter();
567         assert_eq!(iter.next(), Some('h' as libc::c_char));
568         assert_eq!(iter.next(), Some('e' as libc::c_char));
569         assert_eq!(iter.next(), Some('l' as libc::c_char));
570         assert_eq!(iter.next(), Some('l' as libc::c_char));
571         assert_eq!(iter.next(), Some('o' as libc::c_char));
572         assert_eq!(iter.next(), None);
573     }
574
575     #[test]
576     fn test_to_c_str_fail() {
577         assert!(task::try(proc() { "he\x00llo".to_c_str() }).is_err());
578     }
579
580     #[test]
581     fn test_to_c_str_unchecked() {
582         unsafe {
583             "he\x00llo".to_c_str_unchecked().with_ref(|buf| {
584                 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
585                 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
586                 assert_eq!(*buf.offset(2), 0);
587                 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
588                 assert_eq!(*buf.offset(4), 'l' as libc::c_char);
589                 assert_eq!(*buf.offset(5), 'o' as libc::c_char);
590                 assert_eq!(*buf.offset(6), 0);
591             })
592         }
593     }
594
595     #[test]
596     fn test_as_bytes() {
597         let c_str = "hello".to_c_str();
598         assert_eq!(c_str.as_bytes(), bytes!("hello", 0));
599         let c_str = "".to_c_str();
600         assert_eq!(c_str.as_bytes(), bytes!(0));
601         let c_str = bytes!("foo", 0xff).to_c_str();
602         assert_eq!(c_str.as_bytes(), bytes!("foo", 0xff, 0));
603     }
604
605     #[test]
606     fn test_as_bytes_no_nul() {
607         let c_str = "hello".to_c_str();
608         assert_eq!(c_str.as_bytes_no_nul(), bytes!("hello"));
609         let c_str = "".to_c_str();
610         let exp: &[u8] = [];
611         assert_eq!(c_str.as_bytes_no_nul(), exp);
612         let c_str = bytes!("foo", 0xff).to_c_str();
613         assert_eq!(c_str.as_bytes_no_nul(), bytes!("foo", 0xff));
614     }
615
616     #[test]
617     #[should_fail]
618     fn test_as_bytes_fail() {
619         let c_str = unsafe { CString::new(ptr::null(), false) };
620         c_str.as_bytes();
621     }
622
623     #[test]
624     #[should_fail]
625     fn test_as_bytes_no_nul_fail() {
626         let c_str = unsafe { CString::new(ptr::null(), false) };
627         c_str.as_bytes_no_nul();
628     }
629
630     #[test]
631     fn test_as_str() {
632         let c_str = "hello".to_c_str();
633         assert_eq!(c_str.as_str(), Some("hello"));
634         let c_str = "".to_c_str();
635         assert_eq!(c_str.as_str(), Some(""));
636         let c_str = bytes!("foo", 0xff).to_c_str();
637         assert_eq!(c_str.as_str(), None);
638     }
639
640     #[test]
641     #[should_fail]
642     fn test_as_str_fail() {
643         let c_str = unsafe { CString::new(ptr::null(), false) };
644         c_str.as_str();
645     }
646
647     #[test]
648     #[should_fail]
649     fn test_len_fail() {
650         let c_str = unsafe { CString::new(ptr::null(), false) };
651         c_str.len();
652     }
653
654     #[test]
655     #[should_fail]
656     fn test_iter_fail() {
657         let c_str = unsafe { CString::new(ptr::null(), false) };
658         c_str.iter();
659     }
660
661     #[test]
662     fn test_clone() {
663         let a = "hello".to_c_str();
664         let b = a.clone();
665         assert!(a == b);
666     }
667
668     #[test]
669     fn test_clone_noleak() {
670         fn foo(f: |c: &CString|) {
671             let s = "test".to_string();
672             let c = s.to_c_str();
673             // give the closure a non-owned CString
674             let mut c_ = c.with_ref(|c| unsafe { CString::new(c, false) } );
675             f(&c_);
676             // muck with the buffer for later printing
677             c_.with_mut_ref(|c| unsafe { *c = 'X' as libc::c_char } );
678         }
679
680         let mut c_: Option<CString> = None;
681         foo(|c| {
682             c_ = Some(c.clone());
683             c.clone();
684             // force a copy, reading the memory
685             c.as_bytes().to_owned();
686         });
687         let c_ = c_.unwrap();
688         // force a copy, reading the memory
689         c_.as_bytes().to_owned();
690     }
691
692     #[test]
693     fn test_clone_eq_null() {
694         let x = unsafe { CString::new(ptr::null(), false) };
695         let y = x.clone();
696         assert!(x == y);
697     }
698 }
699
700 #[cfg(test)]
701 mod bench {
702     use test::Bencher;
703     use libc;
704     use std::prelude::*;
705
706     #[inline]
707     fn check(s: &str, c_str: *libc::c_char) {
708         let s_buf = s.as_ptr();
709         for i in range(0, s.len()) {
710             unsafe {
711                 assert_eq!(
712                     *s_buf.offset(i as int) as libc::c_char,
713                     *c_str.offset(i as int));
714             }
715         }
716     }
717
718     static s_short: &'static str = "Mary";
719     static s_medium: &'static str = "Mary had a little lamb";
720     static s_long: &'static str = "\
721         Mary had a little lamb, Little lamb
722         Mary had a little lamb, Little lamb
723         Mary had a little lamb, Little lamb
724         Mary had a little lamb, Little lamb
725         Mary had a little lamb, Little lamb
726         Mary had a little lamb, Little lamb";
727
728     fn bench_to_str(b: &mut Bencher, s: &str) {
729         b.iter(|| {
730             let c_str = s.to_c_str();
731             c_str.with_ref(|c_str_buf| check(s, c_str_buf))
732         })
733     }
734
735     #[bench]
736     fn bench_to_c_str_short(b: &mut Bencher) {
737         bench_to_str(b, s_short)
738     }
739
740     #[bench]
741     fn bench_to_c_str_medium(b: &mut Bencher) {
742         bench_to_str(b, s_medium)
743     }
744
745     #[bench]
746     fn bench_to_c_str_long(b: &mut Bencher) {
747         bench_to_str(b, s_long)
748     }
749
750     fn bench_to_c_str_unchecked(b: &mut Bencher, s: &str) {
751         b.iter(|| {
752             let c_str = unsafe { s.to_c_str_unchecked() };
753             c_str.with_ref(|c_str_buf| check(s, c_str_buf))
754         })
755     }
756
757     #[bench]
758     fn bench_to_c_str_unchecked_short(b: &mut Bencher) {
759         bench_to_c_str_unchecked(b, s_short)
760     }
761
762     #[bench]
763     fn bench_to_c_str_unchecked_medium(b: &mut Bencher) {
764         bench_to_c_str_unchecked(b, s_medium)
765     }
766
767     #[bench]
768     fn bench_to_c_str_unchecked_long(b: &mut Bencher) {
769         bench_to_c_str_unchecked(b, s_long)
770     }
771
772     fn bench_with_c_str(b: &mut Bencher, s: &str) {
773         b.iter(|| {
774             s.with_c_str(|c_str_buf| check(s, c_str_buf))
775         })
776     }
777
778     #[bench]
779     fn bench_with_c_str_short(b: &mut Bencher) {
780         bench_with_c_str(b, s_short)
781     }
782
783     #[bench]
784     fn bench_with_c_str_medium(b: &mut Bencher) {
785         bench_with_c_str(b, s_medium)
786     }
787
788     #[bench]
789     fn bench_with_c_str_long(b: &mut Bencher) {
790         bench_with_c_str(b, s_long)
791     }
792
793     fn bench_with_c_str_unchecked(b: &mut Bencher, s: &str) {
794         b.iter(|| {
795             unsafe {
796                 s.with_c_str_unchecked(|c_str_buf| check(s, c_str_buf))
797             }
798         })
799     }
800
801     #[bench]
802     fn bench_with_c_str_unchecked_short(b: &mut Bencher) {
803         bench_with_c_str_unchecked(b, s_short)
804     }
805
806     #[bench]
807     fn bench_with_c_str_unchecked_medium(b: &mut Bencher) {
808         bench_with_c_str_unchecked(b, s_medium)
809     }
810
811     #[bench]
812     fn bench_with_c_str_unchecked_long(b: &mut Bencher) {
813         bench_with_c_str_unchecked(b, s_long)
814     }
815 }