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