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