]> git.lizzy.rs Git - rust.git/blob - src/libstd/ffi/c_str.rs
cstring: avoid excessive growth just to 0-terminate
[rust.git] / src / libstd / ffi / 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 use ascii;
12 use borrow::{Cow, ToOwned, Borrow};
13 use boxed::Box;
14 use convert::{Into, From};
15 use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
16 use error::Error;
17 use fmt::{self, Write};
18 use io;
19 use iter::Iterator;
20 use libc;
21 use mem;
22 use memchr;
23 use ops;
24 use option::Option::{self, Some, None};
25 use os::raw::c_char;
26 use result::Result::{self, Ok, Err};
27 use slice;
28 use str::{self, Utf8Error};
29 use string::String;
30 use vec::Vec;
31
32 /// A type representing an owned C-compatible string
33 ///
34 /// This type serves the primary purpose of being able to safely generate a
35 /// C-compatible string from a Rust byte slice or vector. An instance of this
36 /// type is a static guarantee that the underlying bytes contain no interior 0
37 /// bytes and the final byte is 0.
38 ///
39 /// A `CString` is created from either a byte slice or a byte vector. After
40 /// being created, a `CString` predominately inherits all of its methods from
41 /// the `Deref` implementation to `[c_char]`. Note that the underlying array
42 /// is represented as an array of `c_char` as opposed to `u8`. A `u8` slice
43 /// can be obtained with the `as_bytes` method.  Slices produced from a `CString`
44 /// do *not* contain the trailing nul terminator unless otherwise specified.
45 ///
46 /// # Examples
47 ///
48 /// ```no_run
49 /// # fn main() {
50 /// use std::ffi::CString;
51 /// use std::os::raw::c_char;
52 ///
53 /// extern {
54 ///     fn my_printer(s: *const c_char);
55 /// }
56 ///
57 /// let c_to_print = CString::new("Hello, world!").unwrap();
58 /// unsafe {
59 ///     my_printer(c_to_print.as_ptr());
60 /// }
61 /// # }
62 /// ```
63 ///
64 /// # Safety
65 ///
66 /// `CString` is intended for working with traditional C-style strings
67 /// (a sequence of non-null bytes terminated by a single null byte); the
68 /// primary use case for these kinds of strings is interoperating with C-like
69 /// code. Often you will need to transfer ownership to/from that external
70 /// code. It is strongly recommended that you thoroughly read through the
71 /// documentation of `CString` before use, as improper ownership management
72 /// of `CString` instances can lead to invalid memory accesses, memory leaks,
73 /// and other memory errors.
74
75 #[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
76 #[stable(feature = "rust1", since = "1.0.0")]
77 pub struct CString {
78     inner: Box<[u8]>,
79 }
80
81 /// Representation of a borrowed C string.
82 ///
83 /// This dynamically sized type is only safely constructed via a borrowed
84 /// version of an instance of `CString`. This type can be constructed from a raw
85 /// C string as well and represents a C string borrowed from another location.
86 ///
87 /// Note that this structure is **not** `repr(C)` and is not recommended to be
88 /// placed in the signatures of FFI functions. Instead safe wrappers of FFI
89 /// functions may leverage the unsafe `from_ptr` constructor to provide a safe
90 /// interface to other consumers.
91 ///
92 /// # Examples
93 ///
94 /// Inspecting a foreign C string
95 ///
96 /// ```no_run
97 /// use std::ffi::CStr;
98 /// use std::os::raw::c_char;
99 ///
100 /// extern { fn my_string() -> *const c_char; }
101 ///
102 /// unsafe {
103 ///     let slice = CStr::from_ptr(my_string());
104 ///     println!("string length: {}", slice.to_bytes().len());
105 /// }
106 /// ```
107 ///
108 /// Passing a Rust-originating C string
109 ///
110 /// ```no_run
111 /// use std::ffi::{CString, CStr};
112 /// use std::os::raw::c_char;
113 ///
114 /// fn work(data: &CStr) {
115 ///     extern { fn work_with(data: *const c_char); }
116 ///
117 ///     unsafe { work_with(data.as_ptr()) }
118 /// }
119 ///
120 /// let s = CString::new("data data data data").unwrap();
121 /// work(&s);
122 /// ```
123 ///
124 /// Converting a foreign C string into a Rust `String`
125 ///
126 /// ```no_run
127 /// use std::ffi::CStr;
128 /// use std::os::raw::c_char;
129 ///
130 /// extern { fn my_string() -> *const c_char; }
131 ///
132 /// fn my_string_safe() -> String {
133 ///     unsafe {
134 ///         CStr::from_ptr(my_string()).to_string_lossy().into_owned()
135 ///     }
136 /// }
137 ///
138 /// println!("string: {}", my_string_safe());
139 /// ```
140 #[derive(Hash)]
141 #[stable(feature = "rust1", since = "1.0.0")]
142 pub struct CStr {
143     // FIXME: this should not be represented with a DST slice but rather with
144     //        just a raw `c_char` along with some form of marker to make
145     //        this an unsized type. Essentially `sizeof(&CStr)` should be the
146     //        same as `sizeof(&c_char)` but `CStr` should be an unsized type.
147     inner: [c_char]
148 }
149
150 /// An error returned from `CString::new` to indicate that a nul byte was found
151 /// in the vector provided.
152 #[derive(Clone, PartialEq, Debug)]
153 #[stable(feature = "rust1", since = "1.0.0")]
154 pub struct NulError(usize, Vec<u8>);
155
156 /// An error returned from `CStr::from_bytes_with_nul` to indicate that a nul
157 /// byte was found too early in the slice provided or one wasn't found at all.
158 #[derive(Clone, PartialEq, Debug)]
159 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
160 pub struct FromBytesWithNulError { _a: () }
161
162 /// An error returned from `CString::into_string` to indicate that a UTF-8 error
163 /// was encountered during the conversion.
164 #[derive(Clone, PartialEq, Debug)]
165 #[stable(feature = "cstring_into", since = "1.7.0")]
166 pub struct IntoStringError {
167     inner: CString,
168     error: Utf8Error,
169 }
170
171 impl CString {
172     /// Creates a new C-compatible string from a container of bytes.
173     ///
174     /// This method will consume the provided data and use the underlying bytes
175     /// to construct a new string, ensuring that there is a trailing 0 byte.
176     ///
177     /// # Examples
178     ///
179     /// ```no_run
180     /// use std::ffi::CString;
181     /// use std::os::raw::c_char;
182     ///
183     /// extern { fn puts(s: *const c_char); }
184     ///
185     /// let to_print = CString::new("Hello!").unwrap();
186     /// unsafe {
187     ///     puts(to_print.as_ptr());
188     /// }
189     /// ```
190     ///
191     /// # Errors
192     ///
193     /// This function will return an error if the bytes yielded contain an
194     /// internal 0 byte. The error returned will contain the bytes as well as
195     /// the position of the nul byte.
196     #[stable(feature = "rust1", since = "1.0.0")]
197     pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
198         Self::_new(t.into())
199     }
200
201     fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
202         match memchr::memchr(0, &bytes) {
203             Some(i) => Err(NulError(i, bytes)),
204             None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
205         }
206     }
207
208     /// Creates a C-compatible string from a byte vector without checking for
209     /// interior 0 bytes.
210     ///
211     /// This method is equivalent to `new` except that no runtime assertion
212     /// is made that `v` contains no 0 bytes, and it requires an actual
213     /// byte vector, not anything that can be converted to one with Into.
214     #[stable(feature = "rust1", since = "1.0.0")]
215     pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
216         v.reserve_exact(1);
217         v.push(0);
218         CString { inner: v.into_boxed_slice() }
219     }
220
221     /// Retakes ownership of a `CString` that was transferred to C.
222     ///
223     /// This should only ever be called with a pointer that was earlier
224     /// obtained by calling `into_raw` on a `CString`. Additionally, the length
225     /// of the string will be recalculated from the pointer.
226     #[stable(feature = "cstr_memory", since = "1.4.0")]
227     pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
228         let len = libc::strlen(ptr) + 1; // Including the NUL byte
229         let slice = slice::from_raw_parts(ptr, len as usize);
230         CString { inner: mem::transmute(slice) }
231     }
232
233     /// Transfers ownership of the string to a C caller.
234     ///
235     /// The pointer must be returned to Rust and reconstituted using
236     /// `from_raw` to be properly deallocated. Specifically, one
237     /// should *not* use the standard C `free` function to deallocate
238     /// this string.
239     ///
240     /// Failure to call `from_raw` will lead to a memory leak.
241     #[stable(feature = "cstr_memory", since = "1.4.0")]
242     pub fn into_raw(self) -> *mut c_char {
243         Box::into_raw(self.inner) as *mut c_char
244     }
245
246     /// Converts the `CString` into a `String` if it contains valid Unicode data.
247     ///
248     /// On failure, ownership of the original `CString` is returned.
249     #[stable(feature = "cstring_into", since = "1.7.0")]
250     pub fn into_string(self) -> Result<String, IntoStringError> {
251         String::from_utf8(self.into_bytes())
252             .map_err(|e| IntoStringError {
253                 error: e.utf8_error(),
254                 inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
255             })
256     }
257
258     /// Returns the underlying byte buffer.
259     ///
260     /// The returned buffer does **not** contain the trailing nul separator and
261     /// it is guaranteed to not have any interior nul bytes.
262     #[stable(feature = "cstring_into", since = "1.7.0")]
263     pub fn into_bytes(self) -> Vec<u8> {
264         let mut vec = self.inner.into_vec();
265         let _nul = vec.pop();
266         debug_assert_eq!(_nul, Some(0u8));
267         vec
268     }
269
270     /// Equivalent to the `into_bytes` function except that the returned vector
271     /// includes the trailing nul byte.
272     #[stable(feature = "cstring_into", since = "1.7.0")]
273     pub fn into_bytes_with_nul(self) -> Vec<u8> {
274         self.inner.into_vec()
275     }
276
277     /// Returns the contents of this `CString` as a slice of bytes.
278     ///
279     /// The returned slice does **not** contain the trailing nul separator and
280     /// it is guaranteed to not have any interior nul bytes.
281     #[stable(feature = "rust1", since = "1.0.0")]
282     pub fn as_bytes(&self) -> &[u8] {
283         &self.inner[..self.inner.len() - 1]
284     }
285
286     /// Equivalent to the `as_bytes` function except that the returned slice
287     /// includes the trailing nul byte.
288     #[stable(feature = "rust1", since = "1.0.0")]
289     pub fn as_bytes_with_nul(&self) -> &[u8] {
290         &self.inner
291     }
292 }
293
294 #[stable(feature = "rust1", since = "1.0.0")]
295 impl ops::Deref for CString {
296     type Target = CStr;
297
298     fn deref(&self) -> &CStr {
299         unsafe { mem::transmute(self.as_bytes_with_nul()) }
300     }
301 }
302
303 #[stable(feature = "rust1", since = "1.0.0")]
304 impl fmt::Debug for CString {
305     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
306         fmt::Debug::fmt(&**self, f)
307     }
308 }
309
310 #[stable(feature = "cstring_into", since = "1.7.0")]
311 impl From<CString> for Vec<u8> {
312     fn from(s: CString) -> Vec<u8> {
313         s.into_bytes()
314     }
315 }
316
317 #[stable(feature = "cstr_debug", since = "1.3.0")]
318 impl fmt::Debug for CStr {
319     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
320         write!(f, "\"")?;
321         for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
322             f.write_char(byte as char)?;
323         }
324         write!(f, "\"")
325     }
326 }
327
328 #[stable(feature = "cstr_default", since = "1.10.0")]
329 impl<'a> Default for &'a CStr {
330     fn default() -> &'a CStr {
331         static SLICE: &'static [c_char] = &[0];
332         unsafe { CStr::from_ptr(SLICE.as_ptr()) }
333     }
334 }
335
336 #[stable(feature = "cstr_default", since = "1.10.0")]
337 impl Default for CString {
338     fn default() -> CString {
339         let a: &CStr = Default::default();
340         a.to_owned()
341     }
342 }
343
344 #[stable(feature = "cstr_borrow", since = "1.3.0")]
345 impl Borrow<CStr> for CString {
346     fn borrow(&self) -> &CStr { self }
347 }
348
349 impl NulError {
350     /// Returns the position of the nul byte in the slice that was provided to
351     /// `CString::new`.
352     ///
353     /// # Examples
354     ///
355     /// ```
356     /// use std::ffi::CString;
357     ///
358     /// let nul_error = CString::new("foo\0bar").unwrap_err();
359     /// assert_eq!(nul_error.nul_position(), 3);
360     ///
361     /// let nul_error = CString::new("foo bar\0").unwrap_err();
362     /// assert_eq!(nul_error.nul_position(), 7);
363     /// ```
364     #[stable(feature = "rust1", since = "1.0.0")]
365     pub fn nul_position(&self) -> usize { self.0 }
366
367     /// Consumes this error, returning the underlying vector of bytes which
368     /// generated the error in the first place.
369     ///
370     /// # Examples
371     ///
372     /// ```
373     /// use std::ffi::CString;
374     ///
375     /// let nul_error = CString::new("foo\0bar").unwrap_err();
376     /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
377     /// ```
378     #[stable(feature = "rust1", since = "1.0.0")]
379     pub fn into_vec(self) -> Vec<u8> { self.1 }
380 }
381
382 #[stable(feature = "rust1", since = "1.0.0")]
383 impl Error for NulError {
384     fn description(&self) -> &str { "nul byte found in data" }
385 }
386
387 #[stable(feature = "rust1", since = "1.0.0")]
388 impl fmt::Display for NulError {
389     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
390         write!(f, "nul byte found in provided data at position: {}", self.0)
391     }
392 }
393
394 #[stable(feature = "rust1", since = "1.0.0")]
395 impl From<NulError> for io::Error {
396     fn from(_: NulError) -> io::Error {
397         io::Error::new(io::ErrorKind::InvalidInput,
398                        "data provided contains a nul byte")
399     }
400 }
401
402 impl IntoStringError {
403     /// Consumes this error, returning original `CString` which generated the
404     /// error.
405     #[stable(feature = "cstring_into", since = "1.7.0")]
406     pub fn into_cstring(self) -> CString {
407         self.inner
408     }
409
410     /// Access the underlying UTF-8 error that was the cause of this error.
411     #[stable(feature = "cstring_into", since = "1.7.0")]
412     pub fn utf8_error(&self) -> Utf8Error {
413         self.error
414     }
415 }
416
417 #[stable(feature = "cstring_into", since = "1.7.0")]
418 impl Error for IntoStringError {
419     fn description(&self) -> &str {
420         "C string contained non-utf8 bytes"
421     }
422
423     fn cause(&self) -> Option<&Error> {
424         Some(&self.error)
425     }
426 }
427
428 #[stable(feature = "cstring_into", since = "1.7.0")]
429 impl fmt::Display for IntoStringError {
430     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
431         self.description().fmt(f)
432     }
433 }
434
435 impl CStr {
436     /// Casts a raw C string to a safe C string wrapper.
437     ///
438     /// This function will cast the provided `ptr` to the `CStr` wrapper which
439     /// allows inspection and interoperation of non-owned C strings. This method
440     /// is unsafe for a number of reasons:
441     ///
442     /// * There is no guarantee to the validity of `ptr`
443     /// * The returned lifetime is not guaranteed to be the actual lifetime of
444     ///   `ptr`
445     /// * There is no guarantee that the memory pointed to by `ptr` contains a
446     ///   valid nul terminator byte at the end of the string.
447     ///
448     /// > **Note**: This operation is intended to be a 0-cost cast but it is
449     /// > currently implemented with an up-front calculation of the length of
450     /// > the string. This is not guaranteed to always be the case.
451     ///
452     /// # Examples
453     ///
454     /// ```no_run
455     /// # fn main() {
456     /// use std::ffi::CStr;
457     /// use std::os::raw::c_char;
458     ///
459     /// extern {
460     ///     fn my_string() -> *const c_char;
461     /// }
462     ///
463     /// unsafe {
464     ///     let slice = CStr::from_ptr(my_string());
465     ///     println!("string returned: {}", slice.to_str().unwrap());
466     /// }
467     /// # }
468     /// ```
469     #[stable(feature = "rust1", since = "1.0.0")]
470     pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
471         let len = libc::strlen(ptr);
472         mem::transmute(slice::from_raw_parts(ptr, len as usize + 1))
473     }
474
475     /// Creates a C string wrapper from a byte slice.
476     ///
477     /// This function will cast the provided `bytes` to a `CStr` wrapper after
478     /// ensuring that it is null terminated and does not contain any interior
479     /// nul bytes.
480     ///
481     /// # Examples
482     ///
483     /// ```
484     /// use std::ffi::CStr;
485     ///
486     /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
487     /// assert!(cstr.is_ok());
488     /// ```
489     #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
490     pub fn from_bytes_with_nul(bytes: &[u8])
491                                -> Result<&CStr, FromBytesWithNulError> {
492         if bytes.is_empty() || memchr::memchr(0, &bytes) != Some(bytes.len() - 1) {
493             Err(FromBytesWithNulError { _a: () })
494         } else {
495             Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) })
496         }
497     }
498
499     /// Unsafely creates a C string wrapper from a byte slice.
500     ///
501     /// This function will cast the provided `bytes` to a `CStr` wrapper without
502     /// performing any sanity checks. The provided slice must be null terminated
503     /// and not contain any interior nul bytes.
504     ///
505     /// # Examples
506     ///
507     /// ```
508     /// use std::ffi::{CStr, CString};
509     ///
510     /// unsafe {
511     ///     let cstring = CString::new("hello").unwrap();
512     ///     let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
513     ///     assert_eq!(cstr, &*cstring);
514     /// }
515     /// ```
516     #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
517     pub unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
518         mem::transmute(bytes)
519     }
520
521     /// Returns the inner pointer to this C string.
522     ///
523     /// The returned pointer will be valid for as long as `self` is and points
524     /// to a contiguous region of memory terminated with a 0 byte to represent
525     /// the end of the string.
526     ///
527     /// **WARNING**
528     ///
529     /// It is your responsibility to make sure that the underlying memory is not
530     /// freed too early. For example, the following code will cause undefined
531     /// behaviour when `ptr` is used inside the `unsafe` block:
532     ///
533     /// ```no_run
534     /// use std::ffi::{CString};
535     ///
536     /// let ptr = CString::new("Hello").unwrap().as_ptr();
537     /// unsafe {
538     ///     // `ptr` is dangling
539     ///     *ptr;
540     /// }
541     /// ```
542     ///
543     /// This happens because the pointer returned by `as_ptr` does not carry any
544     /// lifetime information and the string is deallocated immediately after
545     /// the `CString::new("Hello").unwrap().as_ptr()` expression is evaluated.
546     /// To fix the problem, bind the string to a local variable:
547     ///
548     /// ```no_run
549     /// use std::ffi::{CString};
550     ///
551     /// let hello = CString::new("Hello").unwrap();
552     /// let ptr = hello.as_ptr();
553     /// unsafe {
554     ///     // `ptr` is valid because `hello` is in scope
555     ///     *ptr;
556     /// }
557     /// ```
558     #[stable(feature = "rust1", since = "1.0.0")]
559     pub fn as_ptr(&self) -> *const c_char {
560         self.inner.as_ptr()
561     }
562
563     /// Converts this C string to a byte slice.
564     ///
565     /// This function will calculate the length of this string (which normally
566     /// requires a linear amount of work to be done) and then return the
567     /// resulting slice of `u8` elements.
568     ///
569     /// The returned slice will **not** contain the trailing nul that this C
570     /// string has.
571     ///
572     /// > **Note**: This method is currently implemented as a 0-cost cast, but
573     /// > it is planned to alter its definition in the future to perform the
574     /// > length calculation whenever this method is called.
575     #[stable(feature = "rust1", since = "1.0.0")]
576     pub fn to_bytes(&self) -> &[u8] {
577         let bytes = self.to_bytes_with_nul();
578         &bytes[..bytes.len() - 1]
579     }
580
581     /// Converts this C string to a byte slice containing the trailing 0 byte.
582     ///
583     /// This function is the equivalent of `to_bytes` except that it will retain
584     /// the trailing nul instead of chopping it off.
585     ///
586     /// > **Note**: This method is currently implemented as a 0-cost cast, but
587     /// > it is planned to alter its definition in the future to perform the
588     /// > length calculation whenever this method is called.
589     #[stable(feature = "rust1", since = "1.0.0")]
590     pub fn to_bytes_with_nul(&self) -> &[u8] {
591         unsafe { mem::transmute(&self.inner) }
592     }
593
594     /// Yields a `&str` slice if the `CStr` contains valid UTF-8.
595     ///
596     /// This function will calculate the length of this string and check for
597     /// UTF-8 validity, and then return the `&str` if it's valid.
598     ///
599     /// > **Note**: This method is currently implemented to check for validity
600     /// > after a 0-cost cast, but it is planned to alter its definition in the
601     /// > future to perform the length calculation in addition to the UTF-8
602     /// > check whenever this method is called.
603     #[stable(feature = "cstr_to_str", since = "1.4.0")]
604     pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
605         // NB: When CStr is changed to perform the length check in .to_bytes()
606         // instead of in from_ptr(), it may be worth considering if this should
607         // be rewritten to do the UTF-8 check inline with the length calculation
608         // instead of doing it afterwards.
609         str::from_utf8(self.to_bytes())
610     }
611
612     /// Converts a `CStr` into a `Cow<str>`.
613     ///
614     /// This function will calculate the length of this string (which normally
615     /// requires a linear amount of work to be done) and then return the
616     /// resulting slice as a `Cow<str>`, replacing any invalid UTF-8 sequences
617     /// with `U+FFFD REPLACEMENT CHARACTER`.
618     ///
619     /// > **Note**: This method is currently implemented to check for validity
620     /// > after a 0-cost cast, but it is planned to alter its definition in the
621     /// > future to perform the length calculation in addition to the UTF-8
622     /// > check whenever this method is called.
623     #[stable(feature = "cstr_to_str", since = "1.4.0")]
624     pub fn to_string_lossy(&self) -> Cow<str> {
625         String::from_utf8_lossy(self.to_bytes())
626     }
627 }
628
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl PartialEq for CStr {
631     fn eq(&self, other: &CStr) -> bool {
632         self.to_bytes().eq(other.to_bytes())
633     }
634 }
635 #[stable(feature = "rust1", since = "1.0.0")]
636 impl Eq for CStr {}
637 #[stable(feature = "rust1", since = "1.0.0")]
638 impl PartialOrd for CStr {
639     fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
640         self.to_bytes().partial_cmp(&other.to_bytes())
641     }
642 }
643 #[stable(feature = "rust1", since = "1.0.0")]
644 impl Ord for CStr {
645     fn cmp(&self, other: &CStr) -> Ordering {
646         self.to_bytes().cmp(&other.to_bytes())
647     }
648 }
649
650 #[stable(feature = "cstr_borrow", since = "1.3.0")]
651 impl ToOwned for CStr {
652     type Owned = CString;
653
654     fn to_owned(&self) -> CString {
655         unsafe { CString::from_vec_unchecked(self.to_bytes().to_vec()) }
656     }
657 }
658
659 #[stable(feature = "cstring_asref", since = "1.7.0")]
660 impl<'a> From<&'a CStr> for CString {
661     fn from(s: &'a CStr) -> CString {
662         s.to_owned()
663     }
664 }
665
666 #[stable(feature = "cstring_asref", since = "1.7.0")]
667 impl ops::Index<ops::RangeFull> for CString {
668     type Output = CStr;
669
670     #[inline]
671     fn index(&self, _index: ops::RangeFull) -> &CStr {
672         self
673     }
674 }
675
676 #[stable(feature = "cstring_asref", since = "1.7.0")]
677 impl AsRef<CStr> for CStr {
678     fn as_ref(&self) -> &CStr {
679         self
680     }
681 }
682
683 #[stable(feature = "cstring_asref", since = "1.7.0")]
684 impl AsRef<CStr> for CString {
685     fn as_ref(&self) -> &CStr {
686         self
687     }
688 }
689
690 #[cfg(test)]
691 mod tests {
692     use prelude::v1::*;
693     use super::*;
694     use os::raw::c_char;
695     use borrow::Cow::{Borrowed, Owned};
696     use hash::{SipHasher, Hash, Hasher};
697
698     #[test]
699     fn c_to_rust() {
700         let data = b"123\0";
701         let ptr = data.as_ptr() as *const c_char;
702         unsafe {
703             assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
704             assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
705         }
706     }
707
708     #[test]
709     fn simple() {
710         let s = CString::new("1234").unwrap();
711         assert_eq!(s.as_bytes(), b"1234");
712         assert_eq!(s.as_bytes_with_nul(), b"1234\0");
713     }
714
715     #[test]
716     fn build_with_zero1() {
717         assert!(CString::new(&b"\0"[..]).is_err());
718     }
719     #[test]
720     fn build_with_zero2() {
721         assert!(CString::new(vec![0]).is_err());
722     }
723
724     #[test]
725     fn build_with_zero3() {
726         unsafe {
727             let s = CString::from_vec_unchecked(vec![0]);
728             assert_eq!(s.as_bytes(), b"\0");
729         }
730     }
731
732     #[test]
733     fn formatted() {
734         let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
735         assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
736     }
737
738     #[test]
739     fn borrowed() {
740         unsafe {
741             let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
742             assert_eq!(s.to_bytes(), b"12");
743             assert_eq!(s.to_bytes_with_nul(), b"12\0");
744         }
745     }
746
747     #[test]
748     fn to_str() {
749         let data = b"123\xE2\x80\xA6\0";
750         let ptr = data.as_ptr() as *const c_char;
751         unsafe {
752             assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
753             assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
754         }
755         let data = b"123\xE2\0";
756         let ptr = data.as_ptr() as *const c_char;
757         unsafe {
758             assert!(CStr::from_ptr(ptr).to_str().is_err());
759             assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
760         }
761     }
762
763     #[test]
764     fn to_owned() {
765         let data = b"123\0";
766         let ptr = data.as_ptr() as *const c_char;
767
768         let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
769         assert_eq!(owned.as_bytes_with_nul(), data);
770     }
771
772     #[test]
773     fn equal_hash() {
774         let data = b"123\xE2\xFA\xA6\0";
775         let ptr = data.as_ptr() as *const c_char;
776         let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
777
778         let mut s = SipHasher::new_with_keys(0, 0);
779         cstr.hash(&mut s);
780         let cstr_hash = s.finish();
781         let mut s = SipHasher::new_with_keys(0, 0);
782         CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
783         let cstring_hash = s.finish();
784
785         assert_eq!(cstr_hash, cstring_hash);
786     }
787
788     #[test]
789     fn from_bytes_with_nul() {
790         let data = b"123\0";
791         let cstr = CStr::from_bytes_with_nul(data);
792         assert_eq!(cstr.map(CStr::to_bytes), Ok(&b"123"[..]));
793         let cstr = CStr::from_bytes_with_nul(data);
794         assert_eq!(cstr.map(CStr::to_bytes_with_nul), Ok(&b"123\0"[..]));
795
796         unsafe {
797             let cstr = CStr::from_bytes_with_nul(data);
798             let cstr_unchecked = CStr::from_bytes_with_nul_unchecked(data);
799             assert_eq!(cstr, Ok(cstr_unchecked));
800         }
801     }
802
803     #[test]
804     fn from_bytes_with_nul_unterminated() {
805         let data = b"123";
806         let cstr = CStr::from_bytes_with_nul(data);
807         assert!(cstr.is_err());
808     }
809
810     #[test]
811     fn from_bytes_with_nul_interior() {
812         let data = b"1\023\0";
813         let cstr = CStr::from_bytes_with_nul(data);
814         assert!(cstr.is_err());
815     }
816 }