Skip to main content

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::{fmt, 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#[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#[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#[stable(feature = "cstr_debug", since = "1.3.0")]
187impl fmt::Debug for CStr {
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        fmt::Debug::fmt(crate::bstr::ByteStr::from_bytes(self.to_bytes()), f)
190    }
191}
192
193#[cfg(not(feature = "ferrocene_subset"))]
194#[stable(feature = "cstr_default", since = "1.10.0")]
195impl Default for &CStr {
196    #[inline]
197    fn default() -> Self {
198        c""
199    }
200}
201
202impl CStr {
203    /// Wraps a raw C string with a safe C string wrapper.
204    ///
205    /// This function will wrap the provided `ptr` with a `CStr` wrapper, which
206    /// allows inspection and interoperation of non-owned C strings. The total
207    /// size of the terminated buffer must be smaller than [`isize::MAX`] **bytes**
208    /// in memory (a restriction from [`slice::from_raw_parts`]).
209    ///
210    /// # Safety
211    ///
212    /// * The memory pointed to by `ptr` must contain a valid nul terminator at the
213    ///   end of the string.
214    ///
215    /// * `ptr` must be [valid] for reads of bytes up to and including the nul terminator.
216    ///   This means in particular:
217    ///
218    ///     * The entire memory range of this `CStr` must be contained within a single allocation!
219    ///     * `ptr` must be non-null even for a zero-length cstr.
220    ///
221    /// * The memory referenced by the returned `CStr` must not be mutated for
222    ///   the duration of lifetime `'a`.
223    ///
224    /// * The nul terminator must be within `isize::MAX` from `ptr`
225    ///
226    /// > **Note**: This operation is intended to be a 0-cost cast but it is
227    /// > currently implemented with an up-front calculation of the length of
228    /// > the string. This is not guaranteed to always be the case.
229    ///
230    /// # Caveat
231    ///
232    /// The lifetime for the returned slice is inferred from its usage. To prevent accidental misuse,
233    /// it's suggested to tie the lifetime to whichever source lifetime is safe in the context,
234    /// such as by providing a helper function taking the lifetime of a host value for the slice,
235    /// or by explicit annotation.
236    ///
237    /// # Examples
238    ///
239    /// ```
240    /// use std::ffi::{c_char, CStr};
241    ///
242    /// fn my_string() -> *const c_char {
243    ///     c"hello".as_ptr()
244    /// }
245    ///
246    /// unsafe {
247    ///     let slice = CStr::from_ptr(my_string());
248    ///     assert_eq!(slice.to_str().unwrap(), "hello");
249    /// }
250    /// ```
251    ///
252    /// ```
253    /// use std::ffi::{c_char, CStr};
254    ///
255    /// const HELLO_PTR: *const c_char = {
256    ///     const BYTES: &[u8] = b"Hello, world!\0";
257    ///     BYTES.as_ptr().cast()
258    /// };
259    /// const HELLO: &CStr = unsafe { CStr::from_ptr(HELLO_PTR) };
260    ///
261    /// assert_eq!(c"Hello, world!", HELLO);
262    /// ```
263    ///
264    /// [valid]: core::ptr#safety
265    #[inline] // inline is necessary for codegen to see strlen.
266    #[must_use]
267    #[stable(feature = "rust1", since = "1.0.0")]
268    #[rustc_const_stable(feature = "const_cstr_from_ptr", since = "1.81.0")]
269    pub const unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
270        // SAFETY: The caller has provided a pointer that points to a valid C
271        // string with a NUL terminator less than `isize::MAX` from `ptr`.
272        let len = unsafe { strlen(ptr) };
273
274        // SAFETY: The caller has provided a valid pointer with length less than
275        // `isize::MAX`, so `from_raw_parts` is safe. The content remains valid
276        // and doesn't change for the lifetime of the returned `CStr`. This
277        // means the call to `from_bytes_with_nul_unchecked` is correct.
278        //
279        // The cast from c_char to u8 is ok because a c_char is always one byte.
280        unsafe { Self::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr.cast(), len + 1)) }
281    }
282
283    /// Creates a C string wrapper from a byte slice with any number of nuls.
284    ///
285    /// This method will create a `CStr` from any byte slice that contains at
286    /// least one nul byte. Unlike with [`CStr::from_bytes_with_nul`], the caller
287    /// does not need to know where the nul byte is located.
288    ///
289    /// If the first byte is a nul character, this method will return an
290    /// empty `CStr`. If multiple nul characters are present, the `CStr` will
291    /// end at the first one.
292    ///
293    /// If the slice only has a single nul byte at the end, this method is
294    /// equivalent to [`CStr::from_bytes_with_nul`].
295    ///
296    /// # Examples
297    /// ```
298    /// use std::ffi::CStr;
299    ///
300    /// let mut buffer = [0u8; 16];
301    /// unsafe {
302    ///     // Here we might call an unsafe C function that writes a string
303    ///     // into the buffer.
304    ///     let buf_ptr = buffer.as_mut_ptr();
305    ///     buf_ptr.write_bytes(b'A', 8);
306    /// }
307    /// // Attempt to extract a C nul-terminated string from the buffer.
308    /// let c_str = CStr::from_bytes_until_nul(&buffer[..]).unwrap();
309    /// assert_eq!(c_str.to_str().unwrap(), "AAAAAAAA");
310    /// ```
311    ///
312    #[cfg(not(feature = "ferrocene_subset"))]
313    #[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
314    #[rustc_const_stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
315    pub const fn from_bytes_until_nul(bytes: &[u8]) -> Result<&CStr, FromBytesUntilNulError> {
316        let nul_pos = memchr::memchr(0, bytes);
317        match nul_pos {
318            Some(nul_pos) => {
319                // FIXME(const-hack) replace with range index
320                // SAFETY: nul_pos + 1 <= bytes.len()
321                let subslice = unsafe { crate::slice::from_raw_parts(bytes.as_ptr(), nul_pos + 1) };
322                // SAFETY: We know there is a nul byte at nul_pos, so this slice
323                // (ending at the nul byte) is a well-formed C string.
324                Ok(unsafe { CStr::from_bytes_with_nul_unchecked(subslice) })
325            }
326            None => Err(FromBytesUntilNulError(())),
327        }
328    }
329
330    /// Creates a C string wrapper from a byte slice with exactly one nul
331    /// terminator.
332    ///
333    /// This function will cast the provided `bytes` to a `CStr`
334    /// wrapper after ensuring that the byte slice is nul-terminated
335    /// and does not contain any interior nul bytes.
336    ///
337    /// If the nul byte may not be at the end,
338    /// [`CStr::from_bytes_until_nul`] can be used instead.
339    ///
340    /// # Examples
341    ///
342    /// ```
343    /// use std::ffi::CStr;
344    ///
345    /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
346    /// assert_eq!(cstr, Ok(c"hello"));
347    /// ```
348    ///
349    /// Creating a `CStr` without a trailing nul terminator is an error:
350    ///
351    /// ```
352    /// use std::ffi::{CStr, FromBytesWithNulError};
353    ///
354    /// let cstr = CStr::from_bytes_with_nul(b"hello");
355    /// assert_eq!(cstr, Err(FromBytesWithNulError::NotNulTerminated));
356    /// ```
357    ///
358    /// Creating a `CStr` with an interior nul byte is an error:
359    ///
360    /// ```
361    /// use std::ffi::{CStr, FromBytesWithNulError};
362    ///
363    /// let cstr = CStr::from_bytes_with_nul(b"he\0llo\0");
364    /// assert_eq!(cstr, Err(FromBytesWithNulError::InteriorNul { position: 2 }));
365    /// ```
366    #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
367    #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")]
368    pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, FromBytesWithNulError> {
369        let nul_pos = memchr::memchr(0, bytes);
370        match nul_pos {
371            Some(nul_pos) if nul_pos + 1 == bytes.len() => {
372                // SAFETY: We know there is only one nul byte, at the end
373                // of the byte slice.
374                Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) })
375            }
376            Some(position) => Err(FromBytesWithNulError::InteriorNul { position }),
377            None => Err(FromBytesWithNulError::NotNulTerminated),
378        }
379    }
380
381    /// Unsafely creates a C string wrapper from a byte slice.
382    ///
383    /// This function will cast the provided `bytes` to a `CStr` wrapper without
384    /// performing any sanity checks.
385    ///
386    /// # Safety
387    /// The provided slice **must** be nul-terminated and not contain any interior
388    /// nul bytes.
389    ///
390    /// # Examples
391    ///
392    /// ```
393    /// use std::ffi::CStr;
394    ///
395    /// let bytes = b"Hello world!\0";
396    ///
397    /// let cstr = unsafe { CStr::from_bytes_with_nul_unchecked(bytes) };
398    /// assert_eq!(cstr.to_bytes_with_nul(), bytes);
399    /// ```
400    #[inline]
401    #[must_use]
402    #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
403    #[rustc_const_stable(feature = "const_cstr_unchecked", since = "1.59.0")]
404    #[rustc_allow_const_fn_unstable(const_eval_select)]
405    pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
406        const_eval_select!(
407            @capture { bytes: &[u8] } -> &CStr:
408            if const {
409                // Saturating so that an empty slice panics in the assert with a good
410                // message, not here due to underflow.
411                let mut i = bytes.len().saturating_sub(1);
412                assert!(!bytes.is_empty() && bytes[i] == 0, "input was not nul-terminated");
413
414                // Ending nul byte exists, skip to the rest.
415                while i != 0 {
416                    i -= 1;
417                    let byte = bytes[i];
418                    assert!(byte != 0, "input contained interior nul");
419                }
420
421                // SAFETY: See runtime cast comment below.
422                unsafe { &*(bytes as *const [u8] as *const CStr) }
423            } else {
424                // Chance at catching some UB at runtime with debug builds.
425                debug_assert!(!bytes.is_empty() && bytes[bytes.len() - 1] == 0);
426
427                // SAFETY: Casting to CStr is safe because its internal representation
428                // is a [u8] too (safe only inside std).
429                // Dereferencing the obtained pointer is safe because it comes from a
430                // reference. Making a reference is then safe because its lifetime
431                // is bound by the lifetime of the given `bytes`.
432                unsafe { &*(bytes as *const [u8] as *const CStr) }
433            }
434        )
435    }
436
437    /// Returns the inner pointer to this C string.
438    ///
439    /// The returned pointer will be valid for as long as `self` is, and points
440    /// to a contiguous region of memory terminated with a 0 byte to represent
441    /// the end of the string.
442    ///
443    /// The type of the returned pointer is
444    /// [`*const c_char`][crate::ffi::c_char], and whether it's
445    /// an alias for `*const i8` or `*const u8` is platform-specific.
446    ///
447    /// **WARNING**
448    ///
449    /// The returned pointer is read-only; writing to it (including passing it
450    /// to C code that writes to it) causes undefined behavior.
451    ///
452    /// It is your responsibility to make sure that the underlying memory is not
453    /// freed too early. For example, the following code will cause undefined
454    /// behavior when `ptr` is used inside the `unsafe` block:
455    ///
456    /// ```no_run
457    /// # #![expect(dangling_pointers_from_temporaries)]
458    /// use std::ffi::{CStr, CString};
459    ///
460    /// // 💀 The meaning of this entire program is undefined,
461    /// // 💀 and nothing about its behavior is guaranteed,
462    /// // 💀 not even that its behavior resembles the code as written,
463    /// // 💀 just because it contains a single instance of undefined behavior!
464    ///
465    /// // 🚨 creates a dangling pointer to a temporary `CString`
466    /// // 🚨 that is deallocated at the end of the statement
467    /// let ptr = CString::new("Hi!".to_uppercase()).unwrap().as_ptr();
468    ///
469    /// // without undefined behavior, you would expect that `ptr` equals:
470    /// dbg!(CStr::from_bytes_with_nul(b"HI!\0").unwrap());
471    ///
472    /// // 🙏 Possibly the program behaved as expected so far,
473    /// // 🙏 and this just shows `ptr` is now garbage..., but
474    /// // 💀 this violates `CStr::from_ptr`'s safety contract
475    /// // 💀 leading to a dereference of a dangling pointer,
476    /// // 💀 which is immediate undefined behavior.
477    /// // 💀 *BOOM*, you're dead, your entire program has no meaning.
478    /// dbg!(unsafe { CStr::from_ptr(ptr) });
479    /// ```
480    ///
481    /// This happens because, the pointer returned by `as_ptr` does not carry any
482    /// lifetime information, and the `CString` is deallocated immediately after
483    /// the expression that it is part of has been evaluated.
484    /// To fix the problem, bind the `CString` to a local variable:
485    ///
486    /// ```
487    /// use std::ffi::{CStr, CString};
488    ///
489    /// let c_str = CString::new("Hi!".to_uppercase()).unwrap();
490    /// let ptr = c_str.as_ptr();
491    ///
492    /// assert_eq!(unsafe { CStr::from_ptr(ptr) }, c"HI!");
493    /// ```
494    #[cfg(not(feature = "ferrocene_subset"))]
495    #[inline]
496    #[must_use]
497    #[stable(feature = "rust1", since = "1.0.0")]
498    #[rustc_const_stable(feature = "const_str_as_ptr", since = "1.32.0")]
499    #[rustc_as_ptr]
500    #[rustc_never_returns_null_ptr]
501    pub const fn as_ptr(&self) -> *const c_char {
502        self.inner.as_ptr()
503    }
504
505    /// We could eventually expose this publicly, if we wanted.
506    #[cfg(not(feature = "ferrocene_subset"))]
507    #[inline]
508    #[must_use]
509    const fn as_non_null_ptr(&self) -> NonNull<c_char> {
510        // FIXME(const_trait_impl) replace with `NonNull::from`
511        // SAFETY: a reference is never null
512        unsafe { NonNull::new_unchecked(&self.inner as *const [c_char] as *mut [c_char]) }
513            .as_non_null_ptr()
514    }
515
516    /// Returns the length of `self`. Like C's `strlen`, this does not include the nul terminator.
517    ///
518    /// > **Note**: This method is currently implemented as a constant-time
519    /// > cast, but it is planned to alter its definition in the future to
520    /// > perform the length calculation whenever this method is called.
521    ///
522    /// # Examples
523    ///
524    /// ```
525    /// assert_eq!(c"foo".count_bytes(), 3);
526    /// assert_eq!(c"".count_bytes(), 0);
527    /// ```
528    #[cfg(not(feature = "ferrocene_subset"))]
529    #[inline]
530    #[must_use]
531    #[doc(alias("len", "strlen"))]
532    #[stable(feature = "cstr_count_bytes", since = "1.79.0")]
533    #[rustc_const_stable(feature = "const_cstr_from_ptr", since = "1.81.0")]
534    pub const fn count_bytes(&self) -> usize {
535        self.inner.len() - 1
536    }
537
538    /// Returns `true` if `self.to_bytes()` has a length of 0.
539    ///
540    /// # Examples
541    ///
542    /// ```
543    /// assert!(!c"foo".is_empty());
544    /// assert!(c"".is_empty());
545    /// ```
546    #[cfg(not(feature = "ferrocene_subset"))]
547    #[inline]
548    #[stable(feature = "cstr_is_empty", since = "1.71.0")]
549    #[rustc_const_stable(feature = "cstr_is_empty", since = "1.71.0")]
550    pub const fn is_empty(&self) -> bool {
551        // SAFETY: We know there is at least one byte; for empty strings it
552        // is the NUL terminator.
553        // FIXME(const-hack): use get_unchecked
554        unsafe { *self.inner.as_ptr() == 0 }
555    }
556
557    /// Converts this C string to a byte slice.
558    ///
559    /// The returned slice will **not** contain the trailing nul terminator that this C
560    /// string has.
561    ///
562    /// > **Note**: This method is currently implemented as a constant-time
563    /// > cast, but it is planned to alter its definition in the future to
564    /// > perform the length calculation whenever this method is called.
565    ///
566    /// # Examples
567    ///
568    /// ```
569    /// assert_eq!(c"foo".to_bytes(), b"foo");
570    /// ```
571    #[inline]
572    #[must_use = "this returns the result of the operation, \
573                  without modifying the original"]
574    #[stable(feature = "rust1", since = "1.0.0")]
575    #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")]
576    pub const fn to_bytes(&self) -> &[u8] {
577        let bytes = self.to_bytes_with_nul();
578        // FIXME(const-hack) replace with range index
579        // SAFETY: to_bytes_with_nul returns slice with length at least 1
580        unsafe { slice::from_raw_parts(bytes.as_ptr(), bytes.len() - 1) }
581    }
582
583    /// Converts this C string to a byte slice containing the trailing 0 byte.
584    ///
585    /// This function is the equivalent of [`CStr::to_bytes`] except that it
586    /// will retain the trailing nul terminator instead of chopping it off.
587    ///
588    /// > **Note**: This method is currently implemented as a 0-cost cast, but
589    /// > it is planned to alter its definition in the future to perform the
590    /// > length calculation whenever this method is called.
591    ///
592    /// # Examples
593    ///
594    /// ```
595    /// assert_eq!(c"foo".to_bytes_with_nul(), b"foo\0");
596    /// ```
597    #[inline]
598    #[must_use = "this returns the result of the operation, \
599                  without modifying the original"]
600    #[stable(feature = "rust1", since = "1.0.0")]
601    #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")]
602    pub const fn to_bytes_with_nul(&self) -> &[u8] {
603        // SAFETY: Transmuting a slice of `c_char`s to a slice of `u8`s
604        // is safe on all supported targets.
605        unsafe { &*((&raw const self.inner) as *const [u8]) }
606    }
607
608    /// Iterates over the bytes in this C string.
609    ///
610    /// The returned iterator will **not** contain the trailing nul terminator
611    /// that this C string has.
612    ///
613    /// # Examples
614    ///
615    /// ```
616    /// #![feature(cstr_bytes)]
617    ///
618    /// assert!(c"foo".bytes().eq(*b"foo"));
619    /// ```
620    #[cfg(not(feature = "ferrocene_subset"))]
621    #[inline]
622    #[unstable(feature = "cstr_bytes", issue = "112115")]
623    pub fn bytes(&self) -> Bytes<'_> {
624        Bytes::new(self)
625    }
626
627    /// Yields a <code>&[str]</code> slice if the `CStr` contains valid UTF-8.
628    ///
629    /// If the contents of the `CStr` are valid UTF-8 data, this
630    /// function will return the corresponding <code>&[str]</code> slice. Otherwise,
631    /// it will return an error with details of where UTF-8 validation failed.
632    ///
633    /// [str]: prim@str "str"
634    ///
635    /// # Examples
636    ///
637    /// ```
638    /// assert_eq!(c"foo".to_str(), Ok("foo"));
639    /// ```
640    #[cfg(not(feature = "ferrocene_subset"))]
641    #[stable(feature = "cstr_to_str", since = "1.4.0")]
642    #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")]
643    pub const fn to_str(&self) -> Result<&str, str::Utf8Error> {
644        // N.B., when `CStr` is changed to perform the length check in `.to_bytes()`
645        // instead of in `from_ptr()`, it may be worth considering if this should
646        // be rewritten to do the UTF-8 check inline with the length calculation
647        // instead of doing it afterwards.
648        str::from_utf8(self.to_bytes())
649    }
650
651    /// Returns an object that implements [`Display`] for safely printing a [`CStr`] that may
652    /// contain non-Unicode data.
653    ///
654    /// Behaves as if `self` were first lossily converted to a `str`, with invalid UTF-8 presented
655    /// as the Unicode replacement character: �.
656    ///
657    /// [`Display`]: fmt::Display
658    ///
659    /// # Examples
660    ///
661    /// ```
662    /// #![feature(cstr_display)]
663    ///
664    /// let cstr = c"Hello, world!";
665    /// println!("{}", cstr.display());
666    /// ```
667    #[cfg(not(feature = "ferrocene_subset"))]
668    #[unstable(feature = "cstr_display", issue = "139984")]
669    #[must_use = "this does not display the `CStr`; \
670                  it returns an object that can be displayed"]
671    #[inline]
672    pub fn display(&self) -> impl fmt::Display {
673        crate::bstr::ByteStr::from_bytes(self.to_bytes())
674    }
675
676    /// Returns the same string as a string slice `&CStr`.
677    ///
678    /// This method is redundant when used directly on `&CStr`, but
679    /// it helps dereferencing other string-like types to string slices,
680    /// for example references to `Box<CStr>` or `Arc<CStr>`.
681    #[cfg(not(feature = "ferrocene_subset"))]
682    #[inline]
683    #[unstable(feature = "str_as_str", issue = "130366")]
684    pub const fn as_c_str(&self) -> &CStr {
685        self
686    }
687}
688
689#[cfg(not(feature = "ferrocene_subset"))]
690#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
691impl PartialEq<&Self> for CStr {
692    #[inline]
693    fn eq(&self, other: &&Self) -> bool {
694        *self == **other
695    }
696
697    #[inline]
698    fn ne(&self, other: &&Self) -> bool {
699        *self != **other
700    }
701}
702
703// `.to_bytes()` representations are compared instead of the inner `[c_char]`s,
704// because `c_char` is `i8` (not `u8`) on some platforms.
705// That is why this is implemented manually and not derived.
706#[cfg(not(feature = "ferrocene_subset"))]
707#[stable(feature = "rust1", since = "1.0.0")]
708impl PartialOrd for CStr {
709    #[inline]
710    fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
711        self.to_bytes().partial_cmp(&other.to_bytes())
712    }
713}
714
715#[cfg(not(feature = "ferrocene_subset"))]
716#[stable(feature = "rust1", since = "1.0.0")]
717impl Ord for CStr {
718    #[inline]
719    fn cmp(&self, other: &CStr) -> Ordering {
720        self.to_bytes().cmp(&other.to_bytes())
721    }
722}
723
724#[cfg(not(feature = "ferrocene_subset"))]
725#[stable(feature = "cstr_range_from", since = "1.47.0")]
726impl ops::Index<ops::RangeFrom<usize>> for CStr {
727    type Output = CStr;
728
729    #[inline]
730    fn index(&self, index: ops::RangeFrom<usize>) -> &CStr {
731        let bytes = self.to_bytes_with_nul();
732        // we need to manually check the starting index to account for the null
733        // byte, since otherwise we could get an empty string that doesn't end
734        // in a null.
735        if index.start < bytes.len() {
736            // SAFETY: Non-empty tail of a valid `CStr` is still a valid `CStr`.
737            unsafe { CStr::from_bytes_with_nul_unchecked(&bytes[index.start..]) }
738        } else {
739            panic!(
740                "index out of bounds: the len is {} but the index is {}",
741                bytes.len(),
742                index.start
743            );
744        }
745    }
746}
747
748#[cfg(not(feature = "ferrocene_subset"))]
749#[stable(feature = "cstring_asref", since = "1.7.0")]
750#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
751impl const AsRef<CStr> for CStr {
752    #[inline]
753    fn as_ref(&self) -> &CStr {
754        self
755    }
756}
757
758/// Calculate the length of a nul-terminated string. Defers to C's `strlen` when possible.
759///
760/// # Safety
761///
762/// The pointer must point to a valid buffer that contains a NUL terminator. The NUL must be
763/// located within `isize::MAX` from `ptr`.
764#[inline]
765#[unstable(feature = "cstr_internals", issue = "none")]
766#[rustc_allow_const_fn_unstable(const_eval_select)]
767const unsafe fn strlen(ptr: *const c_char) -> usize {
768    const_eval_select!(
769        @capture { s: *const c_char = ptr } -> usize:
770        if const {
771            let mut len = 0;
772
773            // SAFETY: Outer caller has provided a pointer to a valid C string.
774            while unsafe { *s.add(len) } != 0 {
775                len += 1;
776            }
777
778            len
779        } else {
780            unsafe extern "C" {
781                /// Provided by libc or compiler_builtins.
782                fn strlen(s: *const c_char) -> usize;
783            }
784
785            // SAFETY: Outer caller has provided a pointer to a valid C string.
786            unsafe { strlen(s) }
787        }
788    )
789}
790
791/// An iterator over the bytes of a [`CStr`], without the nul terminator.
792///
793/// This struct is created by the [`bytes`] method on [`CStr`].
794/// See its documentation for more.
795///
796/// [`bytes`]: CStr::bytes
797#[cfg(not(feature = "ferrocene_subset"))]
798#[must_use = "iterators are lazy and do nothing unless consumed"]
799#[unstable(feature = "cstr_bytes", issue = "112115")]
800#[derive(Clone, Debug)]
801pub struct Bytes<'a> {
802    // since we know the string is nul-terminated, we only need one pointer
803    ptr: NonNull<u8>,
804    phantom: PhantomData<&'a [c_char]>,
805}
806
807#[cfg(not(feature = "ferrocene_subset"))]
808#[unstable(feature = "cstr_bytes", issue = "112115")]
809unsafe impl Send for Bytes<'_> {}
810
811#[cfg(not(feature = "ferrocene_subset"))]
812#[unstable(feature = "cstr_bytes", issue = "112115")]
813unsafe impl Sync for Bytes<'_> {}
814
815#[cfg(not(feature = "ferrocene_subset"))]
816impl<'a> Bytes<'a> {
817    #[inline]
818    fn new(s: &'a CStr) -> Self {
819        Self { ptr: s.as_non_null_ptr().cast(), phantom: PhantomData }
820    }
821
822    #[inline]
823    fn is_empty(&self) -> bool {
824        // SAFETY: We uphold that the pointer is always valid to dereference
825        // by starting with a valid C string and then never incrementing beyond
826        // the nul terminator.
827        unsafe { self.ptr.read() == 0 }
828    }
829}
830
831#[cfg(not(feature = "ferrocene_subset"))]
832#[unstable(feature = "cstr_bytes", issue = "112115")]
833impl Iterator for Bytes<'_> {
834    type Item = u8;
835
836    #[inline]
837    fn next(&mut self) -> Option<u8> {
838        // SAFETY: We only choose a pointer from a valid C string, which must
839        // be non-null and contain at least one value. Since we always stop at
840        // the nul terminator, which is guaranteed to exist, we can assume that
841        // the pointer is non-null and valid. This lets us safely dereference
842        // it and assume that adding 1 will create a new, non-null, valid
843        // pointer.
844        unsafe {
845            let ret = self.ptr.read();
846            if ret == 0 {
847                None
848            } else {
849                self.ptr = self.ptr.add(1);
850                Some(ret)
851            }
852        }
853    }
854
855    #[inline]
856    fn size_hint(&self) -> (usize, Option<usize>) {
857        if self.is_empty() { (0, Some(0)) } else { (1, None) }
858    }
859
860    #[inline]
861    fn count(self) -> usize {
862        // SAFETY: We always hold a valid pointer to a C string
863        unsafe { strlen(self.ptr.as_ptr().cast()) }
864    }
865}
866
867#[cfg(not(feature = "ferrocene_subset"))]
868#[unstable(feature = "cstr_bytes", issue = "112115")]
869impl FusedIterator for Bytes<'_> {}