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