core/ffi/
c_str.rs

1//! [`CStr`] and its related types.
2
3#[cfg(not(feature = "ferrocene_subset"))]
4use crate::cmp::Ordering;
5#[cfg(not(feature = "ferrocene_subset"))]
6use crate::error::Error;
7use crate::ffi::c_char;
8use crate::intrinsics::const_eval_select;
9#[cfg(not(feature = "ferrocene_subset"))]
10use crate::iter::FusedIterator;
11#[cfg(not(feature = "ferrocene_subset"))]
12use crate::marker::PhantomData;
13#[cfg(not(feature = "ferrocene_subset"))]
14use crate::ptr::NonNull;
15use crate::slice::memchr;
16#[cfg(not(feature = "ferrocene_subset"))]
17use crate::{fmt, ops, slice, str};
18
19// Ferrocene addition: imports for certified subset
20#[cfg(feature = "ferrocene_subset")]
21#[rustfmt::skip]
22use crate::slice;
23
24// FIXME: because this is doc(inline)d, we *have* to use intra-doc links because the actual link
25//   depends on where the item is being documented. however, since this is libcore, we can't
26//   actually reference libstd or liballoc in intra-doc links. so, the best we can do is remove the
27//   links to `CString` and `String` for now until a solution is developed
28
29/// A dynamically-sized view of a C string.
30///
31/// The type `&CStr` represents a reference to a borrowed nul-terminated
32/// array of bytes. It can be constructed safely from a <code>&[[u8]]</code>
33/// slice, or unsafely from a raw `*const c_char`. It can be expressed as a
34/// literal in the form `c"Hello world"`.
35///
36/// The `&CStr` can then be converted to a Rust <code>&[str]</code> by performing
37/// UTF-8 validation, or into an owned `CString`.
38///
39/// `&CStr` is to `CString` as <code>&[str]</code> is to `String`: the former
40/// in each pair are borrowing references; the latter are owned
41/// strings.
42///
43/// Note that this structure does **not** have a guaranteed layout (the `repr(transparent)`
44/// notwithstanding) and should not be placed in the signatures of FFI functions.
45/// Instead, safe wrappers of FFI functions may leverage [`CStr::as_ptr`] and the unsafe
46/// [`CStr::from_ptr`] constructor to provide a safe interface to other consumers.
47///
48/// # Examples
49///
50/// Inspecting a foreign C string:
51///
52/// ```
53/// use std::ffi::CStr;
54/// use std::os::raw::c_char;
55///
56/// # /* Extern functions are awkward in doc comments - fake it instead
57/// extern "C" { fn my_string() -> *const c_char; }
58/// # */ unsafe extern "C" fn my_string() -> *const c_char { c"hello".as_ptr() }
59///
60/// unsafe {
61///     let slice = CStr::from_ptr(my_string());
62///     println!("string buffer size without nul terminator: {}", slice.to_bytes().len());
63/// }
64/// ```
65///
66/// Passing a Rust-originating C string:
67///
68/// ```
69/// use std::ffi::CStr;
70/// use std::os::raw::c_char;
71///
72/// fn work(data: &CStr) {
73///     unsafe extern "C" fn work_with(s: *const c_char) {}
74///     unsafe { work_with(data.as_ptr()) }
75/// }
76///
77/// let s = c"Hello world!";
78/// work(&s);
79/// ```
80///
81/// Converting a foreign C string into a Rust `String`:
82///
83/// ```
84/// use std::ffi::CStr;
85/// use std::os::raw::c_char;
86///
87/// # /* Extern functions are awkward in doc comments - fake it instead
88/// extern "C" { fn my_string() -> *const c_char; }
89/// # */ unsafe extern "C" fn my_string() -> *const c_char { c"hello".as_ptr() }
90///
91/// fn my_string_safe() -> String {
92///     let cstr = unsafe { CStr::from_ptr(my_string()) };
93///     // Get a copy-on-write Cow<'_, str>, then extract the
94///     // allocated String (or allocate a fresh one if needed).
95///     cstr.to_string_lossy().into_owned()
96/// }
97///
98/// println!("string: {}", my_string_safe());
99/// ```
100///
101/// [str]: prim@str "str"
102#[cfg_attr(not(feature = "ferrocene_subset"), derive(PartialEq, Eq, Hash))]
103#[stable(feature = "core_c_str", since = "1.64.0")]
104#[rustc_diagnostic_item = "cstr_type"]
105#[rustc_has_incoherent_inherent_impls]
106#[lang = "CStr"]
107// `fn from` in `impl From<&CStr> for Box<CStr>` current implementation relies
108// on `CStr` being layout-compatible with `[u8]`.
109// However, `CStr` layout is considered an implementation detail and must not be relied upon. We
110// want `repr(transparent)` but we don't want it to show up in rustdoc, so we hide it under
111// `cfg(doc)`. This is an ad-hoc implementation of attribute privacy.
112#[repr(transparent)]
113pub struct CStr {
114    // FIXME: this should not be represented with a DST slice but rather with
115    //        just a raw `c_char` along with some form of marker to make
116    //        this an unsized type. Essentially `sizeof(&CStr)` should be the
117    //        same as `sizeof(&c_char)` but `CStr` should be an unsized type.
118    inner: [c_char],
119}
120
121/// An error indicating that a nul byte was not in the expected position.
122///
123/// The slice used to create a [`CStr`] must have one and only one nul byte,
124/// positioned at the end.
125///
126/// This error is created by the [`CStr::from_bytes_with_nul`] method.
127/// See its documentation for more.
128///
129/// # Examples
130///
131/// ```
132/// use std::ffi::{CStr, FromBytesWithNulError};
133///
134/// let _: FromBytesWithNulError = CStr::from_bytes_with_nul(b"f\0oo").unwrap_err();
135/// ```
136#[cfg_attr(not(feature = "ferrocene_subset"), derive(Clone, Copy, PartialEq, Eq, Debug))]
137#[stable(feature = "core_c_str", since = "1.64.0")]
138pub enum FromBytesWithNulError {
139    /// Data provided contains an interior nul byte at byte `position`.
140    InteriorNul {
141        /// The position of the interior nul byte.
142        position: usize,
143    },
144    /// Data provided is not nul terminated.
145    NotNulTerminated,
146}
147
148#[cfg(not(feature = "ferrocene_subset"))]
149#[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
150impl fmt::Display for FromBytesWithNulError {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        match self {
153            Self::InteriorNul { position } => {
154                write!(f, "data provided contains an interior nul byte at byte position {position}")
155            }
156            Self::NotNulTerminated => write!(f, "data provided is not nul terminated"),
157        }
158    }
159}
160
161#[cfg(not(feature = "ferrocene_subset"))]
162#[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
163impl Error for FromBytesWithNulError {}
164
165/// An error indicating that no nul byte was present.
166///
167/// A slice used to create a [`CStr`] must contain a nul byte somewhere
168/// within the slice.
169///
170/// This error is created by the [`CStr::from_bytes_until_nul`] method.
171#[cfg(not(feature = "ferrocene_subset"))]
172#[derive(Clone, PartialEq, Eq, Debug)]
173#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
174pub struct FromBytesUntilNulError(());
175
176#[cfg(not(feature = "ferrocene_subset"))]
177#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
178impl fmt::Display for FromBytesUntilNulError {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        write!(f, "data provided does not contain a nul")
181    }
182}
183
184/// Shows the underlying bytes as a normal string, with invalid UTF-8
185/// presented as hex escape sequences.
186#[cfg(not(feature = "ferrocene_subset"))]
187#[stable(feature = "cstr_debug", since = "1.3.0")]
188impl fmt::Debug for CStr {
189    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190        fmt::Debug::fmt(crate::bstr::ByteStr::from_bytes(self.to_bytes()), f)
191    }
192}
193
194#[cfg(not(feature = "ferrocene_subset"))]
195#[stable(feature = "cstr_default", since = "1.10.0")]
196impl Default for &CStr {
197    #[inline]
198    fn default() -> Self {
199        c""
200    }
201}
202
203impl CStr {
204    /// Wraps a raw C string with a safe C string wrapper.
205    ///
206    /// This function will wrap the provided `ptr` with a `CStr` wrapper, which
207    /// allows inspection and interoperation of non-owned C strings. The total
208    /// size of the terminated buffer must be smaller than [`isize::MAX`] **bytes**
209    /// in memory (a restriction from [`slice::from_raw_parts`]).
210    ///
211    /// # Safety
212    ///
213    /// * The memory pointed to by `ptr` must contain a valid nul terminator at the
214    ///   end of the string.
215    ///
216    /// * `ptr` must be [valid] for reads of bytes up to and including the nul terminator.
217    ///   This means in particular:
218    ///
219    ///     * The entire memory range of this `CStr` must be contained within a single allocation!
220    ///     * `ptr` must be non-null even for a zero-length cstr.
221    ///
222    /// * The memory referenced by the returned `CStr` must not be mutated for
223    ///   the duration of lifetime `'a`.
224    ///
225    /// * The nul terminator must be within `isize::MAX` from `ptr`
226    ///
227    /// > **Note**: This operation is intended to be a 0-cost cast but it is
228    /// > currently implemented with an up-front calculation of the length of
229    /// > the string. This is not guaranteed to always be the case.
230    ///
231    /// # Caveat
232    ///
233    /// The lifetime for the returned slice is inferred from its usage. To prevent accidental misuse,
234    /// it's suggested to tie the lifetime to whichever source lifetime is safe in the context,
235    /// such as by providing a helper function taking the lifetime of a host value for the slice,
236    /// or by explicit annotation.
237    ///
238    /// # Examples
239    ///
240    /// ```
241    /// use std::ffi::{c_char, CStr};
242    ///
243    /// fn my_string() -> *const c_char {
244    ///     c"hello".as_ptr()
245    /// }
246    ///
247    /// unsafe {
248    ///     let slice = CStr::from_ptr(my_string());
249    ///     assert_eq!(slice.to_str().unwrap(), "hello");
250    /// }
251    /// ```
252    ///
253    /// ```
254    /// use std::ffi::{c_char, CStr};
255    ///
256    /// const HELLO_PTR: *const c_char = {
257    ///     const BYTES: &[u8] = b"Hello, world!\0";
258    ///     BYTES.as_ptr().cast()
259    /// };
260    /// const HELLO: &CStr = unsafe { CStr::from_ptr(HELLO_PTR) };
261    ///
262    /// assert_eq!(c"Hello, world!", HELLO);
263    /// ```
264    ///
265    /// [valid]: core::ptr#safety
266    #[inline] // inline is necessary for codegen to see strlen.
267    #[must_use]
268    #[stable(feature = "rust1", since = "1.0.0")]
269    #[rustc_const_stable(feature = "const_cstr_from_ptr", since = "1.81.0")]
270    pub const unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
271        // SAFETY: The caller has provided a pointer that points to a valid C
272        // string with a NUL terminator less than `isize::MAX` from `ptr`.
273        let len = unsafe { strlen(ptr) };
274
275        // SAFETY: The caller has provided a valid pointer with length less than
276        // `isize::MAX`, so `from_raw_parts` is safe. The content remains valid
277        // and doesn't change for the lifetime of the returned `CStr`. This
278        // means the call to `from_bytes_with_nul_unchecked` is correct.
279        //
280        // The cast from c_char to u8 is ok because a c_char is always one byte.
281        unsafe { Self::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr.cast(), len + 1)) }
282    }
283
284    /// Creates a C string wrapper from a byte slice with any number of nuls.
285    ///
286    /// This method will create a `CStr` from any byte slice that contains at
287    /// least one nul byte. Unlike with [`CStr::from_bytes_with_nul`], the caller
288    /// does not need to know where the nul byte is located.
289    ///
290    /// If the first byte is a nul character, this method will return an
291    /// empty `CStr`. If multiple nul characters are present, the `CStr` will
292    /// end at the first one.
293    ///
294    /// If the slice only has a single nul byte at the end, this method is
295    /// equivalent to [`CStr::from_bytes_with_nul`].
296    ///
297    /// # Examples
298    /// ```
299    /// use std::ffi::CStr;
300    ///
301    /// let mut buffer = [0u8; 16];
302    /// unsafe {
303    ///     // Here we might call an unsafe C function that writes a string
304    ///     // into the buffer.
305    ///     let buf_ptr = buffer.as_mut_ptr();
306    ///     buf_ptr.write_bytes(b'A', 8);
307    /// }
308    /// // Attempt to extract a C nul-terminated string from the buffer.
309    /// let c_str = CStr::from_bytes_until_nul(&buffer[..]).unwrap();
310    /// assert_eq!(c_str.to_str().unwrap(), "AAAAAAAA");
311    /// ```
312    ///
313    #[cfg(not(feature = "ferrocene_subset"))]
314    #[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
315    #[rustc_const_stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
316    pub const fn from_bytes_until_nul(bytes: &[u8]) -> Result<&CStr, FromBytesUntilNulError> {
317        let nul_pos = memchr::memchr(0, bytes);
318        match nul_pos {
319            Some(nul_pos) => {
320                // FIXME(const-hack) replace with range index
321                // SAFETY: nul_pos + 1 <= bytes.len()
322                let subslice = unsafe { crate::slice::from_raw_parts(bytes.as_ptr(), nul_pos + 1) };
323                // SAFETY: We know there is a nul byte at nul_pos, so this slice
324                // (ending at the nul byte) is a well-formed C string.
325                Ok(unsafe { CStr::from_bytes_with_nul_unchecked(subslice) })
326            }
327            None => Err(FromBytesUntilNulError(())),
328        }
329    }
330
331    /// Creates a C string wrapper from a byte slice with exactly one nul
332    /// terminator.
333    ///
334    /// This function will cast the provided `bytes` to a `CStr`
335    /// wrapper after ensuring that the byte slice is nul-terminated
336    /// and does not contain any interior nul bytes.
337    ///
338    /// If the nul byte may not be at the end,
339    /// [`CStr::from_bytes_until_nul`] can be used instead.
340    ///
341    /// # Examples
342    ///
343    /// ```
344    /// use std::ffi::CStr;
345    ///
346    /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
347    /// assert_eq!(cstr, Ok(c"hello"));
348    /// ```
349    ///
350    /// Creating a `CStr` without a trailing nul terminator is an error:
351    ///
352    /// ```
353    /// use std::ffi::{CStr, FromBytesWithNulError};
354    ///
355    /// let cstr = CStr::from_bytes_with_nul(b"hello");
356    /// assert_eq!(cstr, Err(FromBytesWithNulError::NotNulTerminated));
357    /// ```
358    ///
359    /// Creating a `CStr` with an interior nul byte is an error:
360    ///
361    /// ```
362    /// use std::ffi::{CStr, FromBytesWithNulError};
363    ///
364    /// let cstr = CStr::from_bytes_with_nul(b"he\0llo\0");
365    /// assert_eq!(cstr, Err(FromBytesWithNulError::InteriorNul { position: 2 }));
366    /// ```
367    #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
368    #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")]
369    pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, FromBytesWithNulError> {
370        let nul_pos = memchr::memchr(0, bytes);
371        match nul_pos {
372            Some(nul_pos) if nul_pos + 1 == bytes.len() => {
373                // SAFETY: We know there is only one nul byte, at the end
374                // of the byte slice.
375                Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) })
376            }
377            Some(position) => Err(FromBytesWithNulError::InteriorNul { position }),
378            None => Err(FromBytesWithNulError::NotNulTerminated),
379        }
380    }
381
382    /// Unsafely creates a C string wrapper from a byte slice.
383    ///
384    /// This function will cast the provided `bytes` to a `CStr` wrapper without
385    /// performing any sanity checks.
386    ///
387    /// # Safety
388    /// The provided slice **must** be nul-terminated and not contain any interior
389    /// nul bytes.
390    ///
391    /// # Examples
392    ///
393    /// ```
394    /// use std::ffi::CStr;
395    ///
396    /// let bytes = b"Hello world!\0";
397    ///
398    /// let cstr = unsafe { CStr::from_bytes_with_nul_unchecked(bytes) };
399    /// assert_eq!(cstr.to_bytes_with_nul(), bytes);
400    /// ```
401    #[inline]
402    #[must_use]
403    #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
404    #[rustc_const_stable(feature = "const_cstr_unchecked", since = "1.59.0")]
405    #[rustc_allow_const_fn_unstable(const_eval_select)]
406    pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
407        const_eval_select!(
408            @capture { bytes: &[u8] } -> &CStr:
409            if const {
410                // Saturating so that an empty slice panics in the assert with a good
411                // message, not here due to underflow.
412                let mut i = bytes.len().saturating_sub(1);
413                assert!(!bytes.is_empty() && bytes[i] == 0, "input was not nul-terminated");
414
415                // Ending nul byte exists, skip to the rest.
416                while i != 0 {
417                    i -= 1;
418                    let byte = bytes[i];
419                    assert!(byte != 0, "input contained interior nul");
420                }
421
422                // SAFETY: See runtime cast comment below.
423                unsafe { &*(bytes as *const [u8] as *const CStr) }
424            } else {
425                // Chance at catching some UB at runtime with debug builds.
426                debug_assert!(!bytes.is_empty() && bytes[bytes.len() - 1] == 0);
427
428                // SAFETY: Casting to CStr is safe because its internal representation
429                // is a [u8] too (safe only inside std).
430                // Dereferencing the obtained pointer is safe because it comes from a
431                // reference. Making a reference is then safe because its lifetime
432                // is bound by the lifetime of the given `bytes`.
433                unsafe { &*(bytes as *const [u8] as *const CStr) }
434            }
435        )
436    }
437
438    /// Returns the inner pointer to this C string.
439    ///
440    /// The returned pointer will be valid for as long as `self` is, and points
441    /// to a contiguous region of memory terminated with a 0 byte to represent
442    /// the end of the string.
443    ///
444    /// The type of the returned pointer is
445    /// [`*const c_char`][crate::ffi::c_char], and whether it's
446    /// an alias for `*const i8` or `*const u8` is platform-specific.
447    ///
448    /// **WARNING**
449    ///
450    /// The returned pointer is read-only; writing to it (including passing it
451    /// to C code that writes to it) causes undefined behavior.
452    ///
453    /// It is your responsibility to make sure that the underlying memory is not
454    /// freed too early. For example, the following code will cause undefined
455    /// behavior when `ptr` is used inside the `unsafe` block:
456    ///
457    /// ```no_run
458    /// # #![expect(dangling_pointers_from_temporaries)]
459    /// use std::ffi::{CStr, CString};
460    ///
461    /// // 💀 The meaning of this entire program is undefined,
462    /// // 💀 and nothing about its behavior is guaranteed,
463    /// // 💀 not even that its behavior resembles the code as written,
464    /// // 💀 just because it contains a single instance of undefined behavior!
465    ///
466    /// // 🚨 creates a dangling pointer to a temporary `CString`
467    /// // 🚨 that is deallocated at the end of the statement
468    /// let ptr = CString::new("Hi!".to_uppercase()).unwrap().as_ptr();
469    ///
470    /// // without undefined behavior, you would expect that `ptr` equals:
471    /// dbg!(CStr::from_bytes_with_nul(b"HI!\0").unwrap());
472    ///
473    /// // 🙏 Possibly the program behaved as expected so far,
474    /// // 🙏 and this just shows `ptr` is now garbage..., but
475    /// // 💀 this violates `CStr::from_ptr`'s safety contract
476    /// // 💀 leading to a dereference of a dangling pointer,
477    /// // 💀 which is immediate undefined behavior.
478    /// // 💀 *BOOM*, you're dead, your entire program has no meaning.
479    /// dbg!(unsafe { CStr::from_ptr(ptr) });
480    /// ```
481    ///
482    /// This happens because, the pointer returned by `as_ptr` does not carry any
483    /// lifetime information, and the `CString` is deallocated immediately after
484    /// the expression that it is part of has been evaluated.
485    /// To fix the problem, bind the `CString` to a local variable:
486    ///
487    /// ```
488    /// use std::ffi::{CStr, CString};
489    ///
490    /// let c_str = CString::new("Hi!".to_uppercase()).unwrap();
491    /// let ptr = c_str.as_ptr();
492    ///
493    /// assert_eq!(unsafe { CStr::from_ptr(ptr) }, c"HI!");
494    /// ```
495    #[cfg(not(feature = "ferrocene_subset"))]
496    #[inline]
497    #[must_use]
498    #[stable(feature = "rust1", since = "1.0.0")]
499    #[rustc_const_stable(feature = "const_str_as_ptr", since = "1.32.0")]
500    #[rustc_as_ptr]
501    #[rustc_never_returns_null_ptr]
502    pub const fn as_ptr(&self) -> *const c_char {
503        self.inner.as_ptr()
504    }
505
506    /// We could eventually expose this publicly, if we wanted.
507    #[cfg(not(feature = "ferrocene_subset"))]
508    #[inline]
509    #[must_use]
510    const fn as_non_null_ptr(&self) -> NonNull<c_char> {
511        // FIXME(const_trait_impl) replace with `NonNull::from`
512        // SAFETY: a reference is never null
513        unsafe { NonNull::new_unchecked(&self.inner as *const [c_char] as *mut [c_char]) }
514            .as_non_null_ptr()
515    }
516
517    /// Returns the length of `self`. Like C's `strlen`, this does not include the nul terminator.
518    ///
519    /// > **Note**: This method is currently implemented as a constant-time
520    /// > cast, but it is planned to alter its definition in the future to
521    /// > perform the length calculation whenever this method is called.
522    ///
523    /// # Examples
524    ///
525    /// ```
526    /// assert_eq!(c"foo".count_bytes(), 3);
527    /// assert_eq!(c"".count_bytes(), 0);
528    /// ```
529    #[cfg(not(feature = "ferrocene_subset"))]
530    #[inline]
531    #[must_use]
532    #[doc(alias("len", "strlen"))]
533    #[stable(feature = "cstr_count_bytes", since = "1.79.0")]
534    #[rustc_const_stable(feature = "const_cstr_from_ptr", since = "1.81.0")]
535    pub const fn count_bytes(&self) -> usize {
536        self.inner.len() - 1
537    }
538
539    /// Returns `true` if `self.to_bytes()` has a length of 0.
540    ///
541    /// # Examples
542    ///
543    /// ```
544    /// assert!(!c"foo".is_empty());
545    /// assert!(c"".is_empty());
546    /// ```
547    #[cfg(not(feature = "ferrocene_subset"))]
548    #[inline]
549    #[stable(feature = "cstr_is_empty", since = "1.71.0")]
550    #[rustc_const_stable(feature = "cstr_is_empty", since = "1.71.0")]
551    pub const fn is_empty(&self) -> bool {
552        // SAFETY: We know there is at least one byte; for empty strings it
553        // is the NUL terminator.
554        // FIXME(const-hack): use get_unchecked
555        unsafe { *self.inner.as_ptr() == 0 }
556    }
557
558    /// Converts this C string to a byte slice.
559    ///
560    /// The returned slice will **not** contain the trailing nul terminator that this C
561    /// string has.
562    ///
563    /// > **Note**: This method is currently implemented as a constant-time
564    /// > cast, but it is planned to alter its definition in the future to
565    /// > perform the length calculation whenever this method is called.
566    ///
567    /// # Examples
568    ///
569    /// ```
570    /// assert_eq!(c"foo".to_bytes(), b"foo");
571    /// ```
572    #[cfg(not(feature = "ferrocene_subset"))]
573    #[inline]
574    #[must_use = "this returns the result of the operation, \
575                  without modifying the original"]
576    #[stable(feature = "rust1", since = "1.0.0")]
577    #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")]
578    pub const fn to_bytes(&self) -> &[u8] {
579        let bytes = self.to_bytes_with_nul();
580        // FIXME(const-hack) replace with range index
581        // SAFETY: to_bytes_with_nul returns slice with length at least 1
582        unsafe { slice::from_raw_parts(bytes.as_ptr(), bytes.len() - 1) }
583    }
584
585    /// Converts this C string to a byte slice containing the trailing 0 byte.
586    ///
587    /// This function is the equivalent of [`CStr::to_bytes`] except that it
588    /// will retain the trailing nul terminator instead of chopping it off.
589    ///
590    /// > **Note**: This method is currently implemented as a 0-cost cast, but
591    /// > it is planned to alter its definition in the future to perform the
592    /// > length calculation whenever this method is called.
593    ///
594    /// # Examples
595    ///
596    /// ```
597    /// assert_eq!(c"foo".to_bytes_with_nul(), b"foo\0");
598    /// ```
599    #[inline]
600    #[must_use = "this returns the result of the operation, \
601                  without modifying the original"]
602    #[stable(feature = "rust1", since = "1.0.0")]
603    #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")]
604    pub const fn to_bytes_with_nul(&self) -> &[u8] {
605        // SAFETY: Transmuting a slice of `c_char`s to a slice of `u8`s
606        // is safe on all supported targets.
607        unsafe { &*((&raw const self.inner) as *const [u8]) }
608    }
609
610    /// Iterates over the bytes in this C string.
611    ///
612    /// The returned iterator will **not** contain the trailing nul terminator
613    /// that this C string has.
614    ///
615    /// # Examples
616    ///
617    /// ```
618    /// #![feature(cstr_bytes)]
619    ///
620    /// assert!(c"foo".bytes().eq(*b"foo"));
621    /// ```
622    #[cfg(not(feature = "ferrocene_subset"))]
623    #[inline]
624    #[unstable(feature = "cstr_bytes", issue = "112115")]
625    pub fn bytes(&self) -> Bytes<'_> {
626        Bytes::new(self)
627    }
628
629    /// Yields a <code>&[str]</code> slice if the `CStr` contains valid UTF-8.
630    ///
631    /// If the contents of the `CStr` are valid UTF-8 data, this
632    /// function will return the corresponding <code>&[str]</code> slice. Otherwise,
633    /// it will return an error with details of where UTF-8 validation failed.
634    ///
635    /// [str]: prim@str "str"
636    ///
637    /// # Examples
638    ///
639    /// ```
640    /// assert_eq!(c"foo".to_str(), Ok("foo"));
641    /// ```
642    #[cfg(not(feature = "ferrocene_subset"))]
643    #[stable(feature = "cstr_to_str", since = "1.4.0")]
644    #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")]
645    pub const fn to_str(&self) -> Result<&str, str::Utf8Error> {
646        // N.B., when `CStr` is changed to perform the length check in `.to_bytes()`
647        // instead of in `from_ptr()`, it may be worth considering if this should
648        // be rewritten to do the UTF-8 check inline with the length calculation
649        // instead of doing it afterwards.
650        str::from_utf8(self.to_bytes())
651    }
652
653    /// Returns an object that implements [`Display`] for safely printing a [`CStr`] that may
654    /// contain non-Unicode data.
655    ///
656    /// Behaves as if `self` were first lossily converted to a `str`, with invalid UTF-8 presented
657    /// as the Unicode replacement character: �.
658    ///
659    /// [`Display`]: fmt::Display
660    ///
661    /// # Examples
662    ///
663    /// ```
664    /// #![feature(cstr_display)]
665    ///
666    /// let cstr = c"Hello, world!";
667    /// println!("{}", cstr.display());
668    /// ```
669    #[cfg(not(feature = "ferrocene_subset"))]
670    #[unstable(feature = "cstr_display", issue = "139984")]
671    #[must_use = "this does not display the `CStr`; \
672                  it returns an object that can be displayed"]
673    #[inline]
674    pub fn display(&self) -> impl fmt::Display {
675        crate::bstr::ByteStr::from_bytes(self.to_bytes())
676    }
677}
678
679#[cfg(not(feature = "ferrocene_subset"))]
680#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
681impl PartialEq<&Self> for CStr {
682    #[inline]
683    fn eq(&self, other: &&Self) -> bool {
684        *self == **other
685    }
686
687    #[inline]
688    fn ne(&self, other: &&Self) -> bool {
689        *self != **other
690    }
691}
692
693// `.to_bytes()` representations are compared instead of the inner `[c_char]`s,
694// because `c_char` is `i8` (not `u8`) on some platforms.
695// That is why this is implemented manually and not derived.
696#[cfg(not(feature = "ferrocene_subset"))]
697#[stable(feature = "rust1", since = "1.0.0")]
698impl PartialOrd for CStr {
699    #[inline]
700    fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
701        self.to_bytes().partial_cmp(&other.to_bytes())
702    }
703}
704
705#[cfg(not(feature = "ferrocene_subset"))]
706#[stable(feature = "rust1", since = "1.0.0")]
707impl Ord for CStr {
708    #[inline]
709    fn cmp(&self, other: &CStr) -> Ordering {
710        self.to_bytes().cmp(&other.to_bytes())
711    }
712}
713
714#[cfg(not(feature = "ferrocene_subset"))]
715#[stable(feature = "cstr_range_from", since = "1.47.0")]
716impl ops::Index<ops::RangeFrom<usize>> for CStr {
717    type Output = CStr;
718
719    #[inline]
720    fn index(&self, index: ops::RangeFrom<usize>) -> &CStr {
721        let bytes = self.to_bytes_with_nul();
722        // we need to manually check the starting index to account for the null
723        // byte, since otherwise we could get an empty string that doesn't end
724        // in a null.
725        if index.start < bytes.len() {
726            // SAFETY: Non-empty tail of a valid `CStr` is still a valid `CStr`.
727            unsafe { CStr::from_bytes_with_nul_unchecked(&bytes[index.start..]) }
728        } else {
729            panic!(
730                "index out of bounds: the len is {} but the index is {}",
731                bytes.len(),
732                index.start
733            );
734        }
735    }
736}
737
738#[cfg(not(feature = "ferrocene_subset"))]
739#[stable(feature = "cstring_asref", since = "1.7.0")]
740#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
741impl const AsRef<CStr> for CStr {
742    #[inline]
743    fn as_ref(&self) -> &CStr {
744        self
745    }
746}
747
748/// Calculate the length of a nul-terminated string. Defers to C's `strlen` when possible.
749///
750/// # Safety
751///
752/// The pointer must point to a valid buffer that contains a NUL terminator. The NUL must be
753/// located within `isize::MAX` from `ptr`.
754#[inline]
755#[unstable(feature = "cstr_internals", issue = "none")]
756#[rustc_allow_const_fn_unstable(const_eval_select)]
757const unsafe fn strlen(ptr: *const c_char) -> usize {
758    const_eval_select!(
759        @capture { s: *const c_char = ptr } -> usize:
760        if const {
761            let mut len = 0;
762
763            // SAFETY: Outer caller has provided a pointer to a valid C string.
764            while unsafe { *s.add(len) } != 0 {
765                len += 1;
766            }
767
768            len
769        } else {
770            unsafe extern "C" {
771                /// Provided by libc or compiler_builtins.
772                fn strlen(s: *const c_char) -> usize;
773            }
774
775            // SAFETY: Outer caller has provided a pointer to a valid C string.
776            unsafe { strlen(s) }
777        }
778    )
779}
780
781/// An iterator over the bytes of a [`CStr`], without the nul terminator.
782///
783/// This struct is created by the [`bytes`] method on [`CStr`].
784/// See its documentation for more.
785///
786/// [`bytes`]: CStr::bytes
787#[cfg(not(feature = "ferrocene_subset"))]
788#[must_use = "iterators are lazy and do nothing unless consumed"]
789#[unstable(feature = "cstr_bytes", issue = "112115")]
790#[derive(Clone, Debug)]
791pub struct Bytes<'a> {
792    // since we know the string is nul-terminated, we only need one pointer
793    ptr: NonNull<u8>,
794    phantom: PhantomData<&'a [c_char]>,
795}
796
797#[cfg(not(feature = "ferrocene_subset"))]
798#[unstable(feature = "cstr_bytes", issue = "112115")]
799unsafe impl Send for Bytes<'_> {}
800
801#[cfg(not(feature = "ferrocene_subset"))]
802#[unstable(feature = "cstr_bytes", issue = "112115")]
803unsafe impl Sync for Bytes<'_> {}
804
805#[cfg(not(feature = "ferrocene_subset"))]
806impl<'a> Bytes<'a> {
807    #[inline]
808    fn new(s: &'a CStr) -> Self {
809        Self { ptr: s.as_non_null_ptr().cast(), phantom: PhantomData }
810    }
811
812    #[inline]
813    fn is_empty(&self) -> bool {
814        // SAFETY: We uphold that the pointer is always valid to dereference
815        // by starting with a valid C string and then never incrementing beyond
816        // the nul terminator.
817        unsafe { self.ptr.read() == 0 }
818    }
819}
820
821#[cfg(not(feature = "ferrocene_subset"))]
822#[unstable(feature = "cstr_bytes", issue = "112115")]
823impl Iterator for Bytes<'_> {
824    type Item = u8;
825
826    #[inline]
827    fn next(&mut self) -> Option<u8> {
828        // SAFETY: We only choose a pointer from a valid C string, which must
829        // be non-null and contain at least one value. Since we always stop at
830        // the nul terminator, which is guaranteed to exist, we can assume that
831        // the pointer is non-null and valid. This lets us safely dereference
832        // it and assume that adding 1 will create a new, non-null, valid
833        // pointer.
834        unsafe {
835            let ret = self.ptr.read();
836            if ret == 0 {
837                None
838            } else {
839                self.ptr = self.ptr.add(1);
840                Some(ret)
841            }
842        }
843    }
844
845    #[inline]
846    fn size_hint(&self) -> (usize, Option<usize>) {
847        if self.is_empty() { (0, Some(0)) } else { (1, None) }
848    }
849
850    #[inline]
851    fn count(self) -> usize {
852        // SAFETY: We always hold a valid pointer to a C string
853        unsafe { strlen(self.ptr.as_ptr().cast()) }
854    }
855}
856
857#[cfg(not(feature = "ferrocene_subset"))]
858#[unstable(feature = "cstr_bytes", issue = "112115")]
859impl FusedIterator for Bytes<'_> {}