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::{CString, CStr};
59/// use std::os::raw::c_char;
60///
61/// fn work(data: &CStr) {
62/// #   /* Extern functions are awkward in doc comments - fake it instead
63///     extern "C" { fn work_with(data: *const c_char); }
64/// #   */ unsafe extern "C" fn work_with(s: *const c_char) {}
65///
66///     unsafe { work_with(data.as_ptr()) }
67/// }
68///
69/// let s = CString::new("data data data data").expect("CString::new failed");
70/// work(&s);
71/// ```
72///
73/// Converting a foreign C string into a Rust `String`:
74///
75/// ```
76/// use std::ffi::CStr;
77/// use std::os::raw::c_char;
78///
79/// # /* Extern functions are awkward in doc comments - fake it instead
80/// extern "C" { fn my_string() -> *const c_char; }
81/// # */ unsafe extern "C" fn my_string() -> *const c_char { c"hello".as_ptr() }
82///
83/// fn my_string_safe() -> String {
84///     let cstr = unsafe { CStr::from_ptr(my_string()) };
85///     // Get copy-on-write Cow<'_, str>, then guarantee a freshly-owned String allocation
86///     String::from_utf8_lossy(cstr.to_bytes()).to_string()
87/// }
88///
89/// println!("string: {}", my_string_safe());
90/// ```
91///
92/// [str]: prim@str "str"
93#[derive(PartialEq, Eq, Hash)]
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)]
104pub struct CStr {
105    // FIXME: this should not be represented with a DST slice but rather with
106    //        just a raw `c_char` along with some form of marker to make
107    //        this an unsized type. Essentially `sizeof(&CStr)` should be the
108    //        same as `sizeof(&c_char)` but `CStr` should be an unsized type.
109    inner: [c_char],
110}
111
112/// An error indicating that a nul byte was not in the expected position.
113///
114/// The slice used to create a [`CStr`] must have one and only one nul byte,
115/// positioned at the end.
116///
117/// This error is created by the [`CStr::from_bytes_with_nul`] method.
118/// See its documentation for more.
119///
120/// # Examples
121///
122/// ```
123/// use std::ffi::{CStr, FromBytesWithNulError};
124///
125/// let _: FromBytesWithNulError = CStr::from_bytes_with_nul(b"f\0oo").unwrap_err();
126/// ```
127#[derive(Clone, Copy, PartialEq, Eq, Debug)]
128#[stable(feature = "core_c_str", since = "1.64.0")]
129pub enum FromBytesWithNulError {
130    /// Data provided contains an interior nul byte at byte `position`.
131    InteriorNul {
132        /// The position of the interior nul byte.
133        position: usize,
134    },
135    /// Data provided is not nul terminated.
136    NotNulTerminated,
137}
138
139#[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
140impl Error for FromBytesWithNulError {
141    #[allow(deprecated)]
142    fn description(&self) -> &str {
143        match self {
144            Self::InteriorNul { .. } => "data provided contains an interior nul byte",
145            Self::NotNulTerminated => "data provided is not nul terminated",
146        }
147    }
148}
149
150/// An error indicating that no nul byte was present.
151///
152/// A slice used to create a [`CStr`] must contain a nul byte somewhere
153/// within the slice.
154///
155/// This error is created by the [`CStr::from_bytes_until_nul`] method.
156///
157#[derive(Clone, PartialEq, Eq, Debug)]
158#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
159pub struct FromBytesUntilNulError(());
160
161#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
162impl fmt::Display for FromBytesUntilNulError {
163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164        write!(f, "data provided does not contain a nul")
165    }
166}
167
168#[stable(feature = "cstr_debug", since = "1.3.0")]
169impl fmt::Debug for CStr {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        write!(f, "\"{}\"", self.to_bytes().escape_ascii())
172    }
173}
174
175#[stable(feature = "cstr_default", since = "1.10.0")]
176impl Default for &CStr {
177    #[inline]
178    fn default() -> Self {
179        const SLICE: &[c_char] = &[0];
180        // SAFETY: `SLICE` is indeed pointing to a valid nul-terminated string.
181        unsafe { CStr::from_ptr(SLICE.as_ptr()) }
182    }
183}
184
185#[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
186impl fmt::Display for FromBytesWithNulError {
187    #[allow(deprecated, deprecated_in_future)]
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        f.write_str(self.description())?;
190        if let Self::InteriorNul { position } = self {
191            write!(f, " at byte pos {position}")?;
192        }
193        Ok(())
194    }
195}
196
197impl CStr {
198    /// Wraps a raw C string with a safe C string wrapper.
199    ///
200    /// This function will wrap the provided `ptr` with a `CStr` wrapper, which
201    /// allows inspection and interoperation of non-owned C strings. The total
202    /// size of the terminated buffer must be smaller than [`isize::MAX`] **bytes**
203    /// in memory (a restriction from [`slice::from_raw_parts`]).
204    ///
205    /// # Safety
206    ///
207    /// * The memory pointed to by `ptr` must contain a valid nul terminator at the
208    ///   end of the string.
209    ///
210    /// * `ptr` must be [valid] for reads of bytes up to and including the nul terminator.
211    ///   This means in particular:
212    ///
213    ///     * The entire memory range of this `CStr` must be contained within a single allocated object!
214    ///     * `ptr` must be non-null even for a zero-length cstr.
215    ///
216    /// * The memory referenced by the returned `CStr` must not be mutated for
217    ///   the duration of lifetime `'a`.
218    ///
219    /// * The nul terminator must be within `isize::MAX` from `ptr`
220    ///
221    /// > **Note**: This operation is intended to be a 0-cost cast but it is
222    /// > currently implemented with an up-front calculation of the length of
223    /// > the string. This is not guaranteed to always be the case.
224    ///
225    /// # Caveat
226    ///
227    /// The lifetime for the returned slice is inferred from its usage. To prevent accidental misuse,
228    /// it's suggested to tie the lifetime to whichever source lifetime is safe in the context,
229    /// such as by providing a helper function taking the lifetime of a host value for the slice,
230    /// or by explicit annotation.
231    ///
232    /// # Examples
233    ///
234    /// ```
235    /// use std::ffi::{c_char, CStr};
236    ///
237    /// fn my_string() -> *const c_char {
238    ///     c"hello".as_ptr()
239    /// }
240    ///
241    /// unsafe {
242    ///     let slice = CStr::from_ptr(my_string());
243    ///     assert_eq!(slice.to_str().unwrap(), "hello");
244    /// }
245    /// ```
246    ///
247    /// ```
248    /// use std::ffi::{c_char, CStr};
249    ///
250    /// const HELLO_PTR: *const c_char = {
251    ///     const BYTES: &[u8] = b"Hello, world!\0";
252    ///     BYTES.as_ptr().cast()
253    /// };
254    /// const HELLO: &CStr = unsafe { CStr::from_ptr(HELLO_PTR) };
255    ///
256    /// assert_eq!(c"Hello, world!", HELLO);
257    /// ```
258    ///
259    /// [valid]: core::ptr#safety
260    #[inline] // inline is necessary for codegen to see strlen.
261    #[must_use]
262    #[stable(feature = "rust1", since = "1.0.0")]
263    #[rustc_const_stable(feature = "const_cstr_from_ptr", since = "1.81.0")]
264    pub const unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
265        // SAFETY: The caller has provided a pointer that points to a valid C
266        // string with a NUL terminator less than `isize::MAX` from `ptr`.
267        let len = unsafe { strlen(ptr) };
268
269        // SAFETY: The caller has provided a valid pointer with length less than
270        // `isize::MAX`, so `from_raw_parts` is safe. The content remains valid
271        // and doesn't change for the lifetime of the returned `CStr`. This
272        // means the call to `from_bytes_with_nul_unchecked` is correct.
273        //
274        // The cast from c_char to u8 is ok because a c_char is always one byte.
275        unsafe { Self::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr.cast(), len + 1)) }
276    }
277
278    /// Creates a C string wrapper from a byte slice with any number of nuls.
279    ///
280    /// This method will create a `CStr` from any byte slice that contains at
281    /// least one nul byte. Unlike with [`CStr::from_bytes_with_nul`], the caller
282    /// does not need to know where the nul byte is located.
283    ///
284    /// If the first byte is a nul character, this method will return an
285    /// empty `CStr`. If multiple nul characters are present, the `CStr` will
286    /// end at the first one.
287    ///
288    /// If the slice only has a single nul byte at the end, this method is
289    /// equivalent to [`CStr::from_bytes_with_nul`].
290    ///
291    /// # Examples
292    /// ```
293    /// use std::ffi::CStr;
294    ///
295    /// let mut buffer = [0u8; 16];
296    /// unsafe {
297    ///     // Here we might call an unsafe C function that writes a string
298    ///     // into the buffer.
299    ///     let buf_ptr = buffer.as_mut_ptr();
300    ///     buf_ptr.write_bytes(b'A', 8);
301    /// }
302    /// // Attempt to extract a C nul-terminated string from the buffer.
303    /// let c_str = CStr::from_bytes_until_nul(&buffer[..]).unwrap();
304    /// assert_eq!(c_str.to_str().unwrap(), "AAAAAAAA");
305    /// ```
306    ///
307    #[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
308    #[rustc_const_stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
309    pub const fn from_bytes_until_nul(bytes: &[u8]) -> Result<&CStr, FromBytesUntilNulError> {
310        let nul_pos = memchr::memchr(0, bytes);
311        match nul_pos {
312            Some(nul_pos) => {
313                // FIXME(const-hack) replace with range index
314                // SAFETY: nul_pos + 1 <= bytes.len()
315                let subslice = unsafe { crate::slice::from_raw_parts(bytes.as_ptr(), nul_pos + 1) };
316                // SAFETY: We know there is a nul byte at nul_pos, so this slice
317                // (ending at the nul byte) is a well-formed C string.
318                Ok(unsafe { CStr::from_bytes_with_nul_unchecked(subslice) })
319            }
320            None => Err(FromBytesUntilNulError(())),
321        }
322    }
323
324    /// Creates a C string wrapper from a byte slice with exactly one nul
325    /// terminator.
326    ///
327    /// This function will cast the provided `bytes` to a `CStr`
328    /// wrapper after ensuring that the byte slice is nul-terminated
329    /// and does not contain any interior nul bytes.
330    ///
331    /// If the nul byte may not be at the end,
332    /// [`CStr::from_bytes_until_nul`] can be used instead.
333    ///
334    /// # Examples
335    ///
336    /// ```
337    /// use std::ffi::CStr;
338    ///
339    /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
340    /// assert_eq!(cstr, Ok(c"hello"));
341    /// ```
342    ///
343    /// Creating a `CStr` without a trailing nul terminator is an error:
344    ///
345    /// ```
346    /// use std::ffi::{CStr, FromBytesWithNulError};
347    ///
348    /// let cstr = CStr::from_bytes_with_nul(b"hello");
349    /// assert_eq!(cstr, Err(FromBytesWithNulError::NotNulTerminated));
350    /// ```
351    ///
352    /// Creating a `CStr` with an interior nul byte is an error:
353    ///
354    /// ```
355    /// use std::ffi::{CStr, FromBytesWithNulError};
356    ///
357    /// let cstr = CStr::from_bytes_with_nul(b"he\0llo\0");
358    /// assert_eq!(cstr, Err(FromBytesWithNulError::InteriorNul { position: 2 }));
359    /// ```
360    #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
361    #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")]
362    pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, FromBytesWithNulError> {
363        let nul_pos = memchr::memchr(0, bytes);
364        match nul_pos {
365            Some(nul_pos) if nul_pos + 1 == bytes.len() => {
366                // SAFETY: We know there is only one nul byte, at the end
367                // of the byte slice.
368                Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) })
369            }
370            Some(position) => Err(FromBytesWithNulError::InteriorNul { position }),
371            None => Err(FromBytesWithNulError::NotNulTerminated),
372        }
373    }
374
375    /// Unsafely creates a C string wrapper from a byte slice.
376    ///
377    /// This function will cast the provided `bytes` to a `CStr` wrapper without
378    /// performing any sanity checks.
379    ///
380    /// # Safety
381    /// The provided slice **must** be nul-terminated and not contain any interior
382    /// nul bytes.
383    ///
384    /// # Examples
385    ///
386    /// ```
387    /// use std::ffi::{CStr, CString};
388    ///
389    /// unsafe {
390    ///     let cstring = CString::new("hello").expect("CString::new failed");
391    ///     let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
392    ///     assert_eq!(cstr, &*cstring);
393    /// }
394    /// ```
395    #[inline]
396    #[must_use]
397    #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
398    #[rustc_const_stable(feature = "const_cstr_unchecked", since = "1.59.0")]
399    #[rustc_allow_const_fn_unstable(const_eval_select)]
400    pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
401        const_eval_select!(
402            @capture { bytes: &[u8] } -> &CStr:
403            if const {
404                // Saturating so that an empty slice panics in the assert with a good
405                // message, not here due to underflow.
406                let mut i = bytes.len().saturating_sub(1);
407                assert!(!bytes.is_empty() && bytes[i] == 0, "input was not nul-terminated");
408
409                // Ending nul byte exists, skip to the rest.
410                while i != 0 {
411                    i -= 1;
412                    let byte = bytes[i];
413                    assert!(byte != 0, "input contained interior nul");
414                }
415
416                // SAFETY: See runtime cast comment below.
417                unsafe { &*(bytes as *const [u8] as *const CStr) }
418            } else {
419                // Chance at catching some UB at runtime with debug builds.
420                debug_assert!(!bytes.is_empty() && bytes[bytes.len() - 1] == 0);
421
422                // SAFETY: Casting to CStr is safe because its internal representation
423                // is a [u8] too (safe only inside std).
424                // Dereferencing the obtained pointer is safe because it comes from a
425                // reference. Making a reference is then safe because its lifetime
426                // is bound by the lifetime of the given `bytes`.
427                unsafe { &*(bytes as *const [u8] as *const CStr) }
428            }
429        )
430    }
431
432    /// Returns the inner pointer to this C string.
433    ///
434    /// The returned pointer will be valid for as long as `self` is, and points
435    /// to a contiguous region of memory terminated with a 0 byte to represent
436    /// the end of the string.
437    ///
438    /// The type of the returned pointer is
439    /// [`*const c_char`][crate::ffi::c_char], and whether it's
440    /// an alias for `*const i8` or `*const u8` is platform-specific.
441    ///
442    /// **WARNING**
443    ///
444    /// The returned pointer is read-only; writing to it (including passing it
445    /// to C code that writes to it) causes undefined behavior.
446    ///
447    /// It is your responsibility to make sure that the underlying memory is not
448    /// freed too early. For example, the following code will cause undefined
449    /// behavior when `ptr` is used inside the `unsafe` block:
450    ///
451    /// ```no_run
452    /// # #![allow(unused_must_use)]
453    /// # #![expect(dangling_pointers_from_temporaries)]
454    /// use std::ffi::CString;
455    ///
456    /// // Do not do this:
457    /// let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
458    /// unsafe {
459    ///     // `ptr` is dangling
460    ///     *ptr;
461    /// }
462    /// ```
463    ///
464    /// This happens because the pointer returned by `as_ptr` does not carry any
465    /// lifetime information and the `CString` is deallocated immediately after
466    /// the `CString::new("Hello").expect("CString::new failed").as_ptr()`
467    /// expression is evaluated.
468    /// To fix the problem, bind the `CString` to a local variable:
469    ///
470    /// ```no_run
471    /// # #![allow(unused_must_use)]
472    /// use std::ffi::CString;
473    ///
474    /// let hello = CString::new("Hello").expect("CString::new failed");
475    /// let ptr = hello.as_ptr();
476    /// unsafe {
477    ///     // `ptr` is valid because `hello` is in scope
478    ///     *ptr;
479    /// }
480    /// ```
481    ///
482    /// This way, the lifetime of the `CString` in `hello` encompasses
483    /// the lifetime of `ptr` and the `unsafe` block.
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<'_> {}