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