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