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