Skip to main content

core/ffi/
c_str.rs

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