]> git.lizzy.rs Git - rust.git/blob - src/libstd/ffi/c_str.rs
4bac9a4917d8f0a07b4cf4c852cba539d650d7f4
[rust.git] / src / libstd / ffi / c_str.rs
1 use crate::ascii;
2 use crate::borrow::{Borrow, Cow};
3 use crate::cmp::Ordering;
4 use crate::error::Error;
5 use crate::fmt::{self, Write};
6 use crate::io;
7 use crate::mem;
8 use crate::memchr;
9 use crate::num::NonZeroU8;
10 use crate::ops;
11 use crate::os::raw::c_char;
12 use crate::ptr;
13 use crate::rc::Rc;
14 use crate::slice;
15 use crate::str::{self, Utf8Error};
16 use crate::sync::Arc;
17 use crate::sys;
18
19 /// A type representing an owned, C-compatible, nul-terminated string with no nul bytes in the
20 /// middle.
21 ///
22 /// This type serves the purpose of being able to safely generate a
23 /// C-compatible string from a Rust byte slice or vector. An instance of this
24 /// type is a static guarantee that the underlying bytes contain no interior 0
25 /// bytes ("nul characters") and that the final byte is 0 ("nul terminator").
26 ///
27 /// `CString` is to [`&CStr`] as [`String`] is to [`&str`]: the former
28 /// in each pair are owned strings; the latter are borrowed
29 /// references.
30 ///
31 /// # Creating a `CString`
32 ///
33 /// A `CString` is created from either a byte slice or a byte vector,
34 /// or anything that implements [`Into`]`<`[`Vec`]`<`[`u8`]`>>` (for
35 /// example, you can build a `CString` straight out of a [`String`] or
36 /// a [`&str`], since both implement that trait).
37 ///
38 /// The [`new`] method will actually check that the provided `&[u8]`
39 /// does not have 0 bytes in the middle, and return an error if it
40 /// finds one.
41 ///
42 /// # Extracting a raw pointer to the whole C string
43 ///
44 /// `CString` implements a [`as_ptr`] method through the [`Deref`]
45 /// trait. This method will give you a `*const c_char` which you can
46 /// feed directly to extern functions that expect a nul-terminated
47 /// string, like C's `strdup()`. Notice that [`as_ptr`] returns a
48 /// read-only pointer; if the C code writes to it, that causes
49 /// undefined behavior.
50 ///
51 /// # Extracting a slice of the whole C string
52 ///
53 /// Alternatively, you can obtain a `&[`[`u8`]`]` slice from a
54 /// `CString` with the [`as_bytes`] method. Slices produced in this
55 /// way do *not* contain the trailing nul terminator. This is useful
56 /// when you will be calling an extern function that takes a `*const
57 /// u8` argument which is not necessarily nul-terminated, plus another
58 /// argument with the length of the string — like C's `strndup()`.
59 /// You can of course get the slice's length with its
60 /// [`len`][slice.len] method.
61 ///
62 /// If you need a `&[`[`u8`]`]` slice *with* the nul terminator, you
63 /// can use [`as_bytes_with_nul`] instead.
64 ///
65 /// Once you have the kind of slice you need (with or without a nul
66 /// terminator), you can call the slice's own
67 /// [`as_ptr`][slice.as_ptr] method to get a read-only raw pointer to pass to
68 /// extern functions. See the documentation for that function for a
69 /// discussion on ensuring the lifetime of the raw pointer.
70 ///
71 /// [`Into`]: ../convert/trait.Into.html
72 /// [`Vec`]: ../vec/struct.Vec.html
73 /// [`String`]: ../string/struct.String.html
74 /// [`&str`]: ../primitive.str.html
75 /// [`u8`]: ../primitive.u8.html
76 /// [`new`]: #method.new
77 /// [`as_bytes`]: #method.as_bytes
78 /// [`as_bytes_with_nul`]: #method.as_bytes_with_nul
79 /// [`as_ptr`]: #method.as_ptr
80 /// [slice.as_ptr]: ../primitive.slice.html#method.as_ptr
81 /// [slice.len]: ../primitive.slice.html#method.len
82 /// [`Deref`]: ../ops/trait.Deref.html
83 /// [`CStr`]: struct.CStr.html
84 /// [`&CStr`]: struct.CStr.html
85 ///
86 /// # Examples
87 ///
88 /// ```ignore (extern-declaration)
89 /// # fn main() {
90 /// use std::ffi::CString;
91 /// use std::os::raw::c_char;
92 ///
93 /// extern {
94 ///     fn my_printer(s: *const c_char);
95 /// }
96 ///
97 /// // We are certain that our string doesn't have 0 bytes in the middle,
98 /// // so we can .expect()
99 /// let c_to_print = CString::new("Hello, world!").expect("CString::new failed");
100 /// unsafe {
101 ///     my_printer(c_to_print.as_ptr());
102 /// }
103 /// # }
104 /// ```
105 ///
106 /// # Safety
107 ///
108 /// `CString` is intended for working with traditional C-style strings
109 /// (a sequence of non-nul bytes terminated by a single nul byte); the
110 /// primary use case for these kinds of strings is interoperating with C-like
111 /// code. Often you will need to transfer ownership to/from that external
112 /// code. It is strongly recommended that you thoroughly read through the
113 /// documentation of `CString` before use, as improper ownership management
114 /// of `CString` instances can lead to invalid memory accesses, memory leaks,
115 /// and other memory errors.
116
117 #[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
118 #[stable(feature = "rust1", since = "1.0.0")]
119 pub struct CString {
120     // Invariant 1: the slice ends with a zero byte and has a length of at least one.
121     // Invariant 2: the slice contains only one zero byte.
122     // Improper usage of unsafe function can break Invariant 2, but not Invariant 1.
123     inner: Box<[u8]>,
124 }
125
126 /// Representation of a borrowed C string.
127 ///
128 /// This type represents a borrowed reference to a nul-terminated
129 /// array of bytes. It can be constructed safely from a `&[`[`u8`]`]`
130 /// slice, or unsafely from a raw `*const c_char`. It can then be
131 /// converted to a Rust [`&str`] by performing UTF-8 validation, or
132 /// into an owned [`CString`].
133 ///
134 /// `&CStr` is to [`CString`] as [`&str`] is to [`String`]: the former
135 /// in each pair are borrowed references; the latter are owned
136 /// strings.
137 ///
138 /// Note that this structure is **not** `repr(C)` and is not recommended to be
139 /// placed in the signatures of FFI functions. Instead, safe wrappers of FFI
140 /// functions may leverage the unsafe [`from_ptr`] constructor to provide a safe
141 /// interface to other consumers.
142 ///
143 /// # Examples
144 ///
145 /// Inspecting a foreign C string:
146 ///
147 /// ```ignore (extern-declaration)
148 /// use std::ffi::CStr;
149 /// use std::os::raw::c_char;
150 ///
151 /// extern { fn my_string() -> *const c_char; }
152 ///
153 /// unsafe {
154 ///     let slice = CStr::from_ptr(my_string());
155 ///     println!("string buffer size without nul terminator: {}", slice.to_bytes().len());
156 /// }
157 /// ```
158 ///
159 /// Passing a Rust-originating C string:
160 ///
161 /// ```ignore (extern-declaration)
162 /// use std::ffi::{CString, CStr};
163 /// use std::os::raw::c_char;
164 ///
165 /// fn work(data: &CStr) {
166 ///     extern { fn work_with(data: *const c_char); }
167 ///
168 ///     unsafe { work_with(data.as_ptr()) }
169 /// }
170 ///
171 /// let s = CString::new("data data data data").expect("CString::new failed");
172 /// work(&s);
173 /// ```
174 ///
175 /// Converting a foreign C string into a Rust [`String`]:
176 ///
177 /// ```ignore (extern-declaration)
178 /// use std::ffi::CStr;
179 /// use std::os::raw::c_char;
180 ///
181 /// extern { fn my_string() -> *const c_char; }
182 ///
183 /// fn my_string_safe() -> String {
184 ///     unsafe {
185 ///         CStr::from_ptr(my_string()).to_string_lossy().into_owned()
186 ///     }
187 /// }
188 ///
189 /// println!("string: {}", my_string_safe());
190 /// ```
191 ///
192 /// [`u8`]: ../primitive.u8.html
193 /// [`&str`]: ../primitive.str.html
194 /// [`String`]: ../string/struct.String.html
195 /// [`CString`]: struct.CString.html
196 /// [`from_ptr`]: #method.from_ptr
197 #[derive(Hash)]
198 #[stable(feature = "rust1", since = "1.0.0")]
199 // FIXME:
200 // `fn from` in `impl From<&CStr> for Box<CStr>` current implementation relies
201 // on `CStr` being layout-compatible with `[u8]`.
202 // When attribute privacy is implemented, `CStr` should be annotated as `#[repr(transparent)]`.
203 // Anyway, `CStr` representation and layout are considered implementation detail, are
204 // not documented and must not be relied upon.
205 pub struct CStr {
206     // FIXME: this should not be represented with a DST slice but rather with
207     //        just a raw `c_char` along with some form of marker to make
208     //        this an unsized type. Essentially `sizeof(&CStr)` should be the
209     //        same as `sizeof(&c_char)` but `CStr` should be an unsized type.
210     inner: [c_char],
211 }
212
213 /// An error indicating that an interior nul byte was found.
214 ///
215 /// While Rust strings may contain nul bytes in the middle, C strings
216 /// can't, as that byte would effectively truncate the string.
217 ///
218 /// This error is created by the [`new`][`CString::new`] method on
219 /// [`CString`]. See its documentation for more.
220 ///
221 /// [`CString`]: struct.CString.html
222 /// [`CString::new`]: struct.CString.html#method.new
223 ///
224 /// # Examples
225 ///
226 /// ```
227 /// use std::ffi::{CString, NulError};
228 ///
229 /// let _: NulError = CString::new(b"f\0oo".to_vec()).unwrap_err();
230 /// ```
231 #[derive(Clone, PartialEq, Eq, Debug)]
232 #[stable(feature = "rust1", since = "1.0.0")]
233 pub struct NulError(usize, Vec<u8>);
234
235 /// An error indicating that a nul byte was not in the expected position.
236 ///
237 /// The slice used to create a [`CStr`] must have one and only one nul
238 /// byte at the end of the slice.
239 ///
240 /// This error is created by the
241 /// [`from_bytes_with_nul`][`CStr::from_bytes_with_nul`] method on
242 /// [`CStr`]. See its documentation for more.
243 ///
244 /// [`CStr`]: struct.CStr.html
245 /// [`CStr::from_bytes_with_nul`]: struct.CStr.html#method.from_bytes_with_nul
246 ///
247 /// # Examples
248 ///
249 /// ```
250 /// use std::ffi::{CStr, FromBytesWithNulError};
251 ///
252 /// let _: FromBytesWithNulError = CStr::from_bytes_with_nul(b"f\0oo").unwrap_err();
253 /// ```
254 #[derive(Clone, PartialEq, Eq, Debug)]
255 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
256 pub struct FromBytesWithNulError {
257     kind: FromBytesWithNulErrorKind,
258 }
259
260 #[derive(Clone, PartialEq, Eq, Debug)]
261 enum FromBytesWithNulErrorKind {
262     InteriorNul(usize),
263     NotNulTerminated,
264 }
265
266 impl FromBytesWithNulError {
267     fn interior_nul(pos: usize) -> FromBytesWithNulError {
268         FromBytesWithNulError { kind: FromBytesWithNulErrorKind::InteriorNul(pos) }
269     }
270     fn not_nul_terminated() -> FromBytesWithNulError {
271         FromBytesWithNulError { kind: FromBytesWithNulErrorKind::NotNulTerminated }
272     }
273 }
274
275 /// An error indicating invalid UTF-8 when converting a [`CString`] into a [`String`].
276 ///
277 /// `CString` is just a wrapper over a buffer of bytes with a nul
278 /// terminator; [`into_string`][`CString::into_string`] performs UTF-8
279 /// validation on those bytes and may return this error.
280 ///
281 /// This `struct` is created by the
282 /// [`into_string`][`CString::into_string`] method on [`CString`]. See
283 /// its documentation for more.
284 ///
285 /// [`String`]: ../string/struct.String.html
286 /// [`CString`]: struct.CString.html
287 /// [`CString::into_string`]: struct.CString.html#method.into_string
288 #[derive(Clone, PartialEq, Eq, Debug)]
289 #[stable(feature = "cstring_into", since = "1.7.0")]
290 pub struct IntoStringError {
291     inner: CString,
292     error: Utf8Error,
293 }
294
295 impl CString {
296     /// Creates a new C-compatible string from a container of bytes.
297     ///
298     /// This function will consume the provided data and use the
299     /// underlying bytes to construct a new string, ensuring that
300     /// there is a trailing 0 byte. This trailing 0 byte will be
301     /// appended by this function; the provided data should *not*
302     /// contain any 0 bytes in it.
303     ///
304     /// # Examples
305     ///
306     /// ```ignore (extern-declaration)
307     /// use std::ffi::CString;
308     /// use std::os::raw::c_char;
309     ///
310     /// extern { fn puts(s: *const c_char); }
311     ///
312     /// let to_print = CString::new("Hello!").expect("CString::new failed");
313     /// unsafe {
314     ///     puts(to_print.as_ptr());
315     /// }
316     /// ```
317     ///
318     /// # Errors
319     ///
320     /// This function will return an error if the supplied bytes contain an
321     /// internal 0 byte. The [`NulError`] returned will contain the bytes as well as
322     /// the position of the nul byte.
323     ///
324     /// [`NulError`]: struct.NulError.html
325     #[stable(feature = "rust1", since = "1.0.0")]
326     pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
327         trait SpecIntoVec {
328             fn into_vec(self) -> Vec<u8>;
329         }
330         impl<T: Into<Vec<u8>>> SpecIntoVec for T {
331             default fn into_vec(self) -> Vec<u8> {
332                 self.into()
333             }
334         }
335         // Specialization for avoiding reallocation.
336         impl SpecIntoVec for &'_ [u8] {
337             fn into_vec(self) -> Vec<u8> {
338                 let mut v = Vec::with_capacity(self.len() + 1);
339                 v.extend(self);
340                 v
341             }
342         }
343         impl SpecIntoVec for &'_ str {
344             fn into_vec(self) -> Vec<u8> {
345                 let mut v = Vec::with_capacity(self.len() + 1);
346                 v.extend(self.as_bytes());
347                 v
348             }
349         }
350
351         Self::_new(SpecIntoVec::into_vec(t))
352     }
353
354     fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
355         match memchr::memchr(0, &bytes) {
356             Some(i) => Err(NulError(i, bytes)),
357             None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
358         }
359     }
360
361     /// Creates a C-compatible string by consuming a byte vector,
362     /// without checking for interior 0 bytes.
363     ///
364     /// This method is equivalent to [`new`] except that no runtime assertion
365     /// is made that `v` contains no 0 bytes, and it requires an actual
366     /// byte vector, not anything that can be converted to one with Into.
367     ///
368     /// [`new`]: #method.new
369     ///
370     /// # Examples
371     ///
372     /// ```
373     /// use std::ffi::CString;
374     ///
375     /// let raw = b"foo".to_vec();
376     /// unsafe {
377     ///     let c_string = CString::from_vec_unchecked(raw);
378     /// }
379     /// ```
380     #[stable(feature = "rust1", since = "1.0.0")]
381     pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
382         v.reserve_exact(1);
383         v.push(0);
384         CString { inner: v.into_boxed_slice() }
385     }
386
387     /// Retakes ownership of a `CString` that was transferred to C via [`into_raw`].
388     ///
389     /// Additionally, the length of the string will be recalculated from the pointer.
390     ///
391     /// # Safety
392     ///
393     /// This should only ever be called with a pointer that was earlier
394     /// obtained by calling [`into_raw`] on a `CString`. Other usage (e.g., trying to take
395     /// ownership of a string that was allocated by foreign code) is likely to lead
396     /// to undefined behavior or allocator corruption.
397     ///
398     /// > **Note:** If you need to borrow a string that was allocated by
399     /// > foreign code, use [`CStr`]. If you need to take ownership of
400     /// > a string that was allocated by foreign code, you will need to
401     /// > make your own provisions for freeing it appropriately, likely
402     /// > with the foreign code's API to do that.
403     ///
404     /// [`into_raw`]: #method.into_raw
405     /// [`CStr`]: struct.CStr.html
406     ///
407     /// # Examples
408     ///
409     /// Creates a `CString`, pass ownership to an `extern` function (via raw pointer), then retake
410     /// ownership with `from_raw`:
411     ///
412     /// ```ignore (extern-declaration)
413     /// use std::ffi::CString;
414     /// use std::os::raw::c_char;
415     ///
416     /// extern {
417     ///     fn some_extern_function(s: *mut c_char);
418     /// }
419     ///
420     /// let c_string = CString::new("Hello!").expect("CString::new failed");
421     /// let raw = c_string.into_raw();
422     /// unsafe {
423     ///     some_extern_function(raw);
424     ///     let c_string = CString::from_raw(raw);
425     /// }
426     /// ```
427     #[stable(feature = "cstr_memory", since = "1.4.0")]
428     pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
429         let len = sys::strlen(ptr) + 1; // Including the NUL byte
430         let slice = slice::from_raw_parts_mut(ptr, len as usize);
431         CString { inner: Box::from_raw(slice as *mut [c_char] as *mut [u8]) }
432     }
433
434     /// Consumes the `CString` and transfers ownership of the string to a C caller.
435     ///
436     /// The pointer which this function returns must be returned to Rust and reconstituted using
437     /// [`from_raw`] to be properly deallocated. Specifically, one
438     /// should *not* use the standard C `free()` function to deallocate
439     /// this string.
440     ///
441     /// Failure to call [`from_raw`] will lead to a memory leak.
442     ///
443     /// [`from_raw`]: #method.from_raw
444     ///
445     /// # Examples
446     ///
447     /// ```
448     /// use std::ffi::CString;
449     ///
450     /// let c_string = CString::new("foo").expect("CString::new failed");
451     ///
452     /// let ptr = c_string.into_raw();
453     ///
454     /// unsafe {
455     ///     assert_eq!(b'f', *ptr as u8);
456     ///     assert_eq!(b'o', *ptr.offset(1) as u8);
457     ///     assert_eq!(b'o', *ptr.offset(2) as u8);
458     ///     assert_eq!(b'\0', *ptr.offset(3) as u8);
459     ///
460     ///     // retake pointer to free memory
461     ///     let _ = CString::from_raw(ptr);
462     /// }
463     /// ```
464     #[inline]
465     #[stable(feature = "cstr_memory", since = "1.4.0")]
466     pub fn into_raw(self) -> *mut c_char {
467         Box::into_raw(self.into_inner()) as *mut c_char
468     }
469
470     /// Converts the `CString` into a [`String`] if it contains valid UTF-8 data.
471     ///
472     /// On failure, ownership of the original `CString` is returned.
473     ///
474     /// [`String`]: ../string/struct.String.html
475     ///
476     /// # Examples
477     ///
478     /// ```
479     /// use std::ffi::CString;
480     ///
481     /// let valid_utf8 = vec![b'f', b'o', b'o'];
482     /// let cstring = CString::new(valid_utf8).expect("CString::new failed");
483     /// assert_eq!(cstring.into_string().expect("into_string() call failed"), "foo");
484     ///
485     /// let invalid_utf8 = vec![b'f', 0xff, b'o', b'o'];
486     /// let cstring = CString::new(invalid_utf8).expect("CString::new failed");
487     /// let err = cstring.into_string().err().expect("into_string().err() failed");
488     /// assert_eq!(err.utf8_error().valid_up_to(), 1);
489     /// ```
490
491     #[stable(feature = "cstring_into", since = "1.7.0")]
492     pub fn into_string(self) -> Result<String, IntoStringError> {
493         String::from_utf8(self.into_bytes()).map_err(|e| IntoStringError {
494             error: e.utf8_error(),
495             inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
496         })
497     }
498
499     /// Consumes the `CString` and returns the underlying byte buffer.
500     ///
501     /// The returned buffer does **not** contain the trailing nul
502     /// terminator, and it is guaranteed to not have any interior nul
503     /// bytes.
504     ///
505     /// # Examples
506     ///
507     /// ```
508     /// use std::ffi::CString;
509     ///
510     /// let c_string = CString::new("foo").expect("CString::new failed");
511     /// let bytes = c_string.into_bytes();
512     /// assert_eq!(bytes, vec![b'f', b'o', b'o']);
513     /// ```
514     #[stable(feature = "cstring_into", since = "1.7.0")]
515     pub fn into_bytes(self) -> Vec<u8> {
516         let mut vec = self.into_inner().into_vec();
517         let _nul = vec.pop();
518         debug_assert_eq!(_nul, Some(0u8));
519         vec
520     }
521
522     /// Equivalent to the [`into_bytes`] function except that the returned vector
523     /// includes the trailing nul terminator.
524     ///
525     /// [`into_bytes`]: #method.into_bytes
526     ///
527     /// # Examples
528     ///
529     /// ```
530     /// use std::ffi::CString;
531     ///
532     /// let c_string = CString::new("foo").expect("CString::new failed");
533     /// let bytes = c_string.into_bytes_with_nul();
534     /// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
535     /// ```
536     #[stable(feature = "cstring_into", since = "1.7.0")]
537     pub fn into_bytes_with_nul(self) -> Vec<u8> {
538         self.into_inner().into_vec()
539     }
540
541     /// Returns the contents of this `CString` as a slice of bytes.
542     ///
543     /// The returned slice does **not** contain the trailing nul
544     /// terminator, and it is guaranteed to not have any interior nul
545     /// bytes. If you need the nul terminator, use
546     /// [`as_bytes_with_nul`] instead.
547     ///
548     /// [`as_bytes_with_nul`]: #method.as_bytes_with_nul
549     ///
550     /// # Examples
551     ///
552     /// ```
553     /// use std::ffi::CString;
554     ///
555     /// let c_string = CString::new("foo").expect("CString::new failed");
556     /// let bytes = c_string.as_bytes();
557     /// assert_eq!(bytes, &[b'f', b'o', b'o']);
558     /// ```
559     #[inline]
560     #[stable(feature = "rust1", since = "1.0.0")]
561     pub fn as_bytes(&self) -> &[u8] {
562         &self.inner[..self.inner.len() - 1]
563     }
564
565     /// Equivalent to the [`as_bytes`] function except that the returned slice
566     /// includes the trailing nul terminator.
567     ///
568     /// [`as_bytes`]: #method.as_bytes
569     ///
570     /// # Examples
571     ///
572     /// ```
573     /// use std::ffi::CString;
574     ///
575     /// let c_string = CString::new("foo").expect("CString::new failed");
576     /// let bytes = c_string.as_bytes_with_nul();
577     /// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
578     /// ```
579     #[inline]
580     #[stable(feature = "rust1", since = "1.0.0")]
581     pub fn as_bytes_with_nul(&self) -> &[u8] {
582         &self.inner
583     }
584
585     /// Extracts a [`CStr`] slice containing the entire string.
586     ///
587     /// [`CStr`]: struct.CStr.html
588     ///
589     /// # Examples
590     ///
591     /// ```
592     /// use std::ffi::{CString, CStr};
593     ///
594     /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
595     /// let cstr = c_string.as_c_str();
596     /// assert_eq!(cstr,
597     ///            CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
598     /// ```
599     #[inline]
600     #[stable(feature = "as_c_str", since = "1.20.0")]
601     pub fn as_c_str(&self) -> &CStr {
602         &*self
603     }
604
605     /// Converts this `CString` into a boxed [`CStr`].
606     ///
607     /// [`CStr`]: struct.CStr.html
608     ///
609     /// # Examples
610     ///
611     /// ```
612     /// use std::ffi::{CString, CStr};
613     ///
614     /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
615     /// let boxed = c_string.into_boxed_c_str();
616     /// assert_eq!(&*boxed,
617     ///            CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
618     /// ```
619     #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
620     pub fn into_boxed_c_str(self) -> Box<CStr> {
621         unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) }
622     }
623
624     /// Bypass "move out of struct which implements [`Drop`] trait" restriction.
625     ///
626     /// [`Drop`]: ../ops/trait.Drop.html
627     fn into_inner(self) -> Box<[u8]> {
628         // Rationale: `mem::forget(self)` invalidates the previous call to `ptr::read(&self.inner)`
629         // so we use `ManuallyDrop` to ensure `self` is not dropped.
630         // Then we can return the box directly without invalidating it.
631         // See https://github.com/rust-lang/rust/issues/62553.
632         let this = mem::ManuallyDrop::new(self);
633         unsafe { ptr::read(&this.inner) }
634     }
635 }
636
637 // Turns this `CString` into an empty string to prevent
638 // memory-unsafe code from working by accident. Inline
639 // to prevent LLVM from optimizing it away in debug builds.
640 #[stable(feature = "cstring_drop", since = "1.13.0")]
641 impl Drop for CString {
642     #[inline]
643     fn drop(&mut self) {
644         unsafe {
645             *self.inner.get_unchecked_mut(0) = 0;
646         }
647     }
648 }
649
650 #[stable(feature = "rust1", since = "1.0.0")]
651 impl ops::Deref for CString {
652     type Target = CStr;
653
654     #[inline]
655     fn deref(&self) -> &CStr {
656         unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
657     }
658 }
659
660 #[stable(feature = "rust1", since = "1.0.0")]
661 impl fmt::Debug for CString {
662     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
663         fmt::Debug::fmt(&**self, f)
664     }
665 }
666
667 #[stable(feature = "cstring_into", since = "1.7.0")]
668 impl From<CString> for Vec<u8> {
669     /// Converts a [`CString`] into a [`Vec`]`<u8>`.
670     ///
671     /// The conversion consumes the [`CString`], and removes the terminating NUL byte.
672     ///
673     /// [`Vec`]: ../vec/struct.Vec.html
674     /// [`CString`]: ../ffi/struct.CString.html
675     #[inline]
676     fn from(s: CString) -> Vec<u8> {
677         s.into_bytes()
678     }
679 }
680
681 #[stable(feature = "cstr_debug", since = "1.3.0")]
682 impl fmt::Debug for CStr {
683     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
684         write!(f, "\"")?;
685         for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
686             f.write_char(byte as char)?;
687         }
688         write!(f, "\"")
689     }
690 }
691
692 #[stable(feature = "cstr_default", since = "1.10.0")]
693 impl Default for &CStr {
694     fn default() -> Self {
695         const SLICE: &[c_char] = &[0];
696         unsafe { CStr::from_ptr(SLICE.as_ptr()) }
697     }
698 }
699
700 #[stable(feature = "cstr_default", since = "1.10.0")]
701 impl Default for CString {
702     /// Creates an empty `CString`.
703     fn default() -> CString {
704         let a: &CStr = Default::default();
705         a.to_owned()
706     }
707 }
708
709 #[stable(feature = "cstr_borrow", since = "1.3.0")]
710 impl Borrow<CStr> for CString {
711     #[inline]
712     fn borrow(&self) -> &CStr {
713         self
714     }
715 }
716
717 #[stable(feature = "cstring_from_cow_cstr", since = "1.28.0")]
718 impl<'a> From<Cow<'a, CStr>> for CString {
719     #[inline]
720     fn from(s: Cow<'a, CStr>) -> Self {
721         s.into_owned()
722     }
723 }
724
725 #[stable(feature = "box_from_c_str", since = "1.17.0")]
726 impl From<&CStr> for Box<CStr> {
727     fn from(s: &CStr) -> Box<CStr> {
728         let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul());
729         unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
730     }
731 }
732
733 #[stable(feature = "box_from_cow", since = "1.45.0")]
734 impl From<Cow<'_, CStr>> for Box<CStr> {
735     #[inline]
736     fn from(cow: Cow<'_, CStr>) -> Box<CStr> {
737         match cow {
738             Cow::Borrowed(s) => Box::from(s),
739             Cow::Owned(s) => Box::from(s),
740         }
741     }
742 }
743
744 #[stable(feature = "c_string_from_box", since = "1.18.0")]
745 impl From<Box<CStr>> for CString {
746     /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating.
747     ///
748     /// [`Box`]: ../boxed/struct.Box.html
749     /// [`CString`]: ../ffi/struct.CString.html
750     #[inline]
751     fn from(s: Box<CStr>) -> CString {
752         s.into_c_string()
753     }
754 }
755
756 #[stable(feature = "cstring_from_vec_of_nonzerou8", since = "1.43.0")]
757 impl From<Vec<NonZeroU8>> for CString {
758     /// Converts a [`Vec`]`<`[`NonZeroU8`]`>` into a [`CString`] without
759     /// copying nor checking for inner null bytes.
760     ///
761     /// [`CString`]: ../ffi/struct.CString.html
762     /// [`NonZeroU8`]: ../num/struct.NonZeroU8.html
763     /// [`Vec`]: ../vec/struct.Vec.html
764     #[inline]
765     fn from(v: Vec<NonZeroU8>) -> CString {
766         unsafe {
767             // Transmute `Vec<NonZeroU8>` to `Vec<u8>`.
768             let v: Vec<u8> = {
769                 // Safety:
770                 //   - transmuting between `NonZeroU8` and `u8` is sound;
771                 //   - `alloc::Layout<NonZeroU8> == alloc::Layout<u8>`.
772                 let (ptr, len, cap): (*mut NonZeroU8, _, _) = Vec::into_raw_parts(v);
773                 Vec::from_raw_parts(ptr.cast::<u8>(), len, cap)
774             };
775             // Safety: `v` cannot contain null bytes, given the type-level
776             // invariant of `NonZeroU8`.
777             CString::from_vec_unchecked(v)
778         }
779     }
780 }
781
782 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
783 impl Clone for Box<CStr> {
784     #[inline]
785     fn clone(&self) -> Self {
786         (**self).into()
787     }
788 }
789
790 #[stable(feature = "box_from_c_string", since = "1.20.0")]
791 impl From<CString> for Box<CStr> {
792     /// Converts a [`CString`] into a [`Box`]`<CStr>` without copying or allocating.
793     ///
794     /// [`CString`]: ../ffi/struct.CString.html
795     /// [`Box`]: ../boxed/struct.Box.html
796     #[inline]
797     fn from(s: CString) -> Box<CStr> {
798         s.into_boxed_c_str()
799     }
800 }
801
802 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
803 impl<'a> From<CString> for Cow<'a, CStr> {
804     #[inline]
805     fn from(s: CString) -> Cow<'a, CStr> {
806         Cow::Owned(s)
807     }
808 }
809
810 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
811 impl<'a> From<&'a CStr> for Cow<'a, CStr> {
812     #[inline]
813     fn from(s: &'a CStr) -> Cow<'a, CStr> {
814         Cow::Borrowed(s)
815     }
816 }
817
818 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
819 impl<'a> From<&'a CString> for Cow<'a, CStr> {
820     #[inline]
821     fn from(s: &'a CString) -> Cow<'a, CStr> {
822         Cow::Borrowed(s.as_c_str())
823     }
824 }
825
826 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
827 impl From<CString> for Arc<CStr> {
828     /// Converts a [`CString`] into a [`Arc`]`<CStr>` without copying or allocating.
829     ///
830     /// [`CString`]: ../ffi/struct.CString.html
831     /// [`Arc`]: ../sync/struct.Arc.html
832     #[inline]
833     fn from(s: CString) -> Arc<CStr> {
834         let arc: Arc<[u8]> = Arc::from(s.into_inner());
835         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
836     }
837 }
838
839 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
840 impl From<&CStr> for Arc<CStr> {
841     #[inline]
842     fn from(s: &CStr) -> Arc<CStr> {
843         let arc: Arc<[u8]> = Arc::from(s.to_bytes_with_nul());
844         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
845     }
846 }
847
848 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
849 impl From<CString> for Rc<CStr> {
850     /// Converts a [`CString`] into a [`Rc`]`<CStr>` without copying or allocating.
851     ///
852     /// [`CString`]: ../ffi/struct.CString.html
853     /// [`Rc`]: ../rc/struct.Rc.html
854     #[inline]
855     fn from(s: CString) -> Rc<CStr> {
856         let rc: Rc<[u8]> = Rc::from(s.into_inner());
857         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
858     }
859 }
860
861 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
862 impl From<&CStr> for Rc<CStr> {
863     #[inline]
864     fn from(s: &CStr) -> Rc<CStr> {
865         let rc: Rc<[u8]> = Rc::from(s.to_bytes_with_nul());
866         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
867     }
868 }
869
870 #[stable(feature = "default_box_extra", since = "1.17.0")]
871 impl Default for Box<CStr> {
872     fn default() -> Box<CStr> {
873         let boxed: Box<[u8]> = Box::from([0]);
874         unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
875     }
876 }
877
878 impl NulError {
879     /// Returns the position of the nul byte in the slice that caused
880     /// [`CString::new`] to fail.
881     ///
882     /// [`CString::new`]: struct.CString.html#method.new
883     ///
884     /// # Examples
885     ///
886     /// ```
887     /// use std::ffi::CString;
888     ///
889     /// let nul_error = CString::new("foo\0bar").unwrap_err();
890     /// assert_eq!(nul_error.nul_position(), 3);
891     ///
892     /// let nul_error = CString::new("foo bar\0").unwrap_err();
893     /// assert_eq!(nul_error.nul_position(), 7);
894     /// ```
895     #[stable(feature = "rust1", since = "1.0.0")]
896     pub fn nul_position(&self) -> usize {
897         self.0
898     }
899
900     /// Consumes this error, returning the underlying vector of bytes which
901     /// generated the error in the first place.
902     ///
903     /// # Examples
904     ///
905     /// ```
906     /// use std::ffi::CString;
907     ///
908     /// let nul_error = CString::new("foo\0bar").unwrap_err();
909     /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
910     /// ```
911     #[stable(feature = "rust1", since = "1.0.0")]
912     pub fn into_vec(self) -> Vec<u8> {
913         self.1
914     }
915 }
916
917 #[stable(feature = "rust1", since = "1.0.0")]
918 impl Error for NulError {
919     #[allow(deprecated)]
920     fn description(&self) -> &str {
921         "nul byte found in data"
922     }
923 }
924
925 #[stable(feature = "rust1", since = "1.0.0")]
926 impl fmt::Display for NulError {
927     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
928         write!(f, "nul byte found in provided data at position: {}", self.0)
929     }
930 }
931
932 #[stable(feature = "rust1", since = "1.0.0")]
933 impl From<NulError> for io::Error {
934     /// Converts a [`NulError`] into a [`io::Error`].
935     ///
936     /// [`NulError`]: ../ffi/struct.NulError.html
937     /// [`io::Error`]: ../io/struct.Error.html
938     fn from(_: NulError) -> io::Error {
939         io::Error::new(io::ErrorKind::InvalidInput, "data provided contains a nul byte")
940     }
941 }
942
943 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
944 impl Error for FromBytesWithNulError {
945     #[allow(deprecated)]
946     fn description(&self) -> &str {
947         match self.kind {
948             FromBytesWithNulErrorKind::InteriorNul(..) => {
949                 "data provided contains an interior nul byte"
950             }
951             FromBytesWithNulErrorKind::NotNulTerminated => "data provided is not nul terminated",
952         }
953     }
954 }
955
956 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
957 impl fmt::Display for FromBytesWithNulError {
958     #[allow(deprecated, deprecated_in_future)]
959     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
960         f.write_str(self.description())?;
961         if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind {
962             write!(f, " at byte pos {}", pos)?;
963         }
964         Ok(())
965     }
966 }
967
968 impl IntoStringError {
969     /// Consumes this error, returning original [`CString`] which generated the
970     /// error.
971     ///
972     /// [`CString`]: struct.CString.html
973     #[stable(feature = "cstring_into", since = "1.7.0")]
974     pub fn into_cstring(self) -> CString {
975         self.inner
976     }
977
978     /// Access the underlying UTF-8 error that was the cause of this error.
979     #[stable(feature = "cstring_into", since = "1.7.0")]
980     pub fn utf8_error(&self) -> Utf8Error {
981         self.error
982     }
983 }
984
985 #[stable(feature = "cstring_into", since = "1.7.0")]
986 impl Error for IntoStringError {
987     #[allow(deprecated)]
988     fn description(&self) -> &str {
989         "C string contained non-utf8 bytes"
990     }
991
992     fn source(&self) -> Option<&(dyn Error + 'static)> {
993         Some(&self.error)
994     }
995 }
996
997 #[stable(feature = "cstring_into", since = "1.7.0")]
998 impl fmt::Display for IntoStringError {
999     #[allow(deprecated, deprecated_in_future)]
1000     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1001         self.description().fmt(f)
1002     }
1003 }
1004
1005 impl CStr {
1006     /// Wraps a raw C string with a safe C string wrapper.
1007     ///
1008     /// This function will wrap the provided `ptr` with a `CStr` wrapper, which
1009     /// allows inspection and interoperation of non-owned C strings. The total
1010     /// size of the raw C string must be smaller than `isize::MAX` **bytes**
1011     /// in memory due to calling the `slice::from_raw_parts` function.
1012     /// This method is unsafe for a number of reasons:
1013     ///
1014     /// * There is no guarantee to the validity of `ptr`.
1015     /// * The returned lifetime is not guaranteed to be the actual lifetime of
1016     ///   `ptr`.
1017     /// * There is no guarantee that the memory pointed to by `ptr` contains a
1018     ///   valid nul terminator byte at the end of the string.
1019     /// * It is not guaranteed that the memory pointed by `ptr` won't change
1020     ///   before the `CStr` has been destroyed.
1021     ///
1022     /// > **Note**: This operation is intended to be a 0-cost cast but it is
1023     /// > currently implemented with an up-front calculation of the length of
1024     /// > the string. This is not guaranteed to always be the case.
1025     ///
1026     /// # Examples
1027     ///
1028     /// ```ignore (extern-declaration)
1029     /// # fn main() {
1030     /// use std::ffi::CStr;
1031     /// use std::os::raw::c_char;
1032     ///
1033     /// extern {
1034     ///     fn my_string() -> *const c_char;
1035     /// }
1036     ///
1037     /// unsafe {
1038     ///     let slice = CStr::from_ptr(my_string());
1039     ///     println!("string returned: {}", slice.to_str().unwrap());
1040     /// }
1041     /// # }
1042     /// ```
1043     #[stable(feature = "rust1", since = "1.0.0")]
1044     pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
1045         let len = sys::strlen(ptr);
1046         let ptr = ptr as *const u8;
1047         CStr::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr, len as usize + 1))
1048     }
1049
1050     /// Creates a C string wrapper from a byte slice.
1051     ///
1052     /// This function will cast the provided `bytes` to a `CStr`
1053     /// wrapper after ensuring that the byte slice is nul-terminated
1054     /// and does not contain any interior nul bytes.
1055     ///
1056     /// # Examples
1057     ///
1058     /// ```
1059     /// use std::ffi::CStr;
1060     ///
1061     /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
1062     /// assert!(cstr.is_ok());
1063     /// ```
1064     ///
1065     /// Creating a `CStr` without a trailing nul terminator is an error:
1066     ///
1067     /// ```
1068     /// use std::ffi::CStr;
1069     ///
1070     /// let cstr = CStr::from_bytes_with_nul(b"hello");
1071     /// assert!(cstr.is_err());
1072     /// ```
1073     ///
1074     /// Creating a `CStr` with an interior nul byte is an error:
1075     ///
1076     /// ```
1077     /// use std::ffi::CStr;
1078     ///
1079     /// let cstr = CStr::from_bytes_with_nul(b"he\0llo\0");
1080     /// assert!(cstr.is_err());
1081     /// ```
1082     #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
1083     pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError> {
1084         let nul_pos = memchr::memchr(0, bytes);
1085         if let Some(nul_pos) = nul_pos {
1086             if nul_pos + 1 != bytes.len() {
1087                 return Err(FromBytesWithNulError::interior_nul(nul_pos));
1088             }
1089             Ok(unsafe { CStr::from_bytes_with_nul_unchecked(bytes) })
1090         } else {
1091             Err(FromBytesWithNulError::not_nul_terminated())
1092         }
1093     }
1094
1095     /// Unsafely creates a C string wrapper from a byte slice.
1096     ///
1097     /// This function will cast the provided `bytes` to a `CStr` wrapper without
1098     /// performing any sanity checks. The provided slice **must** be nul-terminated
1099     /// and not contain any interior nul bytes.
1100     ///
1101     /// # Examples
1102     ///
1103     /// ```
1104     /// use std::ffi::{CStr, CString};
1105     ///
1106     /// unsafe {
1107     ///     let cstring = CString::new("hello").expect("CString::new failed");
1108     ///     let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
1109     ///     assert_eq!(cstr, &*cstring);
1110     /// }
1111     /// ```
1112     #[inline]
1113     #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
1114     #[rustc_const_unstable(feature = "const_cstr_unchecked", issue = "none")]
1115     pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
1116         &*(bytes as *const [u8] as *const CStr)
1117     }
1118
1119     /// Returns the inner pointer to this C string.
1120     ///
1121     /// The returned pointer will be valid for as long as `self` is, and points
1122     /// to a contiguous region of memory terminated with a 0 byte to represent
1123     /// the end of the string.
1124     ///
1125     /// **WARNING**
1126     ///
1127     /// The returned pointer is read-only; writing to it (including passing it
1128     /// to C code that writes to it) causes undefined behavior.
1129     ///
1130     /// It is your responsibility to make sure that the underlying memory is not
1131     /// freed too early. For example, the following code will cause undefined
1132     /// behavior when `ptr` is used inside the `unsafe` block:
1133     ///
1134     /// ```no_run
1135     /// # #![allow(unused_must_use)]
1136     /// use std::ffi::CString;
1137     ///
1138     /// let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
1139     /// unsafe {
1140     ///     // `ptr` is dangling
1141     ///     *ptr;
1142     /// }
1143     /// ```
1144     ///
1145     /// This happens because the pointer returned by `as_ptr` does not carry any
1146     /// lifetime information and the [`CString`] is deallocated immediately after
1147     /// the `CString::new("Hello").expect("CString::new failed").as_ptr()` expression is evaluated.
1148     /// To fix the problem, bind the `CString` to a local variable:
1149     ///
1150     /// ```no_run
1151     /// # #![allow(unused_must_use)]
1152     /// use std::ffi::CString;
1153     ///
1154     /// let hello = CString::new("Hello").expect("CString::new failed");
1155     /// let ptr = hello.as_ptr();
1156     /// unsafe {
1157     ///     // `ptr` is valid because `hello` is in scope
1158     ///     *ptr;
1159     /// }
1160     /// ```
1161     ///
1162     /// This way, the lifetime of the `CString` in `hello` encompasses
1163     /// the lifetime of `ptr` and the `unsafe` block.
1164     ///
1165     /// [`CString`]: struct.CString.html
1166     #[inline]
1167     #[stable(feature = "rust1", since = "1.0.0")]
1168     #[rustc_const_stable(feature = "const_str_as_ptr", since = "1.32.0")]
1169     pub const fn as_ptr(&self) -> *const c_char {
1170         self.inner.as_ptr()
1171     }
1172
1173     /// Converts this C string to a byte slice.
1174     ///
1175     /// The returned slice will **not** contain the trailing nul terminator that this C
1176     /// string has.
1177     ///
1178     /// > **Note**: This method is currently implemented as a constant-time
1179     /// > cast, but it is planned to alter its definition in the future to
1180     /// > perform the length calculation whenever this method is called.
1181     ///
1182     /// # Examples
1183     ///
1184     /// ```
1185     /// use std::ffi::CStr;
1186     ///
1187     /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1188     /// assert_eq!(cstr.to_bytes(), b"foo");
1189     /// ```
1190     #[inline]
1191     #[stable(feature = "rust1", since = "1.0.0")]
1192     pub fn to_bytes(&self) -> &[u8] {
1193         let bytes = self.to_bytes_with_nul();
1194         &bytes[..bytes.len() - 1]
1195     }
1196
1197     /// Converts this C string to a byte slice containing the trailing 0 byte.
1198     ///
1199     /// This function is the equivalent of [`to_bytes`] except that it will retain
1200     /// the trailing nul terminator instead of chopping it off.
1201     ///
1202     /// > **Note**: This method is currently implemented as a 0-cost cast, but
1203     /// > it is planned to alter its definition in the future to perform the
1204     /// > length calculation whenever this method is called.
1205     ///
1206     /// [`to_bytes`]: #method.to_bytes
1207     ///
1208     /// # Examples
1209     ///
1210     /// ```
1211     /// use std::ffi::CStr;
1212     ///
1213     /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1214     /// assert_eq!(cstr.to_bytes_with_nul(), b"foo\0");
1215     /// ```
1216     #[inline]
1217     #[stable(feature = "rust1", since = "1.0.0")]
1218     pub fn to_bytes_with_nul(&self) -> &[u8] {
1219         unsafe { &*(&self.inner as *const [c_char] as *const [u8]) }
1220     }
1221
1222     /// Yields a [`&str`] slice if the `CStr` contains valid UTF-8.
1223     ///
1224     /// If the contents of the `CStr` are valid UTF-8 data, this
1225     /// function will return the corresponding [`&str`] slice. Otherwise,
1226     /// it will return an error with details of where UTF-8 validation failed.
1227     ///
1228     /// [`&str`]: ../primitive.str.html
1229     ///
1230     /// # Examples
1231     ///
1232     /// ```
1233     /// use std::ffi::CStr;
1234     ///
1235     /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1236     /// assert_eq!(cstr.to_str(), Ok("foo"));
1237     /// ```
1238     #[stable(feature = "cstr_to_str", since = "1.4.0")]
1239     pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
1240         // N.B., when `CStr` is changed to perform the length check in `.to_bytes()`
1241         // instead of in `from_ptr()`, it may be worth considering if this should
1242         // be rewritten to do the UTF-8 check inline with the length calculation
1243         // instead of doing it afterwards.
1244         str::from_utf8(self.to_bytes())
1245     }
1246
1247     /// Converts a `CStr` into a [`Cow`]`<`[`str`]`>`.
1248     ///
1249     /// If the contents of the `CStr` are valid UTF-8 data, this
1250     /// function will return a [`Cow`]`::`[`Borrowed`]`(`[`&str`]`)`
1251     /// with the corresponding [`&str`] slice. Otherwise, it will
1252     /// replace any invalid UTF-8 sequences with
1253     /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD] and return a
1254     /// [`Cow`]`::`[`Owned`]`(`[`String`]`)` with the result.
1255     ///
1256     /// [`Cow`]: ../borrow/enum.Cow.html
1257     /// [`Borrowed`]: ../borrow/enum.Cow.html#variant.Borrowed
1258     /// [`Owned`]: ../borrow/enum.Cow.html#variant.Owned
1259     /// [`str`]: ../primitive.str.html
1260     /// [`String`]: ../string/struct.String.html
1261     /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
1262     ///
1263     /// # Examples
1264     ///
1265     /// Calling `to_string_lossy` on a `CStr` containing valid UTF-8:
1266     ///
1267     /// ```
1268     /// use std::borrow::Cow;
1269     /// use std::ffi::CStr;
1270     ///
1271     /// let cstr = CStr::from_bytes_with_nul(b"Hello World\0")
1272     ///                  .expect("CStr::from_bytes_with_nul failed");
1273     /// assert_eq!(cstr.to_string_lossy(), Cow::Borrowed("Hello World"));
1274     /// ```
1275     ///
1276     /// Calling `to_string_lossy` on a `CStr` containing invalid UTF-8:
1277     ///
1278     /// ```
1279     /// use std::borrow::Cow;
1280     /// use std::ffi::CStr;
1281     ///
1282     /// let cstr = CStr::from_bytes_with_nul(b"Hello \xF0\x90\x80World\0")
1283     ///                  .expect("CStr::from_bytes_with_nul failed");
1284     /// assert_eq!(
1285     ///     cstr.to_string_lossy(),
1286     ///     Cow::Owned(String::from("Hello �World")) as Cow<'_, str>
1287     /// );
1288     /// ```
1289     #[stable(feature = "cstr_to_str", since = "1.4.0")]
1290     pub fn to_string_lossy(&self) -> Cow<'_, str> {
1291         String::from_utf8_lossy(self.to_bytes())
1292     }
1293
1294     /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating.
1295     ///
1296     /// [`Box`]: ../boxed/struct.Box.html
1297     /// [`CString`]: struct.CString.html
1298     ///
1299     /// # Examples
1300     ///
1301     /// ```
1302     /// use std::ffi::CString;
1303     ///
1304     /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
1305     /// let boxed = c_string.into_boxed_c_str();
1306     /// assert_eq!(boxed.into_c_string(), CString::new("foo").expect("CString::new failed"));
1307     /// ```
1308     #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
1309     pub fn into_c_string(self: Box<CStr>) -> CString {
1310         let raw = Box::into_raw(self) as *mut [u8];
1311         CString { inner: unsafe { Box::from_raw(raw) } }
1312     }
1313 }
1314
1315 #[stable(feature = "rust1", since = "1.0.0")]
1316 impl PartialEq for CStr {
1317     fn eq(&self, other: &CStr) -> bool {
1318         self.to_bytes().eq(other.to_bytes())
1319     }
1320 }
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 impl Eq for CStr {}
1323 #[stable(feature = "rust1", since = "1.0.0")]
1324 impl PartialOrd for CStr {
1325     fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
1326         self.to_bytes().partial_cmp(&other.to_bytes())
1327     }
1328 }
1329 #[stable(feature = "rust1", since = "1.0.0")]
1330 impl Ord for CStr {
1331     fn cmp(&self, other: &CStr) -> Ordering {
1332         self.to_bytes().cmp(&other.to_bytes())
1333     }
1334 }
1335
1336 #[stable(feature = "cstr_borrow", since = "1.3.0")]
1337 impl ToOwned for CStr {
1338     type Owned = CString;
1339
1340     fn to_owned(&self) -> CString {
1341         CString { inner: self.to_bytes_with_nul().into() }
1342     }
1343
1344     fn clone_into(&self, target: &mut CString) {
1345         let mut b = Vec::from(mem::take(&mut target.inner));
1346         self.to_bytes_with_nul().clone_into(&mut b);
1347         target.inner = b.into_boxed_slice();
1348     }
1349 }
1350
1351 #[stable(feature = "cstring_asref", since = "1.7.0")]
1352 impl From<&CStr> for CString {
1353     fn from(s: &CStr) -> CString {
1354         s.to_owned()
1355     }
1356 }
1357
1358 #[stable(feature = "cstring_asref", since = "1.7.0")]
1359 impl ops::Index<ops::RangeFull> for CString {
1360     type Output = CStr;
1361
1362     #[inline]
1363     fn index(&self, _index: ops::RangeFull) -> &CStr {
1364         self
1365     }
1366 }
1367
1368 #[stable(feature = "cstring_asref", since = "1.7.0")]
1369 impl AsRef<CStr> for CStr {
1370     #[inline]
1371     fn as_ref(&self) -> &CStr {
1372         self
1373     }
1374 }
1375
1376 #[stable(feature = "cstring_asref", since = "1.7.0")]
1377 impl AsRef<CStr> for CString {
1378     #[inline]
1379     fn as_ref(&self) -> &CStr {
1380         self
1381     }
1382 }
1383
1384 #[cfg(test)]
1385 mod tests {
1386     use super::*;
1387     use crate::borrow::Cow::{Borrowed, Owned};
1388     use crate::collections::hash_map::DefaultHasher;
1389     use crate::hash::{Hash, Hasher};
1390     use crate::os::raw::c_char;
1391     use crate::rc::Rc;
1392     use crate::sync::Arc;
1393
1394     #[test]
1395     fn c_to_rust() {
1396         let data = b"123\0";
1397         let ptr = data.as_ptr() as *const c_char;
1398         unsafe {
1399             assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
1400             assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
1401         }
1402     }
1403
1404     #[test]
1405     fn simple() {
1406         let s = CString::new("1234").unwrap();
1407         assert_eq!(s.as_bytes(), b"1234");
1408         assert_eq!(s.as_bytes_with_nul(), b"1234\0");
1409     }
1410
1411     #[test]
1412     fn build_with_zero1() {
1413         assert!(CString::new(&b"\0"[..]).is_err());
1414     }
1415     #[test]
1416     fn build_with_zero2() {
1417         assert!(CString::new(vec![0]).is_err());
1418     }
1419
1420     #[test]
1421     fn build_with_zero3() {
1422         unsafe {
1423             let s = CString::from_vec_unchecked(vec![0]);
1424             assert_eq!(s.as_bytes(), b"\0");
1425         }
1426     }
1427
1428     #[test]
1429     fn formatted() {
1430         let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
1431         assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
1432     }
1433
1434     #[test]
1435     fn borrowed() {
1436         unsafe {
1437             let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
1438             assert_eq!(s.to_bytes(), b"12");
1439             assert_eq!(s.to_bytes_with_nul(), b"12\0");
1440         }
1441     }
1442
1443     #[test]
1444     fn to_str() {
1445         let data = b"123\xE2\x80\xA6\0";
1446         let ptr = data.as_ptr() as *const c_char;
1447         unsafe {
1448             assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
1449             assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
1450         }
1451         let data = b"123\xE2\0";
1452         let ptr = data.as_ptr() as *const c_char;
1453         unsafe {
1454             assert!(CStr::from_ptr(ptr).to_str().is_err());
1455             assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
1456         }
1457     }
1458
1459     #[test]
1460     fn to_owned() {
1461         let data = b"123\0";
1462         let ptr = data.as_ptr() as *const c_char;
1463
1464         let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
1465         assert_eq!(owned.as_bytes_with_nul(), data);
1466     }
1467
1468     #[test]
1469     fn equal_hash() {
1470         let data = b"123\xE2\xFA\xA6\0";
1471         let ptr = data.as_ptr() as *const c_char;
1472         let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
1473
1474         let mut s = DefaultHasher::new();
1475         cstr.hash(&mut s);
1476         let cstr_hash = s.finish();
1477         let mut s = DefaultHasher::new();
1478         CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
1479         let cstring_hash = s.finish();
1480
1481         assert_eq!(cstr_hash, cstring_hash);
1482     }
1483
1484     #[test]
1485     fn from_bytes_with_nul() {
1486         let data = b"123\0";
1487         let cstr = CStr::from_bytes_with_nul(data);
1488         assert_eq!(cstr.map(CStr::to_bytes), Ok(&b"123"[..]));
1489         let cstr = CStr::from_bytes_with_nul(data);
1490         assert_eq!(cstr.map(CStr::to_bytes_with_nul), Ok(&b"123\0"[..]));
1491
1492         unsafe {
1493             let cstr = CStr::from_bytes_with_nul(data);
1494             let cstr_unchecked = CStr::from_bytes_with_nul_unchecked(data);
1495             assert_eq!(cstr, Ok(cstr_unchecked));
1496         }
1497     }
1498
1499     #[test]
1500     fn from_bytes_with_nul_unterminated() {
1501         let data = b"123";
1502         let cstr = CStr::from_bytes_with_nul(data);
1503         assert!(cstr.is_err());
1504     }
1505
1506     #[test]
1507     fn from_bytes_with_nul_interior() {
1508         let data = b"1\023\0";
1509         let cstr = CStr::from_bytes_with_nul(data);
1510         assert!(cstr.is_err());
1511     }
1512
1513     #[test]
1514     fn into_boxed() {
1515         let orig: &[u8] = b"Hello, world!\0";
1516         let cstr = CStr::from_bytes_with_nul(orig).unwrap();
1517         let boxed: Box<CStr> = Box::from(cstr);
1518         let cstring = cstr.to_owned().into_boxed_c_str().into_c_string();
1519         assert_eq!(cstr, &*boxed);
1520         assert_eq!(&*boxed, &*cstring);
1521         assert_eq!(&*cstring, cstr);
1522     }
1523
1524     #[test]
1525     fn boxed_default() {
1526         let boxed = <Box<CStr>>::default();
1527         assert_eq!(boxed.to_bytes_with_nul(), &[0]);
1528     }
1529
1530     #[test]
1531     fn test_c_str_clone_into() {
1532         let mut c_string = CString::new("lorem").unwrap();
1533         let c_ptr = c_string.as_ptr();
1534         let c_str = CStr::from_bytes_with_nul(b"ipsum\0").unwrap();
1535         c_str.clone_into(&mut c_string);
1536         assert_eq!(c_str, c_string.as_c_str());
1537         // The exact same size shouldn't have needed to move its allocation
1538         assert_eq!(c_ptr, c_string.as_ptr());
1539     }
1540
1541     #[test]
1542     fn into_rc() {
1543         let orig: &[u8] = b"Hello, world!\0";
1544         let cstr = CStr::from_bytes_with_nul(orig).unwrap();
1545         let rc: Rc<CStr> = Rc::from(cstr);
1546         let arc: Arc<CStr> = Arc::from(cstr);
1547
1548         assert_eq!(&*rc, cstr);
1549         assert_eq!(&*arc, cstr);
1550
1551         let rc2: Rc<CStr> = Rc::from(cstr.to_owned());
1552         let arc2: Arc<CStr> = Arc::from(cstr.to_owned());
1553
1554         assert_eq!(&*rc2, cstr);
1555         assert_eq!(&*arc2, cstr);
1556     }
1557
1558     #[test]
1559     fn cstr_const_constructor() {
1560         const CSTR: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b"Hello, world!\0") };
1561
1562         assert_eq!(CSTR.to_str().unwrap(), "Hello, world!");
1563     }
1564 }