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