]> git.lizzy.rs Git - rust.git/blob - src/librustrt/c_str.rs
Rename all raw pointers as necessary
[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: *const 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: *const 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 *const 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: *const 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) -> *const 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: |*const 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: |*const 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: |*const 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: |*const 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: |*const 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: |*const 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: |*const 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 *const libc::c_char, true)
368     }
369
370     fn with_c_str<T>(&self, f: |*const 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: |*const 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,
381                         f: |*const libc::c_char| -> T) -> T {
382     if v.len() < BUF_LEN {
383         let mut buf: [u8, .. BUF_LEN] = mem::uninitialized();
384         slice::bytes::copy_memory(buf, v);
385         buf[v.len()] = 0;
386
387         let buf = buf.as_mut_ptr();
388         if checked {
389             check_for_null(v, buf as *mut libc::c_char);
390         }
391
392         f(buf as *const libc::c_char)
393     } else if checked {
394         v.to_c_str().with_ref(f)
395     } else {
396         v.to_c_str_unchecked().with_ref(f)
397     }
398 }
399
400 #[inline]
401 fn check_for_null(v: &[u8], buf: *mut libc::c_char) {
402     for i in range(0, v.len()) {
403         unsafe {
404             let p = buf.offset(i as int);
405             assert!(*p != 0);
406         }
407     }
408 }
409
410 /// External iterator for a CString's bytes.
411 ///
412 /// Use with the `std::iter` module.
413 pub struct CChars<'a> {
414     ptr: *const libc::c_char,
415     marker: marker::ContravariantLifetime<'a>,
416 }
417
418 impl<'a> Iterator<libc::c_char> for CChars<'a> {
419     fn next(&mut self) -> Option<libc::c_char> {
420         let ch = unsafe { *self.ptr };
421         if ch == 0 {
422             None
423         } else {
424             self.ptr = unsafe { self.ptr.offset(1) };
425             Some(ch)
426         }
427     }
428 }
429
430 /// Parses a C "multistring", eg windows env values or
431 /// the req->ptr result in a uv_fs_readdir() call.
432 ///
433 /// Optionally, a `count` can be passed in, limiting the
434 /// parsing to only being done `count`-times.
435 ///
436 /// The specified closure is invoked with each string that
437 /// is found, and the number of strings found is returned.
438 pub unsafe fn from_c_multistring(buf: *const libc::c_char,
439                                  count: Option<uint>,
440                                  f: |&CString|) -> uint {
441
442     let mut curr_ptr: uint = buf as uint;
443     let mut ctr = 0;
444     let (limited_count, limit) = match count {
445         Some(limit) => (true, limit),
446         None => (false, 0)
447     };
448     while ((limited_count && ctr < limit) || !limited_count)
449           && *(curr_ptr as *const libc::c_char) != 0 as libc::c_char {
450         let cstr = CString::new(curr_ptr as *const libc::c_char, false);
451         f(&cstr);
452         curr_ptr += cstr.len() + 1;
453         ctr += 1;
454     }
455     return ctr;
456 }
457
458 #[cfg(test)]
459 mod tests {
460     use std::prelude::*;
461     use std::ptr;
462     use std::task;
463     use libc;
464
465     use super::*;
466
467     #[test]
468     fn test_str_multistring_parsing() {
469         unsafe {
470             let input = b"zero\0one\0\0";
471             let ptr = input.as_ptr();
472             let expected = ["zero", "one"];
473             let mut it = expected.iter();
474             let result = from_c_multistring(ptr as *const libc::c_char, None, |c| {
475                 let cbytes = c.as_bytes_no_nul();
476                 assert_eq!(cbytes, it.next().unwrap().as_bytes());
477             });
478             assert_eq!(result, 2);
479             assert!(it.next().is_none());
480         }
481     }
482
483     #[test]
484     fn test_str_to_c_str() {
485         "".to_c_str().with_ref(|buf| {
486             unsafe {
487                 assert_eq!(*buf.offset(0), 0);
488             }
489         });
490
491         "hello".to_c_str().with_ref(|buf| {
492             unsafe {
493                 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
494                 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
495                 assert_eq!(*buf.offset(2), 'l' as libc::c_char);
496                 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
497                 assert_eq!(*buf.offset(4), 'o' as libc::c_char);
498                 assert_eq!(*buf.offset(5), 0);
499             }
500         })
501     }
502
503     #[test]
504     fn test_vec_to_c_str() {
505         let b: &[u8] = [];
506         b.to_c_str().with_ref(|buf| {
507             unsafe {
508                 assert_eq!(*buf.offset(0), 0);
509             }
510         });
511
512         let _ = b"hello".to_c_str().with_ref(|buf| {
513             unsafe {
514                 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
515                 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
516                 assert_eq!(*buf.offset(2), 'l' as libc::c_char);
517                 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
518                 assert_eq!(*buf.offset(4), 'o' as libc::c_char);
519                 assert_eq!(*buf.offset(5), 0);
520             }
521         });
522
523         let _ = b"foo\xFF".to_c_str().with_ref(|buf| {
524             unsafe {
525                 assert_eq!(*buf.offset(0), 'f' as libc::c_char);
526                 assert_eq!(*buf.offset(1), 'o' as libc::c_char);
527                 assert_eq!(*buf.offset(2), 'o' as libc::c_char);
528                 assert_eq!(*buf.offset(3), 0xff as i8);
529                 assert_eq!(*buf.offset(4), 0);
530             }
531         });
532     }
533
534     #[test]
535     fn test_is_null() {
536         let c_str = unsafe { CString::new(ptr::null(), false) };
537         assert!(c_str.is_null());
538         assert!(!c_str.is_not_null());
539     }
540
541     #[test]
542     fn test_unwrap() {
543         let c_str = "hello".to_c_str();
544         unsafe { libc::free(c_str.unwrap() as *mut libc::c_void) }
545     }
546
547     #[test]
548     fn test_with_ref() {
549         let c_str = "hello".to_c_str();
550         let len = unsafe { c_str.with_ref(|buf| libc::strlen(buf)) };
551         assert!(!c_str.is_null());
552         assert!(c_str.is_not_null());
553         assert_eq!(len, 5);
554     }
555
556     #[test]
557     #[should_fail]
558     fn test_with_ref_empty_fail() {
559         let c_str = unsafe { CString::new(ptr::null(), false) };
560         c_str.with_ref(|_| ());
561     }
562
563     #[test]
564     fn test_iterator() {
565         let c_str = "".to_c_str();
566         let mut iter = c_str.iter();
567         assert_eq!(iter.next(), None);
568
569         let c_str = "hello".to_c_str();
570         let mut iter = c_str.iter();
571         assert_eq!(iter.next(), Some('h' as libc::c_char));
572         assert_eq!(iter.next(), Some('e' as libc::c_char));
573         assert_eq!(iter.next(), Some('l' as libc::c_char));
574         assert_eq!(iter.next(), Some('l' as libc::c_char));
575         assert_eq!(iter.next(), Some('o' as libc::c_char));
576         assert_eq!(iter.next(), None);
577     }
578
579     #[test]
580     fn test_to_c_str_fail() {
581         assert!(task::try(proc() { "he\x00llo".to_c_str() }).is_err());
582     }
583
584     #[test]
585     fn test_to_c_str_unchecked() {
586         unsafe {
587             "he\x00llo".to_c_str_unchecked().with_ref(|buf| {
588                 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
589                 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
590                 assert_eq!(*buf.offset(2), 0);
591                 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
592                 assert_eq!(*buf.offset(4), 'l' as libc::c_char);
593                 assert_eq!(*buf.offset(5), 'o' as libc::c_char);
594                 assert_eq!(*buf.offset(6), 0);
595             })
596         }
597     }
598
599     #[test]
600     fn test_as_bytes() {
601         let c_str = "hello".to_c_str();
602         assert_eq!(c_str.as_bytes(), b"hello\0");
603         let c_str = "".to_c_str();
604         assert_eq!(c_str.as_bytes(), b"\0");
605         let c_str = b"foo\xFF".to_c_str();
606         assert_eq!(c_str.as_bytes(), b"foo\xFF\0");
607     }
608
609     #[test]
610     fn test_as_bytes_no_nul() {
611         let c_str = "hello".to_c_str();
612         assert_eq!(c_str.as_bytes_no_nul(), b"hello");
613         let c_str = "".to_c_str();
614         let exp: &[u8] = [];
615         assert_eq!(c_str.as_bytes_no_nul(), exp);
616         let c_str = b"foo\xFF".to_c_str();
617         assert_eq!(c_str.as_bytes_no_nul(), b"foo\xFF");
618     }
619
620     #[test]
621     #[should_fail]
622     fn test_as_bytes_fail() {
623         let c_str = unsafe { CString::new(ptr::null(), false) };
624         c_str.as_bytes();
625     }
626
627     #[test]
628     #[should_fail]
629     fn test_as_bytes_no_nul_fail() {
630         let c_str = unsafe { CString::new(ptr::null(), false) };
631         c_str.as_bytes_no_nul();
632     }
633
634     #[test]
635     fn test_as_str() {
636         let c_str = "hello".to_c_str();
637         assert_eq!(c_str.as_str(), Some("hello"));
638         let c_str = "".to_c_str();
639         assert_eq!(c_str.as_str(), Some(""));
640         let c_str = b"foo\xFF".to_c_str();
641         assert_eq!(c_str.as_str(), None);
642     }
643
644     #[test]
645     #[should_fail]
646     fn test_as_str_fail() {
647         let c_str = unsafe { CString::new(ptr::null(), false) };
648         c_str.as_str();
649     }
650
651     #[test]
652     #[should_fail]
653     fn test_len_fail() {
654         let c_str = unsafe { CString::new(ptr::null(), false) };
655         c_str.len();
656     }
657
658     #[test]
659     #[should_fail]
660     fn test_iter_fail() {
661         let c_str = unsafe { CString::new(ptr::null(), false) };
662         c_str.iter();
663     }
664
665     #[test]
666     fn test_clone() {
667         let a = "hello".to_c_str();
668         let b = a.clone();
669         assert!(a == b);
670     }
671
672     #[test]
673     fn test_clone_noleak() {
674         fn foo(f: |c: &CString|) {
675             let s = "test".to_string();
676             let c = s.to_c_str();
677             // give the closure a non-owned CString
678             let mut c_ = c.with_ref(|c| unsafe { CString::new(c, false) } );
679             f(&c_);
680             // muck with the buffer for later printing
681             c_.with_mut_ref(|c| unsafe { *c = 'X' as libc::c_char } );
682         }
683
684         let mut c_: Option<CString> = None;
685         foo(|c| {
686             c_ = Some(c.clone());
687             c.clone();
688             // force a copy, reading the memory
689             c.as_bytes().to_owned();
690         });
691         let c_ = c_.unwrap();
692         // force a copy, reading the memory
693         c_.as_bytes().to_owned();
694     }
695
696     #[test]
697     fn test_clone_eq_null() {
698         let x = unsafe { CString::new(ptr::null(), false) };
699         let y = x.clone();
700         assert!(x == y);
701     }
702 }
703
704 #[cfg(test)]
705 mod bench {
706     use test::Bencher;
707     use libc;
708     use std::prelude::*;
709
710     #[inline]
711     fn check(s: &str, c_str: *const libc::c_char) {
712         let s_buf = s.as_ptr();
713         for i in range(0, s.len()) {
714             unsafe {
715                 assert_eq!(
716                     *s_buf.offset(i as int) as libc::c_char,
717                     *c_str.offset(i as int));
718             }
719         }
720     }
721
722     static s_short: &'static str = "Mary";
723     static s_medium: &'static str = "Mary had a little lamb";
724     static s_long: &'static str = "\
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         Mary had a little lamb, Little lamb";
731
732     fn bench_to_str(b: &mut Bencher, s: &str) {
733         b.iter(|| {
734             let c_str = s.to_c_str();
735             c_str.with_ref(|c_str_buf| check(s, c_str_buf))
736         })
737     }
738
739     #[bench]
740     fn bench_to_c_str_short(b: &mut Bencher) {
741         bench_to_str(b, s_short)
742     }
743
744     #[bench]
745     fn bench_to_c_str_medium(b: &mut Bencher) {
746         bench_to_str(b, s_medium)
747     }
748
749     #[bench]
750     fn bench_to_c_str_long(b: &mut Bencher) {
751         bench_to_str(b, s_long)
752     }
753
754     fn bench_to_c_str_unchecked(b: &mut Bencher, s: &str) {
755         b.iter(|| {
756             let c_str = unsafe { s.to_c_str_unchecked() };
757             c_str.with_ref(|c_str_buf| check(s, c_str_buf))
758         })
759     }
760
761     #[bench]
762     fn bench_to_c_str_unchecked_short(b: &mut Bencher) {
763         bench_to_c_str_unchecked(b, s_short)
764     }
765
766     #[bench]
767     fn bench_to_c_str_unchecked_medium(b: &mut Bencher) {
768         bench_to_c_str_unchecked(b, s_medium)
769     }
770
771     #[bench]
772     fn bench_to_c_str_unchecked_long(b: &mut Bencher) {
773         bench_to_c_str_unchecked(b, s_long)
774     }
775
776     fn bench_with_c_str(b: &mut Bencher, s: &str) {
777         b.iter(|| {
778             s.with_c_str(|c_str_buf| check(s, c_str_buf))
779         })
780     }
781
782     #[bench]
783     fn bench_with_c_str_short(b: &mut Bencher) {
784         bench_with_c_str(b, s_short)
785     }
786
787     #[bench]
788     fn bench_with_c_str_medium(b: &mut Bencher) {
789         bench_with_c_str(b, s_medium)
790     }
791
792     #[bench]
793     fn bench_with_c_str_long(b: &mut Bencher) {
794         bench_with_c_str(b, s_long)
795     }
796
797     fn bench_with_c_str_unchecked(b: &mut Bencher, s: &str) {
798         b.iter(|| {
799             unsafe {
800                 s.with_c_str_unchecked(|c_str_buf| check(s, c_str_buf))
801             }
802         })
803     }
804
805     #[bench]
806     fn bench_with_c_str_unchecked_short(b: &mut Bencher) {
807         bench_with_c_str_unchecked(b, s_short)
808     }
809
810     #[bench]
811     fn bench_with_c_str_unchecked_medium(b: &mut Bencher) {
812         bench_with_c_str_unchecked(b, s_medium)
813     }
814
815     #[bench]
816     fn bench_with_c_str_unchecked_long(b: &mut Bencher) {
817         bench_with_c_str_unchecked(b, s_long)
818     }
819 }