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