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