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, 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/// Representation of a borrowed C string.
19///
20/// This type represents a borrowed reference to a 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 borrowed 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 copy-on-write Cow<'_, str>, then guarantee a freshly-owned String allocation
83///     String::from_utf8_lossy(cstr.to_bytes()).to_string()
84/// }
85///
86/// println!("string: {}", my_string_safe());
87/// ```
88///
89/// [str]: prim@str "str"
90#[derive(PartialEq, Eq, Hash)]
91#[stable(feature = "core_c_str", since = "1.64.0")]
92#[rustc_diagnostic_item = "cstr_type"]
93#[rustc_has_incoherent_inherent_impls]
94#[lang = "CStr"]
95// `fn from` in `impl From<&CStr> for Box<CStr>` current implementation relies
96// on `CStr` being layout-compatible with `[u8]`.
97// However, `CStr` layout is considered an implementation detail and must not be relied upon. We
98// want `repr(transparent)` but we don't want it to show up in rustdoc, so we hide it under
99// `cfg(doc)`. This is an ad-hoc implementation of attribute privacy.
100#[repr(transparent)]
101pub struct CStr {
102    // FIXME: this should not be represented with a DST slice but rather with
103    //        just a raw `c_char` along with some form of marker to make
104    //        this an unsized type. Essentially `sizeof(&CStr)` should be the
105    //        same as `sizeof(&c_char)` but `CStr` should be an unsized type.
106    inner: [c_char],
107}
108
109/// An error indicating that a nul byte was not in the expected position.
110///
111/// The slice used to create a [`CStr`] must have one and only one nul byte,
112/// positioned at the end.
113///
114/// This error is created by the [`CStr::from_bytes_with_nul`] method.
115/// See its documentation for more.
116///
117/// # Examples
118///
119/// ```
120/// use std::ffi::{CStr, FromBytesWithNulError};
121///
122/// let _: FromBytesWithNulError = CStr::from_bytes_with_nul(b"f\0oo").unwrap_err();
123/// ```
124#[derive(Clone, Copy, PartialEq, Eq, Debug)]
125#[stable(feature = "core_c_str", since = "1.64.0")]
126pub enum FromBytesWithNulError {
127    /// Data provided contains an interior nul byte at byte `position`.
128    InteriorNul {
129        /// The position of the interior nul byte.
130        position: usize,
131    },
132    /// Data provided is not nul terminated.
133    NotNulTerminated,
134}
135
136#[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
137impl Error for FromBytesWithNulError {
138    #[allow(deprecated)]
139    fn description(&self) -> &str {
140        match self {
141            Self::InteriorNul { .. } => "data provided contains an interior nul byte",
142            Self::NotNulTerminated => "data provided is not nul terminated",
143        }
144    }
145}
146
147/// An error indicating that no nul byte was present.
148///
149/// A slice used to create a [`CStr`] must contain a nul byte somewhere
150/// within the slice.
151///
152/// This error is created by the [`CStr::from_bytes_until_nul`] method.
153#[derive(Clone, PartialEq, Eq, Debug)]
154#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
155pub struct FromBytesUntilNulError(());
156
157#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
158impl fmt::Display for FromBytesUntilNulError {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        write!(f, "data provided does not contain a nul")
161    }
162}
163
164#[stable(feature = "cstr_debug", since = "1.3.0")]
165impl fmt::Debug for CStr {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        write!(f, "\"{}\"", self.to_bytes().escape_ascii())
168    }
169}
170
171#[stable(feature = "cstr_default", since = "1.10.0")]
172impl Default for &CStr {
173    #[inline]
174    fn default() -> Self {
175        const SLICE: &[c_char] = &[0];
176        // SAFETY: `SLICE` is indeed pointing to a valid nul-terminated string.
177        unsafe { CStr::from_ptr(SLICE.as_ptr()) }
178    }
179}
180
181#[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
182impl fmt::Display for FromBytesWithNulError {
183    #[allow(deprecated, deprecated_in_future)]
184    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185        f.write_str(self.description())?;
186        if let Self::InteriorNul { position } = self {
187            write!(f, " at byte pos {position}")?;
188        }
189        Ok(())
190    }
191}
192
193impl CStr {
194    /// Wraps a raw C string with a safe C string wrapper.
195    ///
196    /// This function will wrap the provided `ptr` with a `CStr` wrapper, which
197    /// allows inspection and interoperation of non-owned C strings. The total
198    /// size of the terminated buffer must be smaller than [`isize::MAX`] **bytes**
199    /// in memory (a restriction from [`slice::from_raw_parts`]).
200    ///
201    /// # Safety
202    ///
203    /// * The memory pointed to by `ptr` must contain a valid nul terminator at the
204    ///   end of the string.
205    ///
206    /// * `ptr` must be [valid] for reads of bytes up to and including the nul terminator.
207    ///   This means in particular:
208    ///
209    ///     * The entire memory range of this `CStr` must be contained within a single allocated object!
210    ///     * `ptr` must be non-null even for a zero-length cstr.
211    ///
212    /// * The memory referenced by the returned `CStr` must not be mutated for
213    ///   the duration of lifetime `'a`.
214    ///
215    /// * The nul terminator must be within `isize::MAX` from `ptr`
216    ///
217    /// > **Note**: This operation is intended to be a 0-cost cast but it is
218    /// > currently implemented with an up-front calculation of the length of
219    /// > the string. This is not guaranteed to always be the case.
220    ///
221    /// # Caveat
222    ///
223    /// The lifetime for the returned slice is inferred from its usage. To prevent accidental misuse,
224    /// it's suggested to tie the lifetime to whichever source lifetime is safe in the context,
225    /// such as by providing a helper function taking the lifetime of a host value for the slice,
226    /// or by explicit annotation.
227    ///
228    /// # Examples
229    ///
230    /// ```
231    /// use std::ffi::{c_char, CStr};
232    ///
233    /// fn my_string() -> *const c_char {
234    ///     c"hello".as_ptr()
235    /// }
236    ///
237    /// unsafe {
238    ///     let slice = CStr::from_ptr(my_string());
239    ///     assert_eq!(slice.to_str().unwrap(), "hello");
240    /// }
241    /// ```
242    ///
243    /// ```
244    /// use std::ffi::{c_char, CStr};
245    ///
246    /// const HELLO_PTR: *const c_char = {
247    ///     const BYTES: &[u8] = b"Hello, world!\0";
248    ///     BYTES.as_ptr().cast()
249    /// };
250    /// const HELLO: &CStr = unsafe { CStr::from_ptr(HELLO_PTR) };
251    ///
252    /// assert_eq!(c"Hello, world!", HELLO);
253    /// ```
254    ///
255    /// [valid]: core::ptr#safety
256    #[inline] // inline is necessary for codegen to see strlen.
257    #[must_use]
258    #[stable(feature = "rust1", since = "1.0.0")]
259    #[rustc_const_stable(feature = "const_cstr_from_ptr", since = "1.81.0")]
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 { Self::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr.cast(), len + 1)) }
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, you're 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    /// use std::ffi::CStr;
514    ///
515    /// let cstr = CStr::from_bytes_with_nul(b"foo\0").unwrap();
516    /// assert_eq!(cstr.count_bytes(), 3);
517    ///
518    /// let cstr = CStr::from_bytes_with_nul(b"\0").unwrap();
519    /// assert_eq!(cstr.count_bytes(), 0);
520    /// ```
521    #[inline]
522    #[must_use]
523    #[doc(alias("len", "strlen"))]
524    #[stable(feature = "cstr_count_bytes", since = "1.79.0")]
525    #[rustc_const_stable(feature = "const_cstr_from_ptr", since = "1.81.0")]
526    pub const fn count_bytes(&self) -> usize {
527        self.inner.len() - 1
528    }
529
530    /// Returns `true` if `self.to_bytes()` has a length of 0.
531    ///
532    /// # Examples
533    ///
534    /// ```
535    /// use std::ffi::CStr;
536    /// # use std::ffi::FromBytesWithNulError;
537    ///
538    /// # fn main() { test().unwrap(); }
539    /// # fn test() -> Result<(), FromBytesWithNulError> {
540    /// let cstr = CStr::from_bytes_with_nul(b"foo\0")?;
541    /// assert!(!cstr.is_empty());
542    ///
543    /// let empty_cstr = CStr::from_bytes_with_nul(b"\0")?;
544    /// assert!(empty_cstr.is_empty());
545    /// assert!(c"".is_empty());
546    /// # Ok(())
547    /// # }
548    /// ```
549    #[inline]
550    #[stable(feature = "cstr_is_empty", since = "1.71.0")]
551    #[rustc_const_stable(feature = "cstr_is_empty", since = "1.71.0")]
552    pub const fn is_empty(&self) -> bool {
553        // SAFETY: We know there is at least one byte; for empty strings it
554        // is the NUL terminator.
555        // FIXME(const-hack): use get_unchecked
556        unsafe { *self.inner.as_ptr() == 0 }
557    }
558
559    /// Converts this C string to a byte slice.
560    ///
561    /// The returned slice will **not** contain the trailing nul terminator that this C
562    /// string has.
563    ///
564    /// > **Note**: This method is currently implemented as a constant-time
565    /// > cast, but it is planned to alter its definition in the future to
566    /// > perform the length calculation whenever this method is called.
567    ///
568    /// # Examples
569    ///
570    /// ```
571    /// use std::ffi::CStr;
572    ///
573    /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
574    /// assert_eq!(cstr.to_bytes(), b"foo");
575    /// ```
576    #[inline]
577    #[must_use = "this returns the result of the operation, \
578                  without modifying the original"]
579    #[stable(feature = "rust1", since = "1.0.0")]
580    #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")]
581    pub const fn to_bytes(&self) -> &[u8] {
582        let bytes = self.to_bytes_with_nul();
583        // FIXME(const-hack) replace with range index
584        // SAFETY: to_bytes_with_nul returns slice with length at least 1
585        unsafe { slice::from_raw_parts(bytes.as_ptr(), bytes.len() - 1) }
586    }
587
588    /// Converts this C string to a byte slice containing the trailing 0 byte.
589    ///
590    /// This function is the equivalent of [`CStr::to_bytes`] except that it
591    /// will retain the trailing nul terminator instead of chopping it off.
592    ///
593    /// > **Note**: This method is currently implemented as a 0-cost cast, but
594    /// > it is planned to alter its definition in the future to perform the
595    /// > length calculation whenever this method is called.
596    ///
597    /// # Examples
598    ///
599    /// ```
600    /// use std::ffi::CStr;
601    ///
602    /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
603    /// assert_eq!(cstr.to_bytes_with_nul(), b"foo\0");
604    /// ```
605    #[inline]
606    #[must_use = "this returns the result of the operation, \
607                  without modifying the original"]
608    #[stable(feature = "rust1", since = "1.0.0")]
609    #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")]
610    pub const fn to_bytes_with_nul(&self) -> &[u8] {
611        // SAFETY: Transmuting a slice of `c_char`s to a slice of `u8`s
612        // is safe on all supported targets.
613        unsafe { &*((&raw const self.inner) as *const [u8]) }
614    }
615
616    /// Iterates over the bytes in this C string.
617    ///
618    /// The returned iterator will **not** contain the trailing nul terminator
619    /// that this C string has.
620    ///
621    /// # Examples
622    ///
623    /// ```
624    /// #![feature(cstr_bytes)]
625    /// use std::ffi::CStr;
626    ///
627    /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
628    /// assert!(cstr.bytes().eq(*b"foo"));
629    /// ```
630    #[inline]
631    #[unstable(feature = "cstr_bytes", issue = "112115")]
632    pub fn bytes(&self) -> Bytes<'_> {
633        Bytes::new(self)
634    }
635
636    /// Yields a <code>&[str]</code> slice if the `CStr` contains valid UTF-8.
637    ///
638    /// If the contents of the `CStr` are valid UTF-8 data, this
639    /// function will return the corresponding <code>&[str]</code> slice. Otherwise,
640    /// it will return an error with details of where UTF-8 validation failed.
641    ///
642    /// [str]: prim@str "str"
643    ///
644    /// # Examples
645    ///
646    /// ```
647    /// use std::ffi::CStr;
648    ///
649    /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
650    /// assert_eq!(cstr.to_str(), Ok("foo"));
651    /// ```
652    #[stable(feature = "cstr_to_str", since = "1.4.0")]
653    #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")]
654    pub const fn to_str(&self) -> Result<&str, str::Utf8Error> {
655        // N.B., when `CStr` is changed to perform the length check in `.to_bytes()`
656        // instead of in `from_ptr()`, it may be worth considering if this should
657        // be rewritten to do the UTF-8 check inline with the length calculation
658        // instead of doing it afterwards.
659        str::from_utf8(self.to_bytes())
660    }
661}
662
663// `.to_bytes()` representations are compared instead of the inner `[c_char]`s,
664// because `c_char` is `i8` (not `u8`) on some platforms.
665// That is why this is implemented manually and not derived.
666#[stable(feature = "rust1", since = "1.0.0")]
667impl PartialOrd for CStr {
668    #[inline]
669    fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
670        self.to_bytes().partial_cmp(&other.to_bytes())
671    }
672}
673#[stable(feature = "rust1", since = "1.0.0")]
674impl Ord for CStr {
675    #[inline]
676    fn cmp(&self, other: &CStr) -> Ordering {
677        self.to_bytes().cmp(&other.to_bytes())
678    }
679}
680
681#[stable(feature = "cstr_range_from", since = "1.47.0")]
682impl ops::Index<ops::RangeFrom<usize>> for CStr {
683    type Output = CStr;
684
685    #[inline]
686    fn index(&self, index: ops::RangeFrom<usize>) -> &CStr {
687        let bytes = self.to_bytes_with_nul();
688        // we need to manually check the starting index to account for the null
689        // byte, since otherwise we could get an empty string that doesn't end
690        // in a null.
691        if index.start < bytes.len() {
692            // SAFETY: Non-empty tail of a valid `CStr` is still a valid `CStr`.
693            unsafe { CStr::from_bytes_with_nul_unchecked(&bytes[index.start..]) }
694        } else {
695            panic!(
696                "index out of bounds: the len is {} but the index is {}",
697                bytes.len(),
698                index.start
699            );
700        }
701    }
702}
703
704#[stable(feature = "cstring_asref", since = "1.7.0")]
705impl AsRef<CStr> for CStr {
706    #[inline]
707    fn as_ref(&self) -> &CStr {
708        self
709    }
710}
711
712/// Calculate the length of a nul-terminated string. Defers to C's `strlen` when possible.
713///
714/// # Safety
715///
716/// The pointer must point to a valid buffer that contains a NUL terminator. The NUL must be
717/// located within `isize::MAX` from `ptr`.
718#[inline]
719#[unstable(feature = "cstr_internals", issue = "none")]
720#[rustc_allow_const_fn_unstable(const_eval_select)]
721const unsafe fn strlen(ptr: *const c_char) -> usize {
722    const_eval_select!(
723        @capture { s: *const c_char = ptr } -> usize:
724        if const {
725            let mut len = 0;
726
727            // SAFETY: Outer caller has provided a pointer to a valid C string.
728            while unsafe { *s.add(len) } != 0 {
729                len += 1;
730            }
731
732            len
733        } else {
734            unsafe extern "C" {
735                /// Provided by libc or compiler_builtins.
736                fn strlen(s: *const c_char) -> usize;
737            }
738
739            // SAFETY: Outer caller has provided a pointer to a valid C string.
740            unsafe { strlen(s) }
741        }
742    )
743}
744
745/// An iterator over the bytes of a [`CStr`], without the nul terminator.
746///
747/// This struct is created by the [`bytes`] method on [`CStr`].
748/// See its documentation for more.
749///
750/// [`bytes`]: CStr::bytes
751#[must_use = "iterators are lazy and do nothing unless consumed"]
752#[unstable(feature = "cstr_bytes", issue = "112115")]
753#[derive(Clone, Debug)]
754pub struct Bytes<'a> {
755    // since we know the string is nul-terminated, we only need one pointer
756    ptr: NonNull<u8>,
757    phantom: PhantomData<&'a [c_char]>,
758}
759
760#[unstable(feature = "cstr_bytes", issue = "112115")]
761unsafe impl Send for Bytes<'_> {}
762
763#[unstable(feature = "cstr_bytes", issue = "112115")]
764unsafe impl Sync for Bytes<'_> {}
765
766impl<'a> Bytes<'a> {
767    #[inline]
768    fn new(s: &'a CStr) -> Self {
769        Self { ptr: s.as_non_null_ptr().cast(), phantom: PhantomData }
770    }
771
772    #[inline]
773    fn is_empty(&self) -> bool {
774        // SAFETY: We uphold that the pointer is always valid to dereference
775        // by starting with a valid C string and then never incrementing beyond
776        // the nul terminator.
777        unsafe { self.ptr.read() == 0 }
778    }
779}
780
781#[unstable(feature = "cstr_bytes", issue = "112115")]
782impl Iterator for Bytes<'_> {
783    type Item = u8;
784
785    #[inline]
786    fn next(&mut self) -> Option<u8> {
787        // SAFETY: We only choose a pointer from a valid C string, which must
788        // be non-null and contain at least one value. Since we always stop at
789        // the nul terminator, which is guaranteed to exist, we can assume that
790        // the pointer is non-null and valid. This lets us safely dereference
791        // it and assume that adding 1 will create a new, non-null, valid
792        // pointer.
793        unsafe {
794            let ret = self.ptr.read();
795            if ret == 0 {
796                None
797            } else {
798                self.ptr = self.ptr.add(1);
799                Some(ret)
800            }
801        }
802    }
803
804    #[inline]
805    fn size_hint(&self) -> (usize, Option<usize>) {
806        if self.is_empty() { (0, Some(0)) } else { (1, None) }
807    }
808
809    #[inline]
810    fn count(self) -> usize {
811        // SAFETY: We always hold a valid pointer to a C string
812        unsafe { strlen(self.ptr.as_ptr().cast()) }
813    }
814}
815
816#[unstable(feature = "cstr_bytes", issue = "112115")]
817impl FusedIterator for Bytes<'_> {}