Skip to main content

alloc/ffi/
c_str.rs

1//! [`CString`] and its related types.
2
3use core::borrow::Borrow;
4use core::ffi::{CStr, c_char};
5use core::num::NonZero;
6use core::slice::memchr;
7use core::str::{self, FromStr, Utf8Error};
8use core::{fmt, mem, ops, ptr, slice};
9
10use crate::alloc::Allocator;
11use crate::borrow::{Cow, ToOwned};
12use crate::boxed::Box;
13use crate::rc::Rc;
14use crate::string::String;
15#[cfg(target_has_atomic = "ptr")]
16use crate::sync::Arc;
17use crate::vec::Vec;
18
19/// A type representing an owned, C-compatible, nul-terminated string with no nul bytes in the
20/// middle.
21///
22/// This type serves the purpose of being able to safely generate a
23/// C-compatible string from a Rust byte slice or vector. An instance of this
24/// type is a static guarantee that the underlying bytes contain no interior 0
25/// bytes ("nul characters") and that the final byte is 0 ("nul terminator").
26///
27/// `CString` is to <code>&[CStr]</code> as [`String`] is to <code>&[str]</code>: the former
28/// in each pair are owned strings; the latter are borrowed
29/// references.
30///
31/// # Creating a `CString`
32///
33/// A `CString` is created from either a byte slice or a byte vector,
34/// or anything that implements <code>[Into]<[Vec]<[u8]>></code> (for
35/// example, you can build a `CString` straight out of a [`String`] or
36/// a <code>&[str]</code>, since both implement that trait).
37/// You can create a `CString` from a literal with `CString::from(c"Text")`.
38///
39/// The [`CString::new`] method will actually check that the provided <code>&[[u8]]</code>
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 an [`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 <code>&[[u8]]</code> 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 <code>&[[u8]]</code> 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]: prim@str "str"
73/// [`Deref`]: ops::Deref
74///
75/// # Examples
76///
77/// ```ignore (extern-declaration)
78/// # fn main() {
79/// use std::ffi::CString;
80/// use std::os::raw::c_char;
81///
82/// extern "C" {
83///     fn my_printer(s: *const c_char);
84/// }
85///
86/// // We are certain that our string doesn't have 0 bytes in the middle,
87/// // so we can .expect()
88/// let c_to_print = CString::new("Hello, world!").expect("we provided a string without NUL bytes, so CString::new should not fail");
89/// unsafe {
90///     my_printer(c_to_print.as_ptr());
91/// }
92/// # }
93/// ```
94///
95/// # Safety
96///
97/// `CString` is intended for working with traditional C-style strings
98/// (a sequence of non-nul bytes terminated by a single nul byte); the
99/// primary use case for these kinds of strings is interoperating with C-like
100/// code. Often you will need to transfer ownership to/from that external
101/// code. It is strongly recommended that you thoroughly read through the
102/// documentation of `CString` before use, as improper ownership management
103/// of `CString` instances can lead to invalid memory accesses, memory leaks,
104/// and other memory errors.
105#[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
106#[rustc_diagnostic_item = "cstring_type"]
107#[rustc_insignificant_dtor]
108#[stable(feature = "alloc_c_string", since = "1.64.0")]
109pub struct CString {
110    // Invariant 1: the slice ends with a zero byte and has a length of at least one.
111    // Invariant 2: the slice contains only one zero byte.
112    // Improper usage of unsafe function can break Invariant 2, but not Invariant 1.
113    inner: Box<[u8]>,
114}
115
116/// An error indicating that an interior nul byte was found.
117///
118/// While Rust strings may contain nul bytes in the middle, C strings
119/// can't, as that byte would effectively truncate the string.
120///
121/// This error is created by the [`new`][`CString::new`] method on
122/// [`CString`]. See its documentation for more.
123///
124/// # Examples
125///
126/// ```
127/// use std::ffi::{CString, NulError};
128///
129/// let _: NulError = CString::new(b"f\0oo".to_vec()).unwrap_err();
130/// ```
131#[derive(Clone, PartialEq, Eq, Debug)]
132#[stable(feature = "alloc_c_string", since = "1.64.0")]
133pub struct NulError(usize, Vec<u8>);
134
135#[derive(Clone, PartialEq, Eq, Debug)]
136enum FromBytesWithNulErrorKind {
137    InteriorNul(usize),
138    NotNulTerminated,
139}
140
141/// An error indicating that a nul byte was not in the expected position.
142///
143/// The vector used to create a [`CString`] must have one and only one nul byte,
144/// positioned at the end.
145///
146/// This error is created by the [`CString::from_vec_with_nul`] method.
147/// See its documentation for more.
148///
149/// # Examples
150///
151/// ```
152/// use std::ffi::{CString, FromVecWithNulError};
153///
154/// let _: FromVecWithNulError = CString::from_vec_with_nul(b"f\0oo".to_vec()).unwrap_err();
155/// ```
156#[derive(Clone, PartialEq, Eq, Debug)]
157#[stable(feature = "alloc_c_string", since = "1.64.0")]
158pub struct FromVecWithNulError {
159    error_kind: FromBytesWithNulErrorKind,
160    bytes: Vec<u8>,
161}
162
163#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
164impl FromVecWithNulError {
165    /// Returns a slice of [`u8`]s bytes that were attempted to convert to a [`CString`].
166    ///
167    /// # Examples
168    ///
169    /// Basic usage:
170    ///
171    /// ```
172    /// use std::ffi::CString;
173    ///
174    /// // Some invalid bytes in a vector
175    /// let bytes = b"f\0oo".to_vec();
176    ///
177    /// let value = CString::from_vec_with_nul(bytes.clone());
178    ///
179    /// assert_eq!(&bytes[..], value.unwrap_err().as_bytes());
180    /// ```
181    #[must_use]
182    #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
183    pub fn as_bytes(&self) -> &[u8] {
184        &self.bytes[..]
185    }
186
187    /// Returns the bytes that were attempted to convert to a [`CString`].
188    ///
189    /// This method is carefully constructed to avoid allocation. It will
190    /// consume the error, moving out the bytes, so that a copy of the bytes
191    /// does not need to be made.
192    ///
193    /// # Examples
194    ///
195    /// Basic usage:
196    ///
197    /// ```
198    /// use std::ffi::CString;
199    ///
200    /// // Some invalid bytes in a vector
201    /// let bytes = b"f\0oo".to_vec();
202    ///
203    /// let value = CString::from_vec_with_nul(bytes.clone());
204    ///
205    /// assert_eq!(bytes, value.unwrap_err().into_bytes());
206    /// ```
207    #[must_use = "`self` will be dropped if the result is not used"]
208    #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
209    pub fn into_bytes(self) -> Vec<u8> {
210        self.bytes
211    }
212}
213
214/// An error indicating invalid UTF-8 when converting a [`CString`] into a [`String`].
215///
216/// `CString` is just a wrapper over a buffer of bytes with a nul terminator;
217/// [`CString::into_string`] performs UTF-8 validation on those bytes and may
218/// return this error.
219///
220/// This `struct` is created by [`CString::into_string()`]. See
221/// its documentation for more.
222#[derive(Clone, PartialEq, Eq, Debug)]
223#[stable(feature = "alloc_c_string", since = "1.64.0")]
224pub struct IntoStringError {
225    inner: CString,
226    error: Utf8Error,
227}
228
229impl CString {
230    /// Creates a new C-compatible string from a container of bytes.
231    ///
232    /// This function will consume the provided data and use the
233    /// underlying bytes to construct a new string, ensuring that
234    /// there is a trailing 0 byte. This trailing 0 byte will be
235    /// appended by this function; the provided data should *not*
236    /// contain any 0 bytes in it.
237    ///
238    /// # Examples
239    ///
240    /// ```ignore (extern-declaration)
241    /// use std::ffi::CString;
242    /// use std::os::raw::c_char;
243    ///
244    /// extern "C" { fn puts(s: *const c_char); }
245    ///
246    /// let to_print = CString::new("Hello!").expect("we provided a string without NUL bytes, so CString::new should not fail");
247    /// unsafe {
248    ///     puts(to_print.as_ptr());
249    /// }
250    /// ```
251    ///
252    /// # Errors
253    ///
254    /// This function will return an error if the supplied bytes contain an
255    /// internal 0 byte. The [`NulError`] returned will contain the bytes as well as
256    /// the position of the nul byte.
257    #[stable(feature = "rust1", since = "1.0.0")]
258    pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
259        trait SpecNewImpl {
260            fn spec_new_impl(self) -> Result<CString, NulError>;
261        }
262
263        impl<T: Into<Vec<u8>>> SpecNewImpl for T {
264            default fn spec_new_impl(self) -> Result<CString, NulError> {
265                let bytes: Vec<u8> = self.into();
266                match memchr::memchr(0, &bytes) {
267                    Some(i) => Err(NulError(i, bytes)),
268                    // SAFETY: We ensured there's no null bytes.
269                    None => Ok(unsafe { CString::_from_vec_unchecked(bytes) }),
270                }
271            }
272        }
273
274        // Specialization for avoiding reallocation
275        #[inline(always)] // Without that it is not inlined into specializations
276        fn spec_new_impl_bytes(bytes: &[u8]) -> Result<CString, NulError> {
277            // We cannot have such large slice that we would overflow here
278            // but using `checked_add` allows LLVM to assume that capacity never overflows
279            // and generate twice shorter code.
280            // `saturating_add` doesn't help for some reason.
281            let capacity = bytes.len().checked_add(1).unwrap();
282
283            // Allocate before validation to avoid duplication of allocation code.
284            // We still need to allocate and copy memory even if we get an error.
285            let mut buffer = Vec::with_capacity(capacity);
286            buffer.extend(bytes);
287
288            // Check memory of self instead of new buffer.
289            // This allows better optimizations if lto enabled.
290            match memchr::memchr(0, bytes) {
291                Some(i) => Err(NulError(i, buffer)),
292                // SAFETY: We ensured there's no null bytes.
293                None => Ok(unsafe { CString::_from_vec_unchecked(buffer) }),
294            }
295        }
296
297        impl SpecNewImpl for &'_ [u8] {
298            fn spec_new_impl(self) -> Result<CString, NulError> {
299                spec_new_impl_bytes(self)
300            }
301        }
302
303        impl SpecNewImpl for &'_ str {
304            fn spec_new_impl(self) -> Result<CString, NulError> {
305                spec_new_impl_bytes(self.as_bytes())
306            }
307        }
308
309        impl SpecNewImpl for &'_ mut [u8] {
310            fn spec_new_impl(self) -> Result<CString, NulError> {
311                spec_new_impl_bytes(self)
312            }
313        }
314
315        t.spec_new_impl()
316    }
317
318    /// Creates a C-compatible string by consuming a byte vector,
319    /// without checking for interior 0 bytes.
320    ///
321    /// Trailing 0 byte will be appended by this function.
322    ///
323    /// This method is equivalent to [`CString::new`] except that no runtime
324    /// assertion is made that `v` contains no 0 bytes, and it requires an
325    /// actual byte vector, not anything that can be converted to one with Into.
326    ///
327    /// # Safety
328    ///
329    /// The caller must ensure `v` contains no nul bytes in its contents.
330    ///
331    /// # Examples
332    ///
333    /// ```
334    /// use std::ffi::CString;
335    ///
336    /// let raw = b"foo".to_vec();
337    /// unsafe {
338    ///     let c_string = CString::from_vec_unchecked(raw);
339    /// }
340    /// ```
341    #[must_use]
342    #[stable(feature = "rust1", since = "1.0.0")]
343    pub unsafe fn from_vec_unchecked(v: Vec<u8>) -> Self {
344        debug_assert!(memchr::memchr(0, &v).is_none());
345        // SAFETY: Upheld by caller.
346        unsafe { Self::_from_vec_unchecked(v) }
347    }
348
349    unsafe fn _from_vec_unchecked(mut v: Vec<u8>) -> Self {
350        v.reserve_exact(1);
351        v.push(0);
352        Self { inner: v.into_boxed_slice() }
353    }
354
355    /// Retakes ownership of a `CString` that was transferred to C via
356    /// [`CString::into_raw`].
357    ///
358    /// Additionally, the length of the string will be recalculated from the pointer.
359    ///
360    /// # Safety
361    ///
362    /// This should only ever be called with a pointer that was earlier
363    /// obtained by calling [`CString::into_raw`], and the memory it points to must not be accessed
364    /// through any other pointer during the lifetime of reconstructed `CString`.
365    /// Other usage (e.g., trying to take ownership of a string that was allocated by foreign code)
366    /// is likely to lead to undefined behavior or allocator corruption.
367    ///
368    /// This function does not validate ownership of the raw pointer's memory.
369    /// A double-free may occur if the function is called twice on the same raw pointer.
370    /// Additionally, the caller must ensure the pointer is not dangling.
371    ///
372    /// It should be noted that the length isn't just "recomputed," but that
373    /// the recomputed length must match the original length from the
374    /// [`CString::into_raw`] call. This means the [`CString::into_raw`]/`from_raw`
375    /// methods should not be used when passing the string to C functions that can
376    /// modify the string's length.
377    ///
378    /// > **Note:** If you need to borrow a string that was allocated by
379    /// > foreign code, use [`CStr`]. If you need to take ownership of
380    /// > a string that was allocated by foreign code, you will need to
381    /// > make your own provisions for freeing it appropriately, likely
382    /// > with the foreign code's API to do that.
383    ///
384    /// # Examples
385    ///
386    /// Creates a `CString`, pass ownership to an `extern` function (via raw pointer), then retake
387    /// ownership with `from_raw`:
388    ///
389    /// ```ignore (extern-declaration)
390    /// use std::ffi::CString;
391    /// use std::os::raw::c_char;
392    ///
393    /// extern "C" {
394    ///     fn some_extern_function(s: *mut c_char);
395    /// }
396    ///
397    /// let c_string = CString::from(c"Hello!");
398    /// let raw = c_string.into_raw();
399    /// unsafe {
400    ///     some_extern_function(raw);
401    ///     let c_string = CString::from_raw(raw);
402    /// }
403    /// ```
404    #[must_use = "call `drop(from_raw(ptr))` if you intend to drop the `CString`"]
405    #[stable(feature = "cstr_memory", since = "1.4.0")]
406    pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
407        // SAFETY: This is called with a pointer that was obtained from a call
408        // to `CString::into_raw` and the length has not been modified. As such,
409        // we know there is a NUL byte (and only one) at the end and that the
410        // information about the size of the allocation is correct on Rust's
411        // side.
412        unsafe {
413            unsafe extern "C" {
414                /// Provided by libc or compiler_builtins.
415                fn strlen(s: *const c_char) -> usize;
416            }
417            let len = strlen(ptr) + 1; // Including the NUL byte
418            let slice = slice::from_raw_parts_mut(ptr, len);
419            CString { inner: Box::from_raw(slice as *mut [c_char] as *mut [u8]) }
420        }
421    }
422
423    /// Consumes the `CString` and transfers ownership of the string to a C caller.
424    ///
425    /// The pointer which this function returns must be returned to Rust and reconstituted using
426    /// [`CString::from_raw`] to be properly deallocated. Specifically, one
427    /// should *not* use the standard C `free()` function to deallocate
428    /// this string.
429    ///
430    /// Failure to call [`CString::from_raw`] will lead to a memory leak.
431    ///
432    /// The C side must **not** modify the length of the string (by writing a
433    /// nul byte somewhere inside the string or removing the final one) before
434    /// it makes it back into Rust using [`CString::from_raw`]. See the safety section
435    /// in [`CString::from_raw`].
436    ///
437    /// # Examples
438    ///
439    /// ```
440    /// use std::ffi::CString;
441    ///
442    /// let c_string = CString::from(c"foo");
443    ///
444    /// let ptr = c_string.into_raw();
445    ///
446    /// unsafe {
447    ///     assert_eq!(b'f', *ptr as u8);
448    ///     assert_eq!(b'o', *ptr.add(1) as u8);
449    ///     assert_eq!(b'o', *ptr.add(2) as u8);
450    ///     assert_eq!(b'\0', *ptr.add(3) as u8);
451    ///
452    ///     // retake pointer to free memory
453    ///     let _ = CString::from_raw(ptr);
454    /// }
455    /// ```
456    #[inline]
457    #[must_use = "`self` will be dropped if the result is not used"]
458    #[stable(feature = "cstr_memory", since = "1.4.0")]
459    pub fn into_raw(self) -> *mut c_char {
460        Box::into_raw(self.into_inner()) as *mut c_char
461    }
462
463    /// Converts the `CString` into a [`String`] if it contains valid UTF-8 data.
464    ///
465    /// On failure, ownership of the original `CString` is returned.
466    ///
467    /// # Examples
468    ///
469    /// ```
470    /// use std::ffi::CString;
471    ///
472    /// let valid_utf8 = vec![b'f', b'o', b'o'];
473    /// let cstring = CString::new(valid_utf8).expect("we provided bytes that do not have a NUL byte, so CString::new should not fail");
474    /// assert_eq!(cstring.into_string().expect("we provided bytes that are valid UTF-8, so `into_string` should not fail"), "foo");
475    ///
476    /// let invalid_utf8 = vec![b'f', 0xff, b'o', b'o'];
477    /// let cstring = CString::new(invalid_utf8).expect("we provided bytes that do not have a NUL byte, so CString::new should not fail");
478    /// let err = cstring.into_string().expect_err("we provided bytes that are invalid UTF-8, so `into_string` should fail");
479    /// assert_eq!(err.utf8_error().valid_up_to(), 1);
480    /// ```
481    #[stable(feature = "cstring_into", since = "1.7.0")]
482    pub fn into_string(self) -> Result<String, IntoStringError> {
483        String::from_utf8(self.into_bytes()).map_err(|e| IntoStringError {
484            error: e.utf8_error(),
485            // SAFETY: `CString`s never contain null bytes.
486            inner: unsafe { Self::_from_vec_unchecked(e.into_bytes()) },
487        })
488    }
489
490    /// Consumes the `CString` and returns the underlying byte buffer.
491    ///
492    /// The returned buffer does **not** contain the trailing nul
493    /// terminator, and it is guaranteed to not have any interior nul
494    /// bytes.
495    ///
496    /// # Examples
497    ///
498    /// ```
499    /// use std::ffi::CString;
500    ///
501    /// let c_string = CString::from(c"foo");
502    /// let bytes = c_string.into_bytes();
503    /// assert_eq!(bytes, vec![b'f', b'o', b'o']);
504    /// ```
505    #[must_use = "`self` will be dropped if the result is not used"]
506    #[stable(feature = "cstring_into", since = "1.7.0")]
507    pub fn into_bytes(self) -> Vec<u8> {
508        let mut vec = self.into_inner().into_vec();
509        let _nul = vec.pop();
510        debug_assert_eq!(_nul, Some(0u8));
511        vec
512    }
513
514    /// Equivalent to [`CString::into_bytes()`] except that the
515    /// returned vector includes the trailing nul terminator.
516    ///
517    /// # Examples
518    ///
519    /// ```
520    /// use std::ffi::CString;
521    ///
522    /// let c_string = CString::from(c"foo");
523    /// let bytes = c_string.into_bytes_with_nul();
524    /// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
525    /// ```
526    #[must_use = "`self` will be dropped if the result is not used"]
527    #[stable(feature = "cstring_into", since = "1.7.0")]
528    pub fn into_bytes_with_nul(self) -> Vec<u8> {
529        self.into_inner().into_vec()
530    }
531
532    /// Returns the contents of this `CString` as a slice of bytes.
533    ///
534    /// The returned slice does **not** contain the trailing nul
535    /// terminator, and it is guaranteed to not have any interior nul
536    /// bytes. If you need the nul terminator, use
537    /// [`CString::as_bytes_with_nul`] instead.
538    ///
539    /// # Examples
540    ///
541    /// ```
542    /// use std::ffi::CString;
543    ///
544    /// let c_string = CString::from(c"foo");
545    /// let bytes = c_string.as_bytes();
546    /// assert_eq!(bytes, &[b'f', b'o', b'o']);
547    /// ```
548    #[inline]
549    #[must_use]
550    #[stable(feature = "rust1", since = "1.0.0")]
551    pub fn as_bytes(&self) -> &[u8] {
552        // SAFETY: CString has a length at least 1
553        unsafe { self.inner.get_unchecked(..self.inner.len() - 1) }
554    }
555
556    /// Equivalent to [`CString::as_bytes()`] except that the
557    /// returned slice includes the trailing nul terminator.
558    ///
559    /// # Examples
560    ///
561    /// ```
562    /// use std::ffi::CString;
563    ///
564    /// let c_string = CString::from(c"foo");
565    /// let bytes = c_string.as_bytes_with_nul();
566    /// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
567    /// ```
568    #[inline]
569    #[must_use]
570    #[stable(feature = "rust1", since = "1.0.0")]
571    pub fn as_bytes_with_nul(&self) -> &[u8] {
572        &self.inner
573    }
574
575    /// Extracts a [`CStr`] slice containing the entire string.
576    ///
577    /// # Examples
578    ///
579    /// ```
580    /// use std::ffi::{CString, CStr};
581    ///
582    /// let c_string = CString::from(c"foo");
583    /// let cstr = c_string.as_c_str();
584    /// assert_eq!(cstr,
585    ///            CStr::from_bytes_with_nul(b"foo\0").expect("we provided bytes that has one NUL byte exactly at the end, so CStr::from_bytes_with_nul should not fail"));
586    /// ```
587    #[inline]
588    #[must_use]
589    #[stable(feature = "as_c_str", since = "1.20.0")]
590    #[rustc_diagnostic_item = "cstring_as_c_str"]
591    pub fn as_c_str(&self) -> &CStr {
592        // SAFETY: Ensured by `as_bytes_with_nul`.
593        unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
594    }
595
596    /// Converts this `CString` into a boxed [`CStr`].
597    ///
598    /// # Examples
599    ///
600    /// ```
601    /// let c_string = c"foo".to_owned();
602    /// let boxed = c_string.into_boxed_c_str();
603    /// assert_eq!(boxed.to_bytes_with_nul(), b"foo\0");
604    /// ```
605    #[must_use = "`self` will be dropped if the result is not used"]
606    #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
607    pub fn into_boxed_c_str(self) -> Box<CStr> {
608        // SAFETY: Typecast of [u8] to CStr is valid and we know contents have
609        // no nulls except for the terminating byte.
610        unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) }
611    }
612
613    /// Bypass "move out of struct which implements [`Drop`] trait" restriction.
614    #[inline]
615    fn into_inner(self) -> Box<[u8]> {
616        let this = mem::ManuallyDrop::new(self);
617        // SAFETY: `mem::forget(self)` invalidates the previous call to `ptr::read(&self.inner)`
618        // so we use `ManuallyDrop` to ensure `self` is not dropped.
619        // Then we can return the box directly without invalidating it.
620        // See https://github.com/rust-lang/rust/issues/62553.
621        unsafe { ptr::read(&this.inner) }
622    }
623
624    /// Converts a <code>[Vec]<[u8]></code> to a [`CString`] without checking the
625    /// invariants on the given [`Vec`].
626    ///
627    /// # Safety
628    ///
629    /// The given [`Vec`] **must** have one nul byte as its last element.
630    /// This means it cannot be empty nor have any other nul byte anywhere else.
631    ///
632    /// # Example
633    ///
634    /// ```
635    /// use std::ffi::CString;
636    /// assert_eq!(
637    ///     unsafe { CString::from_vec_with_nul_unchecked(b"abc\0".to_vec()) },
638    ///     unsafe { CString::from_vec_unchecked(b"abc".to_vec()) }
639    /// );
640    /// ```
641    #[must_use]
642    #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
643    pub unsafe fn from_vec_with_nul_unchecked(v: Vec<u8>) -> Self {
644        debug_assert!(memchr::memchr(0, &v).unwrap() + 1 == v.len());
645        // SAFETY: Upheld by caller.
646        unsafe { Self::_from_vec_with_nul_unchecked(v) }
647    }
648
649    unsafe fn _from_vec_with_nul_unchecked(v: Vec<u8>) -> Self {
650        Self { inner: v.into_boxed_slice() }
651    }
652
653    /// Attempts to convert a <code>[Vec]<[u8]></code> to a [`CString`].
654    ///
655    /// Runtime checks are present to ensure there is only one nul byte in the
656    /// [`Vec`], its last element.
657    ///
658    /// # Errors
659    ///
660    /// If a nul byte is present and not the last element or no nul bytes
661    /// is present, an error will be returned.
662    ///
663    /// # Examples
664    ///
665    /// A successful conversion will produce the same result as [`CString::new`]
666    /// when called without the ending nul byte.
667    ///
668    /// ```
669    /// use std::ffi::CString;
670    /// assert_eq!(
671    ///     CString::from_vec_with_nul(b"abc\0".to_vec())
672    ///         .expect("we provided bytes that has one NUL byte exactly at the end, so CString::from_vec_with_nul should not fail"),
673    ///     c"abc".to_owned()
674    /// );
675    /// ```
676    ///
677    /// An incorrectly formatted [`Vec`] will produce an error.
678    ///
679    /// ```
680    /// use std::ffi::{CString, FromVecWithNulError};
681    /// // Interior nul byte
682    /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"a\0bc".to_vec()).unwrap_err();
683    /// // No nul byte
684    /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"abc".to_vec()).unwrap_err();
685    /// ```
686    #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
687    pub fn from_vec_with_nul(v: Vec<u8>) -> Result<Self, FromVecWithNulError> {
688        let nul_pos = memchr::memchr(0, &v);
689        match nul_pos {
690            Some(nul_pos) if nul_pos + 1 == v.len() => {
691                // SAFETY: We know there is only one nul byte, at the end
692                // of the vec.
693                Ok(unsafe { Self::_from_vec_with_nul_unchecked(v) })
694            }
695            Some(nul_pos) => Err(FromVecWithNulError {
696                error_kind: FromBytesWithNulErrorKind::InteriorNul(nul_pos),
697                bytes: v,
698            }),
699            None => Err(FromVecWithNulError {
700                error_kind: FromBytesWithNulErrorKind::NotNulTerminated,
701                bytes: v,
702            }),
703        }
704    }
705}
706
707// Turns this `CString` into an empty string to prevent
708// memory-unsafe code from working by accident. Inline
709// to prevent LLVM from optimizing it away in debug builds.
710#[stable(feature = "cstring_drop", since = "1.13.0")]
711impl Drop for CString {
712    #[inline]
713    fn drop(&mut self) {
714        // SAFETY: Length is always at least one.
715        unsafe {
716            *self.inner.get_unchecked_mut(0) = 0;
717        }
718    }
719}
720
721#[stable(feature = "rust1", since = "1.0.0")]
722impl ops::Deref for CString {
723    type Target = CStr;
724
725    #[inline]
726    fn deref(&self) -> &CStr {
727        self.as_c_str()
728    }
729}
730
731/// Delegates to the [`CStr`] implementation of [`fmt::Debug`],
732/// showing invalid UTF-8 as hex escapes.
733#[stable(feature = "rust1", since = "1.0.0")]
734impl fmt::Debug for CString {
735    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
736        fmt::Debug::fmt(self.as_c_str(), f)
737    }
738}
739
740#[stable(feature = "cstring_into", since = "1.7.0")]
741impl From<CString> for Vec<u8> {
742    /// Converts a [`CString`] into a <code>[Vec]<[u8]></code>.
743    ///
744    /// The conversion consumes the [`CString`], and removes the terminating NUL byte.
745    #[inline]
746    fn from(s: CString) -> Vec<u8> {
747        s.into_bytes()
748    }
749}
750
751#[stable(feature = "cstr_default", since = "1.10.0")]
752impl Default for CString {
753    /// Creates an empty `CString`.
754    fn default() -> CString {
755        let a: &CStr = Default::default();
756        a.to_owned()
757    }
758}
759
760#[stable(feature = "cstr_borrow", since = "1.3.0")]
761impl Borrow<CStr> for CString {
762    #[inline]
763    fn borrow(&self) -> &CStr {
764        self
765    }
766}
767
768#[stable(feature = "cstring_from_cow_cstr", since = "1.28.0")]
769impl<'a> From<Cow<'a, CStr>> for CString {
770    /// Converts a `Cow<'a, CStr>` into a `CString`, by copying the contents if they are
771    /// borrowed.
772    #[inline]
773    fn from(s: Cow<'a, CStr>) -> Self {
774        s.into_owned()
775    }
776}
777
778#[stable(feature = "box_from_c_str", since = "1.17.0")]
779impl From<&CStr> for Box<CStr> {
780    /// Converts a `&CStr` into a `Box<CStr>`,
781    /// by copying the contents into a newly allocated [`Box`].
782    fn from(s: &CStr) -> Box<CStr> {
783        Box::clone_from_ref(s)
784    }
785}
786
787#[stable(feature = "box_from_mut_slice", since = "1.84.0")]
788impl From<&mut CStr> for Box<CStr> {
789    /// Converts a `&mut CStr` into a `Box<CStr>`,
790    /// by copying the contents into a newly allocated [`Box`].
791    fn from(s: &mut CStr) -> Box<CStr> {
792        Self::from(&*s)
793    }
794}
795
796#[stable(feature = "box_from_cow", since = "1.45.0")]
797impl From<Cow<'_, CStr>> for Box<CStr> {
798    /// Converts a `Cow<'a, CStr>` into a `Box<CStr>`,
799    /// by copying the contents if they are borrowed.
800    #[inline]
801    fn from(cow: Cow<'_, CStr>) -> Box<CStr> {
802        match cow {
803            Cow::Borrowed(s) => Box::from(s),
804            Cow::Owned(s) => Box::from(s),
805        }
806    }
807}
808
809#[stable(feature = "c_string_from_box", since = "1.18.0")]
810impl From<Box<CStr>> for CString {
811    /// Converts a <code>[Box]<[CStr]></code> into a [`CString`] without copying or allocating.
812    #[inline]
813    fn from(s: Box<CStr>) -> CString {
814        let raw = Box::into_raw(s) as *mut [u8];
815        // SAFETY: Converting a *mut CStr -> *mut [u8] -> CString is valid.
816        CString { inner: unsafe { Box::from_raw(raw) } }
817    }
818}
819
820#[stable(feature = "cstring_from_vec_of_nonzerou8", since = "1.43.0")]
821impl From<Vec<NonZero<u8>>> for CString {
822    /// Converts a <code>[Vec]<[NonZero]<[u8]>></code> into a [`CString`] without
823    /// copying nor checking for inner nul bytes.
824    #[inline]
825    fn from(v: Vec<NonZero<u8>>) -> CString {
826        // Transmute `Vec<NonZero<u8>>` to `Vec<u8>`.
827        let v: Vec<u8> = {
828            let (ptr, len, cap): (*mut NonZero<u8>, _, _) = Vec::into_raw_parts(v);
829            // SAFETY:
830            //   - transmuting between `NonZero<u8>` and `u8` is sound;
831            //   - `alloc::Layout<NonZero<u8>> == alloc::Layout<u8>`.
832            unsafe { Vec::from_raw_parts(ptr.cast::<u8>(), len, cap) }
833        };
834        // SAFETY: `v` cannot contain nul bytes, given the type-level
835        // invariant of `NonZero<u8>`.
836        unsafe { Self::_from_vec_unchecked(v) }
837    }
838}
839
840#[stable(feature = "c_string_from_str", since = "1.85.0")]
841impl FromStr for CString {
842    type Err = NulError;
843
844    /// Converts a string `s` into a [`CString`].
845    ///
846    /// This method is equivalent to [`CString::new`].
847    #[inline]
848    fn from_str(s: &str) -> Result<Self, Self::Err> {
849        Self::new(s)
850    }
851}
852
853#[stable(feature = "c_string_from_str", since = "1.85.0")]
854impl TryFrom<CString> for String {
855    type Error = IntoStringError;
856
857    /// Converts a [`CString`] into a [`String`] if it contains valid UTF-8 data.
858    ///
859    /// This method is equivalent to [`CString::into_string`].
860    #[inline]
861    fn try_from(value: CString) -> Result<Self, Self::Error> {
862        value.into_string()
863    }
864}
865
866#[stable(feature = "more_box_slice_clone", since = "1.29.0")]
867impl<A: Allocator + Clone> Clone for Box<CStr, A> {
868    #[inline]
869    fn clone(&self) -> Self {
870        Box::clone_from_ref_in(&**self, Self::allocator(self).clone())
871    }
872}
873
874#[stable(feature = "box_from_c_string", since = "1.20.0")]
875impl From<CString> for Box<CStr> {
876    /// Converts a [`CString`] into a <code>[Box]<[CStr]></code> without copying or allocating.
877    #[inline]
878    fn from(s: CString) -> Box<CStr> {
879        s.into_boxed_c_str()
880    }
881}
882
883#[stable(feature = "cow_from_cstr", since = "1.28.0")]
884impl<'a> From<CString> for Cow<'a, CStr> {
885    /// Converts a [`CString`] into an owned [`Cow`] without copying or allocating.
886    #[inline]
887    fn from(s: CString) -> Cow<'a, CStr> {
888        Cow::Owned(s)
889    }
890}
891
892#[stable(feature = "cow_from_cstr", since = "1.28.0")]
893impl<'a> From<&'a CStr> for Cow<'a, CStr> {
894    /// Converts a [`CStr`] into a borrowed [`Cow`] without copying or allocating.
895    #[inline]
896    fn from(s: &'a CStr) -> Cow<'a, CStr> {
897        Cow::Borrowed(s)
898    }
899}
900
901#[stable(feature = "cow_from_cstr", since = "1.28.0")]
902impl<'a> From<&'a CString> for Cow<'a, CStr> {
903    /// Converts a `&`[`CString`] into a borrowed [`Cow`] without copying or allocating.
904    #[inline]
905    fn from(s: &'a CString) -> Cow<'a, CStr> {
906        Cow::Borrowed(s.as_c_str())
907    }
908}
909
910#[cfg(target_has_atomic = "ptr")]
911#[stable(feature = "shared_from_slice2", since = "1.24.0")]
912impl From<CString> for Arc<CStr> {
913    /// Converts a [`CString`] into an <code>[Arc]<[CStr]></code> by moving the [`CString`]
914    /// data into a new [`Arc`] buffer.
915    #[inline]
916    fn from(s: CString) -> Arc<CStr> {
917        let arc: Arc<[u8]> = Arc::from(s.into_inner());
918        // SAFETY: Type conversion is valid.
919        unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
920    }
921}
922
923#[cfg(target_has_atomic = "ptr")]
924#[stable(feature = "shared_from_slice2", since = "1.24.0")]
925impl From<&CStr> for Arc<CStr> {
926    /// Converts a `&CStr` into a `Arc<CStr>`,
927    /// by copying the contents into a newly allocated [`Arc`].
928    #[inline]
929    fn from(s: &CStr) -> Arc<CStr> {
930        let arc: Arc<[u8]> = Arc::from(s.to_bytes_with_nul());
931        // SAFETY: Type conversion is valid.
932        unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
933    }
934}
935
936#[cfg(target_has_atomic = "ptr")]
937#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
938impl From<&mut CStr> for Arc<CStr> {
939    /// Converts a `&mut CStr` into a `Arc<CStr>`,
940    /// by copying the contents into a newly allocated [`Arc`].
941    #[inline]
942    fn from(s: &mut CStr) -> Arc<CStr> {
943        Arc::from(&*s)
944    }
945}
946
947#[stable(feature = "shared_from_slice2", since = "1.24.0")]
948impl From<CString> for Rc<CStr> {
949    /// Converts a [`CString`] into an <code>[Rc]<[CStr]></code> by moving the [`CString`]
950    /// data into a new [`Rc`] buffer.
951    #[inline]
952    fn from(s: CString) -> Rc<CStr> {
953        let rc: Rc<[u8]> = Rc::from(s.into_inner());
954        // SAFETY: Type conversion is valid.
955        unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
956    }
957}
958
959#[stable(feature = "shared_from_slice2", since = "1.24.0")]
960impl From<&CStr> for Rc<CStr> {
961    /// Converts a `&CStr` into a `Rc<CStr>`,
962    /// by copying the contents into a newly allocated [`Rc`].
963    #[inline]
964    fn from(s: &CStr) -> Rc<CStr> {
965        let rc: Rc<[u8]> = Rc::from(s.to_bytes_with_nul());
966        // SAFETY: Type conversion is valid.
967        unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
968    }
969}
970
971#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
972impl From<&mut CStr> for Rc<CStr> {
973    /// Converts a `&mut CStr` into a `Rc<CStr>`,
974    /// by copying the contents into a newly allocated [`Rc`].
975    #[inline]
976    fn from(s: &mut CStr) -> Rc<CStr> {
977        Rc::from(&*s)
978    }
979}
980
981#[cfg(not(no_global_oom_handling))]
982#[stable(feature = "more_rc_default_impls", since = "1.80.0")]
983impl Default for Rc<CStr> {
984    /// Creates an empty CStr inside an Rc
985    ///
986    /// This may or may not share an allocation with other Rcs on the same thread.
987    #[inline]
988    fn default() -> Self {
989        Rc::from(c"")
990    }
991}
992
993#[stable(feature = "default_box_extra", since = "1.17.0")]
994impl Default for Box<CStr> {
995    fn default() -> Box<CStr> {
996        Box::from(c"")
997    }
998}
999
1000impl NulError {
1001    /// Returns the position of the nul byte in the slice that caused
1002    /// [`CString::new`] to fail.
1003    ///
1004    /// # Examples
1005    ///
1006    /// ```
1007    /// use std::ffi::CString;
1008    ///
1009    /// let nul_error = CString::new("foo\0bar").unwrap_err();
1010    /// assert_eq!(nul_error.nul_position(), 3);
1011    ///
1012    /// let nul_error = CString::new("foo bar\0").unwrap_err();
1013    /// assert_eq!(nul_error.nul_position(), 7);
1014    /// ```
1015    #[must_use]
1016    #[stable(feature = "rust1", since = "1.0.0")]
1017    pub fn nul_position(&self) -> usize {
1018        self.0
1019    }
1020
1021    /// Consumes this error, returning the underlying vector of bytes which
1022    /// generated the error in the first place.
1023    ///
1024    /// # Examples
1025    ///
1026    /// ```
1027    /// use std::ffi::CString;
1028    ///
1029    /// let nul_error = CString::new("foo\0bar").unwrap_err();
1030    /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
1031    /// ```
1032    #[must_use = "`self` will be dropped if the result is not used"]
1033    #[stable(feature = "rust1", since = "1.0.0")]
1034    pub fn into_vec(self) -> Vec<u8> {
1035        self.1
1036    }
1037}
1038
1039#[stable(feature = "rust1", since = "1.0.0")]
1040impl fmt::Display for NulError {
1041    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1042        write!(f, "nul byte found in provided data at position: {}", self.0)
1043    }
1044}
1045
1046#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
1047impl fmt::Display for FromVecWithNulError {
1048    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1049        match self.error_kind {
1050            FromBytesWithNulErrorKind::InteriorNul(pos) => {
1051                write!(f, "data provided contains an interior nul byte at pos {pos}")
1052            }
1053            FromBytesWithNulErrorKind::NotNulTerminated => {
1054                write!(f, "data provided is not nul terminated")
1055            }
1056        }
1057    }
1058}
1059
1060impl IntoStringError {
1061    /// Consumes this error, returning original [`CString`] which generated the
1062    /// error.
1063    #[must_use = "`self` will be dropped if the result is not used"]
1064    #[stable(feature = "cstring_into", since = "1.7.0")]
1065    pub fn into_cstring(self) -> CString {
1066        self.inner
1067    }
1068
1069    /// Access the underlying UTF-8 error that was the cause of this error.
1070    #[must_use]
1071    #[stable(feature = "cstring_into", since = "1.7.0")]
1072    pub fn utf8_error(&self) -> Utf8Error {
1073        self.error
1074    }
1075}
1076
1077#[stable(feature = "cstring_into", since = "1.7.0")]
1078impl fmt::Display for IntoStringError {
1079    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1080        "C string contained non-utf8 bytes".fmt(f)
1081    }
1082}
1083
1084#[stable(feature = "cstr_borrow", since = "1.3.0")]
1085impl ToOwned for CStr {
1086    type Owned = CString;
1087
1088    fn to_owned(&self) -> CString {
1089        CString { inner: self.to_bytes_with_nul().into() }
1090    }
1091
1092    fn clone_into(&self, target: &mut CString) {
1093        let src = self.to_bytes_with_nul();
1094        // If the lengths match, we can reuse the existing allocation without any overhead.
1095        if target.inner.len() == src.len() {
1096            target.inner.copy_from_slice(src);
1097        } else {
1098            // Reuse the existing allocation's capacity by converting to a Vec.
1099            // We temporarily replace `target` with a valid dummy to remain panic-safe.
1100            let mut b = mem::replace(&mut target.inner, Box::new([0])).into_vec();
1101            self.to_bytes_with_nul().clone_into(&mut b);
1102            target.inner = b.into_boxed_slice();
1103        }
1104    }
1105}
1106
1107#[stable(feature = "cstring_asref", since = "1.7.0")]
1108impl From<&CStr> for CString {
1109    /// Converts a <code>&[CStr]</code> into a [`CString`]
1110    /// by copying the contents into a new allocation.
1111    fn from(s: &CStr) -> CString {
1112        s.to_owned()
1113    }
1114}
1115
1116#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1117impl PartialEq<CStr> for CString {
1118    #[inline]
1119    fn eq(&self, other: &CStr) -> bool {
1120        **self == *other
1121    }
1122
1123    #[inline]
1124    fn ne(&self, other: &CStr) -> bool {
1125        **self != *other
1126    }
1127}
1128
1129#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1130impl PartialEq<&CStr> for CString {
1131    #[inline]
1132    fn eq(&self, other: &&CStr) -> bool {
1133        **self == **other
1134    }
1135
1136    #[inline]
1137    fn ne(&self, other: &&CStr) -> bool {
1138        **self != **other
1139    }
1140}
1141
1142#[cfg(not(no_global_oom_handling))]
1143#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1144impl PartialEq<Cow<'_, CStr>> for CString {
1145    #[inline]
1146    fn eq(&self, other: &Cow<'_, CStr>) -> bool {
1147        **self == **other
1148    }
1149
1150    #[inline]
1151    fn ne(&self, other: &Cow<'_, CStr>) -> bool {
1152        **self != **other
1153    }
1154}
1155
1156#[stable(feature = "cstring_asref", since = "1.7.0")]
1157impl ops::Index<ops::RangeFull> for CString {
1158    type Output = CStr;
1159
1160    #[inline]
1161    fn index(&self, _index: ops::RangeFull) -> &CStr {
1162        self
1163    }
1164}
1165
1166#[stable(feature = "cstring_asref", since = "1.7.0")]
1167impl AsRef<CStr> for CString {
1168    #[inline]
1169    fn as_ref(&self) -> &CStr {
1170        self
1171    }
1172}
1173
1174impl CStr {
1175    /// Converts a `CStr` into a <code>[Cow]<[str]></code>.
1176    ///
1177    /// If the contents of the `CStr` are valid UTF-8 data, this
1178    /// function will return a <code>[Cow]::[Borrowed]\(&[str])</code>
1179    /// with the corresponding <code>&[str]</code> slice. Otherwise, it will
1180    /// replace any invalid UTF-8 sequences with
1181    /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD] and return a
1182    /// <code>[Cow]::[Owned]\([String])</code> with the result.
1183    ///
1184    /// [str]: prim@str "str"
1185    /// [Borrowed]: Cow::Borrowed
1186    /// [Owned]: Cow::Owned
1187    /// [U+FFFD]: char::REPLACEMENT_CHARACTER
1188    ///
1189    /// # Examples
1190    ///
1191    /// Calling `to_string_lossy` on a `CStr` containing valid UTF-8. The leading
1192    /// `c` on the string literal denotes a `CStr`.
1193    ///
1194    /// ```
1195    /// use std::borrow::Cow;
1196    ///
1197    /// assert_eq!(c"Hello World".to_string_lossy(), Cow::Borrowed("Hello World"));
1198    /// ```
1199    ///
1200    /// Calling `to_string_lossy` on a `CStr` containing invalid UTF-8:
1201    ///
1202    /// ```
1203    /// use std::borrow::Cow;
1204    ///
1205    /// assert_eq!(
1206    ///     c"Hello \xF0\x90\x80World".to_string_lossy(),
1207    ///     Cow::Owned(String::from("Hello �World")) as Cow<'_, str>
1208    /// );
1209    /// ```
1210    #[rustc_allow_incoherent_impl]
1211    #[must_use = "this returns the result of the operation, \
1212                  without modifying the original"]
1213    #[stable(feature = "cstr_to_str", since = "1.4.0")]
1214    pub fn to_string_lossy(&self) -> Cow<'_, str> {
1215        String::from_utf8_lossy(self.to_bytes())
1216    }
1217
1218    /// Converts a <code>[Box]<[CStr]></code> into a [`CString`] without copying or allocating.
1219    ///
1220    /// # Examples
1221    ///
1222    /// ```
1223    /// use std::ffi::{CStr, CString};
1224    ///
1225    /// let boxed: Box<CStr> = Box::from(c"foo");
1226    /// let c_string: CString = c"foo".to_owned();
1227    ///
1228    /// assert_eq!(boxed.into_c_string(), c_string);
1229    /// ```
1230    #[rustc_allow_incoherent_impl]
1231    #[must_use = "`self` will be dropped if the result is not used"]
1232    #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
1233    pub fn into_c_string(self: Box<Self>) -> CString {
1234        CString::from(self)
1235    }
1236}
1237
1238#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1239impl PartialEq<CString> for CStr {
1240    #[inline]
1241    fn eq(&self, other: &CString) -> bool {
1242        *self == **other
1243    }
1244
1245    #[inline]
1246    fn ne(&self, other: &CString) -> bool {
1247        *self != **other
1248    }
1249}
1250
1251#[cfg(not(no_global_oom_handling))]
1252#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1253impl PartialEq<Cow<'_, Self>> for CStr {
1254    #[inline]
1255    fn eq(&self, other: &Cow<'_, Self>) -> bool {
1256        *self == **other
1257    }
1258
1259    #[inline]
1260    fn ne(&self, other: &Cow<'_, Self>) -> bool {
1261        *self != **other
1262    }
1263}
1264
1265#[cfg(not(no_global_oom_handling))]
1266#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1267impl PartialEq<CStr> for Cow<'_, CStr> {
1268    #[inline]
1269    fn eq(&self, other: &CStr) -> bool {
1270        **self == *other
1271    }
1272
1273    #[inline]
1274    fn ne(&self, other: &CStr) -> bool {
1275        **self != *other
1276    }
1277}
1278
1279#[cfg(not(no_global_oom_handling))]
1280#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1281impl PartialEq<&CStr> for Cow<'_, CStr> {
1282    #[inline]
1283    fn eq(&self, other: &&CStr) -> bool {
1284        **self == **other
1285    }
1286
1287    #[inline]
1288    fn ne(&self, other: &&CStr) -> bool {
1289        **self != **other
1290    }
1291}
1292
1293#[cfg(not(no_global_oom_handling))]
1294#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1295impl PartialEq<CString> for Cow<'_, CStr> {
1296    #[inline]
1297    fn eq(&self, other: &CString) -> bool {
1298        **self == **other
1299    }
1300
1301    #[inline]
1302    fn ne(&self, other: &CString) -> bool {
1303        **self != **other
1304    }
1305}
1306
1307#[stable(feature = "rust1", since = "1.0.0")]
1308impl core::error::Error for NulError {}
1309
1310#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
1311impl core::error::Error for FromVecWithNulError {}
1312
1313#[stable(feature = "cstring_into", since = "1.7.0")]
1314impl core::error::Error for IntoStringError {
1315    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
1316        Some(&self.error)
1317    }
1318}