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