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