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