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