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