]> git.lizzy.rs Git - rust.git/blob - src/librustrt/c_str.rs
auto merge of #15165 : zookoatleastauthoritycom/rust/14148-Optimize-out-exhortations...
[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     ///
127     /// The original object is destructed after this method is called, and if
128     /// the underlying pointer was previously allocated, care must be taken to
129     /// ensure that it is deallocated properly.
130     pub unsafe fn unwrap(self) -> *libc::c_char {
131         let mut c_str = self;
132         c_str.owns_buffer_ = false;
133         c_str.buf
134     }
135
136     /// Calls a closure with a reference to the underlying `*libc::c_char`.
137     ///
138     /// # Failure
139     ///
140     /// Fails if the CString is null.
141     pub fn with_ref<T>(&self, f: |*libc::c_char| -> T) -> T {
142         if self.buf.is_null() { fail!("CString is null!"); }
143         f(self.buf)
144     }
145
146     /// Calls a closure with a mutable reference to the underlying `*libc::c_char`.
147     ///
148     /// # Failure
149     ///
150     /// Fails if the CString is null.
151     pub fn with_mut_ref<T>(&mut self, f: |*mut libc::c_char| -> T) -> T {
152         if self.buf.is_null() { fail!("CString is null!"); }
153         f(self.buf as *mut libc::c_char)
154     }
155
156     /// Returns true if the CString is a null.
157     pub fn is_null(&self) -> bool {
158         self.buf.is_null()
159     }
160
161     /// Returns true if the CString is not null.
162     pub fn is_not_null(&self) -> bool {
163         self.buf.is_not_null()
164     }
165
166     /// Returns whether or not the `CString` owns the buffer.
167     pub fn owns_buffer(&self) -> bool {
168         self.owns_buffer_
169     }
170
171     /// Converts the CString into a `&[u8]` without copying.
172     /// Includes the terminating NUL byte.
173     ///
174     /// # Failure
175     ///
176     /// Fails if the CString is null.
177     #[inline]
178     pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
179         if self.buf.is_null() { fail!("CString is null!"); }
180         unsafe {
181             mem::transmute(Slice { data: self.buf, len: self.len() + 1 })
182         }
183     }
184
185     /// Converts the CString into a `&[u8]` without copying.
186     /// Does not include the terminating NUL byte.
187     ///
188     /// # Failure
189     ///
190     /// Fails if the CString is null.
191     #[inline]
192     pub fn as_bytes_no_nul<'a>(&'a self) -> &'a [u8] {
193         if self.buf.is_null() { fail!("CString is null!"); }
194         unsafe {
195             mem::transmute(Slice { data: self.buf, len: self.len() })
196         }
197     }
198
199     /// Converts the CString into a `&str` without copying.
200     /// Returns None if the CString is not UTF-8.
201     ///
202     /// # Failure
203     ///
204     /// Fails if the CString is null.
205     #[inline]
206     pub fn as_str<'a>(&'a self) -> Option<&'a str> {
207         let buf = self.as_bytes_no_nul();
208         str::from_utf8(buf)
209     }
210
211     /// Return a CString iterator.
212     ///
213     /// # Failure
214     ///
215     /// Fails if the CString is null.
216     pub fn iter<'a>(&'a self) -> CChars<'a> {
217         if self.buf.is_null() { fail!("CString is null!"); }
218         CChars {
219             ptr: self.buf,
220             marker: marker::ContravariantLifetime,
221         }
222     }
223 }
224
225 impl Drop for CString {
226     fn drop(&mut self) {
227         if self.owns_buffer_ {
228             unsafe {
229                 libc::free(self.buf as *mut libc::c_void)
230             }
231         }
232     }
233 }
234
235 impl Collection for CString {
236     /// Return the number of bytes in the CString (not including the NUL terminator).
237     ///
238     /// # Failure
239     ///
240     /// Fails if the CString is null.
241     #[inline]
242     fn len(&self) -> uint {
243         if self.buf.is_null() { fail!("CString is null!"); }
244         let mut cur = self.buf;
245         let mut len = 0;
246         unsafe {
247             while *cur != 0 {
248                 len += 1;
249                 cur = cur.offset(1);
250             }
251         }
252         return len;
253     }
254 }
255
256 /// A generic trait for converting a value to a CString.
257 pub trait ToCStr {
258     /// Copy the receiver into a CString.
259     ///
260     /// # Failure
261     ///
262     /// Fails the task if the receiver has an interior null.
263     fn to_c_str(&self) -> CString;
264
265     /// Unsafe variant of `to_c_str()` that doesn't check for nulls.
266     unsafe fn to_c_str_unchecked(&self) -> CString;
267
268     /// Work with a temporary CString constructed from the receiver.
269     /// The provided `*libc::c_char` will be freed immediately upon return.
270     ///
271     /// # Example
272     ///
273     /// ```rust
274     /// extern crate libc;
275     ///
276     /// fn main() {
277     ///     let s = "PATH".with_c_str(|path| unsafe {
278     ///         libc::getenv(path)
279     ///     });
280     /// }
281     /// ```
282     ///
283     /// # Failure
284     ///
285     /// Fails the task if the receiver has an interior null.
286     #[inline]
287     fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T {
288         self.to_c_str().with_ref(f)
289     }
290
291     /// Unsafe variant of `with_c_str()` that doesn't check for nulls.
292     #[inline]
293     unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T {
294         self.to_c_str_unchecked().with_ref(f)
295     }
296 }
297
298 // FIXME (#12938): Until DST lands, we cannot decompose &str into &
299 // and str, so we cannot usefully take ToCStr arguments by reference
300 // (without forcing an additional & around &str). So we are instead
301 // temporarily adding an instance for ~str and String, so that we can
302 // take ToCStr as owned. When DST lands, the string instances should
303 // be revisted, and arguments bound by ToCStr should be passed by
304 // reference.
305
306 impl<'a> ToCStr for &'a str {
307     #[inline]
308     fn to_c_str(&self) -> CString {
309         self.as_bytes().to_c_str()
310     }
311
312     #[inline]
313     unsafe fn to_c_str_unchecked(&self) -> CString {
314         self.as_bytes().to_c_str_unchecked()
315     }
316
317     #[inline]
318     fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T {
319         self.as_bytes().with_c_str(f)
320     }
321
322     #[inline]
323     unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T {
324         self.as_bytes().with_c_str_unchecked(f)
325     }
326 }
327
328 impl ToCStr for String {
329     #[inline]
330     fn to_c_str(&self) -> CString {
331         self.as_bytes().to_c_str()
332     }
333
334     #[inline]
335     unsafe fn to_c_str_unchecked(&self) -> CString {
336         self.as_bytes().to_c_str_unchecked()
337     }
338
339     #[inline]
340     fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T {
341         self.as_bytes().with_c_str(f)
342     }
343
344     #[inline]
345     unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T {
346         self.as_bytes().with_c_str_unchecked(f)
347     }
348 }
349
350 // The length of the stack allocated buffer for `vec.with_c_str()`
351 static BUF_LEN: uint = 128;
352
353 impl<'a> ToCStr for &'a [u8] {
354     fn to_c_str(&self) -> CString {
355         let mut cs = unsafe { self.to_c_str_unchecked() };
356         cs.with_mut_ref(|buf| check_for_null(*self, buf));
357         cs
358     }
359
360     unsafe fn to_c_str_unchecked(&self) -> CString {
361         let self_len = self.len();
362         let buf = malloc_raw(self_len + 1);
363
364         ptr::copy_memory(buf, self.as_ptr(), self_len);
365         *buf.offset(self_len as int) = 0;
366
367         CString::new(buf as *libc::c_char, true)
368     }
369
370     fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T {
371         unsafe { with_c_str(*self, true, f) }
372     }
373
374     unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T {
375         with_c_str(*self, false, f)
376     }
377 }
378
379 // Unsafe function that handles possibly copying the &[u8] into a stack array.
380 unsafe fn with_c_str<T>(v: &[u8], checked: bool, f: |*libc::c_char| -> T) -> T {
381     if v.len() < BUF_LEN {
382         let mut buf: [u8, .. BUF_LEN] = mem::uninitialized();
383         slice::bytes::copy_memory(buf, v);
384         buf[v.len()] = 0;
385
386         let buf = buf.as_mut_ptr();
387         if checked {
388             check_for_null(v, buf as *mut libc::c_char);
389         }
390
391         f(buf as *libc::c_char)
392     } else if checked {
393         v.to_c_str().with_ref(f)
394     } else {
395         v.to_c_str_unchecked().with_ref(f)
396     }
397 }
398
399 #[inline]
400 fn check_for_null(v: &[u8], buf: *mut libc::c_char) {
401     for i in range(0, v.len()) {
402         unsafe {
403             let p = buf.offset(i as int);
404             assert!(*p != 0);
405         }
406     }
407 }
408
409 /// External iterator for a CString's bytes.
410 ///
411 /// Use with the `std::iter` module.
412 pub struct CChars<'a> {
413     ptr: *libc::c_char,
414     marker: marker::ContravariantLifetime<'a>,
415 }
416
417 impl<'a> Iterator<libc::c_char> for CChars<'a> {
418     fn next(&mut self) -> Option<libc::c_char> {
419         let ch = unsafe { *self.ptr };
420         if ch == 0 {
421             None
422         } else {
423             self.ptr = unsafe { self.ptr.offset(1) };
424             Some(ch)
425         }
426     }
427 }
428
429 /// Parses a C "multistring", eg windows env values or
430 /// the req->ptr result in a uv_fs_readdir() call.
431 ///
432 /// Optionally, a `count` can be passed in, limiting the
433 /// parsing to only being done `count`-times.
434 ///
435 /// The specified closure is invoked with each string that
436 /// is found, and the number of strings found is returned.
437 pub unsafe fn from_c_multistring(buf: *libc::c_char,
438                                  count: Option<uint>,
439                                  f: |&CString|) -> uint {
440
441     let mut curr_ptr: uint = buf as uint;
442     let mut ctr = 0;
443     let (limited_count, limit) = match count {
444         Some(limit) => (true, limit),
445         None => (false, 0)
446     };
447     while ((limited_count && ctr < limit) || !limited_count)
448           && *(curr_ptr as *libc::c_char) != 0 as libc::c_char {
449         let cstr = CString::new(curr_ptr as *libc::c_char, false);
450         f(&cstr);
451         curr_ptr += cstr.len() + 1;
452         ctr += 1;
453     }
454     return ctr;
455 }
456
457 #[cfg(test)]
458 mod tests {
459     use std::prelude::*;
460     use std::ptr;
461     use std::task;
462     use libc;
463
464     use super::*;
465
466     #[test]
467     fn test_str_multistring_parsing() {
468         unsafe {
469             let input = b"zero\0one\0\0";
470             let ptr = input.as_ptr();
471             let expected = ["zero", "one"];
472             let mut it = expected.iter();
473             let result = from_c_multistring(ptr as *libc::c_char, None, |c| {
474                 let cbytes = c.as_bytes_no_nul();
475                 assert_eq!(cbytes, it.next().unwrap().as_bytes());
476             });
477             assert_eq!(result, 2);
478             assert!(it.next().is_none());
479         }
480     }
481
482     #[test]
483     fn test_str_to_c_str() {
484         "".to_c_str().with_ref(|buf| {
485             unsafe {
486                 assert_eq!(*buf.offset(0), 0);
487             }
488         });
489
490         "hello".to_c_str().with_ref(|buf| {
491             unsafe {
492                 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
493                 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
494                 assert_eq!(*buf.offset(2), 'l' as libc::c_char);
495                 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
496                 assert_eq!(*buf.offset(4), 'o' as libc::c_char);
497                 assert_eq!(*buf.offset(5), 0);
498             }
499         })
500     }
501
502     #[test]
503     fn test_vec_to_c_str() {
504         let b: &[u8] = [];
505         b.to_c_str().with_ref(|buf| {
506             unsafe {
507                 assert_eq!(*buf.offset(0), 0);
508             }
509         });
510
511         let _ = b"hello".to_c_str().with_ref(|buf| {
512             unsafe {
513                 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
514                 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
515                 assert_eq!(*buf.offset(2), 'l' as libc::c_char);
516                 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
517                 assert_eq!(*buf.offset(4), 'o' as libc::c_char);
518                 assert_eq!(*buf.offset(5), 0);
519             }
520         });
521
522         let _ = b"foo\xFF".to_c_str().with_ref(|buf| {
523             unsafe {
524                 assert_eq!(*buf.offset(0), 'f' as libc::c_char);
525                 assert_eq!(*buf.offset(1), 'o' as libc::c_char);
526                 assert_eq!(*buf.offset(2), 'o' as libc::c_char);
527                 assert_eq!(*buf.offset(3), 0xff as i8);
528                 assert_eq!(*buf.offset(4), 0);
529             }
530         });
531     }
532
533     #[test]
534     fn test_is_null() {
535         let c_str = unsafe { CString::new(ptr::null(), false) };
536         assert!(c_str.is_null());
537         assert!(!c_str.is_not_null());
538     }
539
540     #[test]
541     fn test_unwrap() {
542         let c_str = "hello".to_c_str();
543         unsafe { libc::free(c_str.unwrap() as *mut libc::c_void) }
544     }
545
546     #[test]
547     fn test_with_ref() {
548         let c_str = "hello".to_c_str();
549         let len = unsafe { c_str.with_ref(|buf| libc::strlen(buf)) };
550         assert!(!c_str.is_null());
551         assert!(c_str.is_not_null());
552         assert_eq!(len, 5);
553     }
554
555     #[test]
556     #[should_fail]
557     fn test_with_ref_empty_fail() {
558         let c_str = unsafe { CString::new(ptr::null(), false) };
559         c_str.with_ref(|_| ());
560     }
561
562     #[test]
563     fn test_iterator() {
564         let c_str = "".to_c_str();
565         let mut iter = c_str.iter();
566         assert_eq!(iter.next(), None);
567
568         let c_str = "hello".to_c_str();
569         let mut iter = c_str.iter();
570         assert_eq!(iter.next(), Some('h' as libc::c_char));
571         assert_eq!(iter.next(), Some('e' as libc::c_char));
572         assert_eq!(iter.next(), Some('l' as libc::c_char));
573         assert_eq!(iter.next(), Some('l' as libc::c_char));
574         assert_eq!(iter.next(), Some('o' as libc::c_char));
575         assert_eq!(iter.next(), None);
576     }
577
578     #[test]
579     fn test_to_c_str_fail() {
580         assert!(task::try(proc() { "he\x00llo".to_c_str() }).is_err());
581     }
582
583     #[test]
584     fn test_to_c_str_unchecked() {
585         unsafe {
586             "he\x00llo".to_c_str_unchecked().with_ref(|buf| {
587                 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
588                 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
589                 assert_eq!(*buf.offset(2), 0);
590                 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
591                 assert_eq!(*buf.offset(4), 'l' as libc::c_char);
592                 assert_eq!(*buf.offset(5), 'o' as libc::c_char);
593                 assert_eq!(*buf.offset(6), 0);
594             })
595         }
596     }
597
598     #[test]
599     fn test_as_bytes() {
600         let c_str = "hello".to_c_str();
601         assert_eq!(c_str.as_bytes(), b"hello\0");
602         let c_str = "".to_c_str();
603         assert_eq!(c_str.as_bytes(), b"\0");
604         let c_str = b"foo\xFF".to_c_str();
605         assert_eq!(c_str.as_bytes(), b"foo\xFF\0");
606     }
607
608     #[test]
609     fn test_as_bytes_no_nul() {
610         let c_str = "hello".to_c_str();
611         assert_eq!(c_str.as_bytes_no_nul(), b"hello");
612         let c_str = "".to_c_str();
613         let exp: &[u8] = [];
614         assert_eq!(c_str.as_bytes_no_nul(), exp);
615         let c_str = b"foo\xFF".to_c_str();
616         assert_eq!(c_str.as_bytes_no_nul(), b"foo\xFF");
617     }
618
619     #[test]
620     #[should_fail]
621     fn test_as_bytes_fail() {
622         let c_str = unsafe { CString::new(ptr::null(), false) };
623         c_str.as_bytes();
624     }
625
626     #[test]
627     #[should_fail]
628     fn test_as_bytes_no_nul_fail() {
629         let c_str = unsafe { CString::new(ptr::null(), false) };
630         c_str.as_bytes_no_nul();
631     }
632
633     #[test]
634     fn test_as_str() {
635         let c_str = "hello".to_c_str();
636         assert_eq!(c_str.as_str(), Some("hello"));
637         let c_str = "".to_c_str();
638         assert_eq!(c_str.as_str(), Some(""));
639         let c_str = b"foo\xFF".to_c_str();
640         assert_eq!(c_str.as_str(), None);
641     }
642
643     #[test]
644     #[should_fail]
645     fn test_as_str_fail() {
646         let c_str = unsafe { CString::new(ptr::null(), false) };
647         c_str.as_str();
648     }
649
650     #[test]
651     #[should_fail]
652     fn test_len_fail() {
653         let c_str = unsafe { CString::new(ptr::null(), false) };
654         c_str.len();
655     }
656
657     #[test]
658     #[should_fail]
659     fn test_iter_fail() {
660         let c_str = unsafe { CString::new(ptr::null(), false) };
661         c_str.iter();
662     }
663
664     #[test]
665     fn test_clone() {
666         let a = "hello".to_c_str();
667         let b = a.clone();
668         assert!(a == b);
669     }
670
671     #[test]
672     fn test_clone_noleak() {
673         fn foo(f: |c: &CString|) {
674             let s = "test".to_string();
675             let c = s.to_c_str();
676             // give the closure a non-owned CString
677             let mut c_ = c.with_ref(|c| unsafe { CString::new(c, false) } );
678             f(&c_);
679             // muck with the buffer for later printing
680             c_.with_mut_ref(|c| unsafe { *c = 'X' as libc::c_char } );
681         }
682
683         let mut c_: Option<CString> = None;
684         foo(|c| {
685             c_ = Some(c.clone());
686             c.clone();
687             // force a copy, reading the memory
688             c.as_bytes().to_owned();
689         });
690         let c_ = c_.unwrap();
691         // force a copy, reading the memory
692         c_.as_bytes().to_owned();
693     }
694
695     #[test]
696     fn test_clone_eq_null() {
697         let x = unsafe { CString::new(ptr::null(), false) };
698         let y = x.clone();
699         assert!(x == y);
700     }
701 }
702
703 #[cfg(test)]
704 mod bench {
705     use test::Bencher;
706     use libc;
707     use std::prelude::*;
708
709     #[inline]
710     fn check(s: &str, c_str: *libc::c_char) {
711         let s_buf = s.as_ptr();
712         for i in range(0, s.len()) {
713             unsafe {
714                 assert_eq!(
715                     *s_buf.offset(i as int) as libc::c_char,
716                     *c_str.offset(i as int));
717             }
718         }
719     }
720
721     static s_short: &'static str = "Mary";
722     static s_medium: &'static str = "Mary had a little lamb";
723     static s_long: &'static str = "\
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         Mary had a little lamb, Little lamb
728         Mary had a little lamb, Little lamb
729         Mary had a little lamb, Little lamb";
730
731     fn bench_to_str(b: &mut Bencher, s: &str) {
732         b.iter(|| {
733             let c_str = s.to_c_str();
734             c_str.with_ref(|c_str_buf| check(s, c_str_buf))
735         })
736     }
737
738     #[bench]
739     fn bench_to_c_str_short(b: &mut Bencher) {
740         bench_to_str(b, s_short)
741     }
742
743     #[bench]
744     fn bench_to_c_str_medium(b: &mut Bencher) {
745         bench_to_str(b, s_medium)
746     }
747
748     #[bench]
749     fn bench_to_c_str_long(b: &mut Bencher) {
750         bench_to_str(b, s_long)
751     }
752
753     fn bench_to_c_str_unchecked(b: &mut Bencher, s: &str) {
754         b.iter(|| {
755             let c_str = unsafe { s.to_c_str_unchecked() };
756             c_str.with_ref(|c_str_buf| check(s, c_str_buf))
757         })
758     }
759
760     #[bench]
761     fn bench_to_c_str_unchecked_short(b: &mut Bencher) {
762         bench_to_c_str_unchecked(b, s_short)
763     }
764
765     #[bench]
766     fn bench_to_c_str_unchecked_medium(b: &mut Bencher) {
767         bench_to_c_str_unchecked(b, s_medium)
768     }
769
770     #[bench]
771     fn bench_to_c_str_unchecked_long(b: &mut Bencher) {
772         bench_to_c_str_unchecked(b, s_long)
773     }
774
775     fn bench_with_c_str(b: &mut Bencher, s: &str) {
776         b.iter(|| {
777             s.with_c_str(|c_str_buf| check(s, c_str_buf))
778         })
779     }
780
781     #[bench]
782     fn bench_with_c_str_short(b: &mut Bencher) {
783         bench_with_c_str(b, s_short)
784     }
785
786     #[bench]
787     fn bench_with_c_str_medium(b: &mut Bencher) {
788         bench_with_c_str(b, s_medium)
789     }
790
791     #[bench]
792     fn bench_with_c_str_long(b: &mut Bencher) {
793         bench_with_c_str(b, s_long)
794     }
795
796     fn bench_with_c_str_unchecked(b: &mut Bencher, s: &str) {
797         b.iter(|| {
798             unsafe {
799                 s.with_c_str_unchecked(|c_str_buf| check(s, c_str_buf))
800             }
801         })
802     }
803
804     #[bench]
805     fn bench_with_c_str_unchecked_short(b: &mut Bencher) {
806         bench_with_c_str_unchecked(b, s_short)
807     }
808
809     #[bench]
810     fn bench_with_c_str_unchecked_medium(b: &mut Bencher) {
811         bench_with_c_str_unchecked(b, s_medium)
812     }
813
814     #[bench]
815     fn bench_with_c_str_unchecked_long(b: &mut Bencher) {
816         bench_with_c_str_unchecked(b, s_long)
817     }
818 }