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