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