]> git.lizzy.rs Git - rust.git/blob - library/core/src/ffi/c_str.rs
Rollup merge of #107446 - clubby789:rustc-parse-diag-migrate, r=compiler-errors
[rust.git] / library / core / src / ffi / c_str.rs
1 use crate::cmp::Ordering;
2 use crate::ffi::c_char;
3 use crate::fmt;
4 use crate::intrinsics;
5 use crate::ops;
6 use crate::slice;
7 use crate::slice::memchr;
8 use crate::str;
9
10 /// Representation of a borrowed C string.
11 ///
12 /// This type represents a borrowed reference to a nul-terminated
13 /// array of bytes. It can be constructed safely from a <code>&[[u8]]</code>
14 /// slice, or unsafely from a raw `*const c_char`. It can then be
15 /// converted to a Rust <code>&[str]</code> by performing UTF-8 validation, or
16 /// into an owned [`CString`].
17 ///
18 /// `&CStr` is to [`CString`] as <code>&[str]</code> is to [`String`]: the former
19 /// in each pair are borrowed references; the latter are owned
20 /// strings.
21 ///
22 /// Note that this structure is **not** `repr(C)` and is not recommended to be
23 /// placed in the signatures of FFI functions. Instead, safe wrappers of FFI
24 /// functions may leverage the unsafe [`CStr::from_ptr`] constructor to provide
25 /// a safe interface to other consumers.
26 ///
27 /// [`CString`]: ../../std/ffi/struct.CString.html
28 /// [`String`]: ../../std/string/struct.String.html
29 ///
30 /// # Examples
31 ///
32 /// Inspecting a foreign C string:
33 ///
34 /// ```ignore (extern-declaration)
35 /// use std::ffi::CStr;
36 /// use std::os::raw::c_char;
37 ///
38 /// extern "C" { fn my_string() -> *const c_char; }
39 ///
40 /// unsafe {
41 ///     let slice = CStr::from_ptr(my_string());
42 ///     println!("string buffer size without nul terminator: {}", slice.to_bytes().len());
43 /// }
44 /// ```
45 ///
46 /// Passing a Rust-originating C string:
47 ///
48 /// ```ignore (extern-declaration)
49 /// use std::ffi::{CString, CStr};
50 /// use std::os::raw::c_char;
51 ///
52 /// fn work(data: &CStr) {
53 ///     extern "C" { fn work_with(data: *const c_char); }
54 ///
55 ///     unsafe { work_with(data.as_ptr()) }
56 /// }
57 ///
58 /// let s = CString::new("data data data data").expect("CString::new failed");
59 /// work(&s);
60 /// ```
61 ///
62 /// Converting a foreign C string into a Rust `String`:
63 ///
64 /// ```ignore (extern-declaration)
65 /// use std::ffi::CStr;
66 /// use std::os::raw::c_char;
67 ///
68 /// extern "C" { fn my_string() -> *const c_char; }
69 ///
70 /// fn my_string_safe() -> String {
71 ///     let cstr = unsafe { CStr::from_ptr(my_string()) };
72 ///     // Get copy-on-write Cow<'_, str>, then guarantee a freshly-owned String allocation
73 ///     String::from_utf8_lossy(cstr.to_bytes()).to_string()
74 /// }
75 ///
76 /// println!("string: {}", my_string_safe());
77 /// ```
78 ///
79 /// [str]: prim@str "str"
80 #[derive(Hash)]
81 #[cfg_attr(not(test), rustc_diagnostic_item = "CStr")]
82 #[stable(feature = "core_c_str", since = "1.64.0")]
83 #[rustc_has_incoherent_inherent_impls]
84 // FIXME:
85 // `fn from` in `impl From<&CStr> for Box<CStr>` current implementation relies
86 // on `CStr` being layout-compatible with `[u8]`.
87 // When attribute privacy is implemented, `CStr` should be annotated as `#[repr(transparent)]`.
88 // Anyway, `CStr` representation and layout are considered implementation detail, are
89 // not documented and must not be relied upon.
90 pub struct CStr {
91     // FIXME: this should not be represented with a DST slice but rather with
92     //        just a raw `c_char` along with some form of marker to make
93     //        this an unsized type. Essentially `sizeof(&CStr)` should be the
94     //        same as `sizeof(&c_char)` but `CStr` should be an unsized type.
95     inner: [c_char],
96 }
97
98 /// An error indicating that a nul byte was not in the expected position.
99 ///
100 /// The slice used to create a [`CStr`] must have one and only one nul byte,
101 /// positioned at the end.
102 ///
103 /// This error is created by the [`CStr::from_bytes_with_nul`] method.
104 /// See its documentation for more.
105 ///
106 /// # Examples
107 ///
108 /// ```
109 /// use std::ffi::{CStr, FromBytesWithNulError};
110 ///
111 /// let _: FromBytesWithNulError = CStr::from_bytes_with_nul(b"f\0oo").unwrap_err();
112 /// ```
113 #[derive(Clone, PartialEq, Eq, Debug)]
114 #[stable(feature = "core_c_str", since = "1.64.0")]
115 pub struct FromBytesWithNulError {
116     kind: FromBytesWithNulErrorKind,
117 }
118
119 #[derive(Clone, PartialEq, Eq, Debug)]
120 enum FromBytesWithNulErrorKind {
121     InteriorNul(usize),
122     NotNulTerminated,
123 }
124
125 impl FromBytesWithNulError {
126     const fn interior_nul(pos: usize) -> FromBytesWithNulError {
127         FromBytesWithNulError { kind: FromBytesWithNulErrorKind::InteriorNul(pos) }
128     }
129     const fn not_nul_terminated() -> FromBytesWithNulError {
130         FromBytesWithNulError { kind: FromBytesWithNulErrorKind::NotNulTerminated }
131     }
132
133     #[doc(hidden)]
134     #[unstable(feature = "cstr_internals", issue = "none")]
135     pub fn __description(&self) -> &str {
136         match self.kind {
137             FromBytesWithNulErrorKind::InteriorNul(..) => {
138                 "data provided contains an interior nul byte"
139             }
140             FromBytesWithNulErrorKind::NotNulTerminated => "data provided is not nul terminated",
141         }
142     }
143 }
144
145 /// An error indicating that no nul byte was present.
146 ///
147 /// A slice used to create a [`CStr`] must contain a nul byte somewhere
148 /// within the slice.
149 ///
150 /// This error is created by the [`CStr::from_bytes_until_nul`] method.
151 ///
152 #[derive(Clone, PartialEq, Eq, Debug)]
153 #[stable(feature = "cstr_from_bytes_until_nul", since = "CURRENT_RUSTC_VERSION")]
154 pub struct FromBytesUntilNulError(());
155
156 #[stable(feature = "cstr_from_bytes_until_nul", since = "CURRENT_RUSTC_VERSION")]
157 impl fmt::Display for FromBytesUntilNulError {
158     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159         write!(f, "data provided does not contain a nul")
160     }
161 }
162
163 #[stable(feature = "cstr_debug", since = "1.3.0")]
164 impl fmt::Debug for CStr {
165     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166         write!(f, "\"{}\"", self.to_bytes().escape_ascii())
167     }
168 }
169
170 #[stable(feature = "cstr_default", since = "1.10.0")]
171 impl Default for &CStr {
172     fn default() -> Self {
173         const SLICE: &[c_char] = &[0];
174         // SAFETY: `SLICE` is indeed pointing to a valid nul-terminated string.
175         unsafe { CStr::from_ptr(SLICE.as_ptr()) }
176     }
177 }
178
179 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
180 impl fmt::Display for FromBytesWithNulError {
181     #[allow(deprecated, deprecated_in_future)]
182     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183         f.write_str(self.__description())?;
184         if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind {
185             write!(f, " at byte pos {pos}")?;
186         }
187         Ok(())
188     }
189 }
190
191 impl CStr {
192     /// Wraps a raw C string with a safe C string wrapper.
193     ///
194     /// This function will wrap the provided `ptr` with a `CStr` wrapper, which
195     /// allows inspection and interoperation of non-owned C strings. The total
196     /// size of the raw C string must be smaller than `isize::MAX` **bytes**
197     /// in memory due to calling the `slice::from_raw_parts` function.
198     ///
199     /// # Safety
200     ///
201     /// * The memory pointed to by `ptr` must contain a valid nul terminator at the
202     ///   end of the string.
203     ///
204     /// * `ptr` must be [valid] for reads of bytes up to and including the null terminator.
205     ///   This means in particular:
206     ///
207     ///     * The entire memory range of this `CStr` must be contained within a single allocated object!
208     ///     * `ptr` must be non-null even for a zero-length cstr.
209     ///
210     /// * The memory referenced by the returned `CStr` must not be mutated for
211     ///   the duration of lifetime `'a`.
212     ///
213     /// > **Note**: This operation is intended to be a 0-cost cast but it is
214     /// > currently implemented with an up-front calculation of the length of
215     /// > the string. This is not guaranteed to always be the case.
216     ///
217     /// # Caveat
218     ///
219     /// The lifetime for the returned slice is inferred from its usage. To prevent accidental misuse,
220     /// it's suggested to tie the lifetime to whichever source lifetime is safe in the context,
221     /// such as by providing a helper function taking the lifetime of a host value for the slice,
222     /// or by explicit annotation.
223     ///
224     /// # Examples
225     ///
226     /// ```ignore (extern-declaration)
227     /// use std::ffi::{c_char, CStr};
228     ///
229     /// extern "C" {
230     ///     fn my_string() -> *const c_char;
231     /// }
232     ///
233     /// unsafe {
234     ///     let slice = CStr::from_ptr(my_string());
235     ///     println!("string returned: {}", slice.to_str().unwrap());
236     /// }
237     /// ```
238     ///
239     /// ```
240     /// #![feature(const_cstr_methods)]
241     ///
242     /// use std::ffi::{c_char, CStr};
243     ///
244     /// const HELLO_PTR: *const c_char = {
245     ///     const BYTES: &[u8] = b"Hello, world!\0";
246     ///     BYTES.as_ptr().cast()
247     /// };
248     /// const HELLO: &CStr = unsafe { CStr::from_ptr(HELLO_PTR) };
249     /// ```
250     ///
251     /// [valid]: core::ptr#safety
252     #[inline]
253     #[must_use]
254     #[stable(feature = "rust1", since = "1.0.0")]
255     #[rustc_const_unstable(feature = "const_cstr_methods", issue = "101719")]
256     pub const unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
257         // SAFETY: The caller has provided a pointer that points to a valid C
258         // string with a NUL terminator of size less than `isize::MAX`, whose
259         // content remain valid and doesn't change for the lifetime of the
260         // returned `CStr`.
261         //
262         // Thus computing the length is fine (a NUL byte exists), the call to
263         // from_raw_parts is safe because we know the length is at most `isize::MAX`, meaning
264         // the call to `from_bytes_with_nul_unchecked` is correct.
265         //
266         // The cast from c_char to u8 is ok because a c_char is always one byte.
267         unsafe {
268             const fn strlen_ct(s: *const c_char) -> usize {
269                 let mut len = 0;
270
271                 // SAFETY: Outer caller has provided a pointer to a valid C string.
272                 while unsafe { *s.add(len) } != 0 {
273                     len += 1;
274                 }
275
276                 len
277             }
278
279             fn strlen_rt(s: *const c_char) -> usize {
280                 extern "C" {
281                     /// Provided by libc or compiler_builtins.
282                     fn strlen(s: *const c_char) -> usize;
283                 }
284
285                 // SAFETY: Outer caller has provided a pointer to a valid C string.
286                 unsafe { strlen(s) }
287             }
288
289             let len = intrinsics::const_eval_select((ptr,), strlen_ct, strlen_rt);
290             Self::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr.cast(), len + 1))
291         }
292     }
293
294     /// Creates a C string wrapper from a byte slice.
295     ///
296     /// This method will create a `CStr` from any byte slice that contains at
297     /// least one nul byte. The caller does not need to know or specify where
298     /// the nul byte is located.
299     ///
300     /// If the first byte is a nul character, this method will return an
301     /// empty `CStr`. If multiple nul characters are present, the `CStr` will
302     /// end at the first one.
303     ///
304     /// If the slice only has a single nul byte at the end, this method is
305     /// equivalent to [`CStr::from_bytes_with_nul`].
306     ///
307     /// # Examples
308     /// ```
309     /// use std::ffi::CStr;
310     ///
311     /// let mut buffer = [0u8; 16];
312     /// unsafe {
313     ///     // Here we might call an unsafe C function that writes a string
314     ///     // into the buffer.
315     ///     let buf_ptr = buffer.as_mut_ptr();
316     ///     buf_ptr.write_bytes(b'A', 8);
317     /// }
318     /// // Attempt to extract a C nul-terminated string from the buffer.
319     /// let c_str = CStr::from_bytes_until_nul(&buffer[..]).unwrap();
320     /// assert_eq!(c_str.to_str().unwrap(), "AAAAAAAA");
321     /// ```
322     ///
323     #[rustc_allow_const_fn_unstable(const_slice_index)]
324     #[stable(feature = "cstr_from_bytes_until_nul", since = "CURRENT_RUSTC_VERSION")]
325     #[rustc_const_stable(feature = "cstr_from_bytes_until_nul", since = "CURRENT_RUSTC_VERSION")]
326     pub const fn from_bytes_until_nul(bytes: &[u8]) -> Result<&CStr, FromBytesUntilNulError> {
327         let nul_pos = memchr::memchr(0, bytes);
328         match nul_pos {
329             Some(nul_pos) => {
330                 let subslice = &bytes[..nul_pos + 1];
331                 // SAFETY: We know there is a nul byte at nul_pos, so this slice
332                 // (ending at the nul byte) is a well-formed C string.
333                 Ok(unsafe { CStr::from_bytes_with_nul_unchecked(subslice) })
334             }
335             None => Err(FromBytesUntilNulError(())),
336         }
337     }
338
339     /// Creates a C string wrapper from a byte slice.
340     ///
341     /// This function will cast the provided `bytes` to a `CStr`
342     /// wrapper after ensuring that the byte slice is nul-terminated
343     /// and does not contain any interior nul bytes.
344     ///
345     /// If the nul byte may not be at the end,
346     /// [`CStr::from_bytes_until_nul`] can be used instead.
347     ///
348     /// # Examples
349     ///
350     /// ```
351     /// use std::ffi::CStr;
352     ///
353     /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
354     /// assert!(cstr.is_ok());
355     /// ```
356     ///
357     /// Creating a `CStr` without a trailing nul terminator is an error:
358     ///
359     /// ```
360     /// use std::ffi::CStr;
361     ///
362     /// let cstr = CStr::from_bytes_with_nul(b"hello");
363     /// assert!(cstr.is_err());
364     /// ```
365     ///
366     /// Creating a `CStr` with an interior nul byte is an error:
367     ///
368     /// ```
369     /// use std::ffi::CStr;
370     ///
371     /// let cstr = CStr::from_bytes_with_nul(b"he\0llo\0");
372     /// assert!(cstr.is_err());
373     /// ```
374     #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
375     #[rustc_const_unstable(feature = "const_cstr_methods", issue = "101719")]
376     pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, FromBytesWithNulError> {
377         let nul_pos = memchr::memchr(0, bytes);
378         match nul_pos {
379             Some(nul_pos) if nul_pos + 1 == bytes.len() => {
380                 // SAFETY: We know there is only one nul byte, at the end
381                 // of the byte slice.
382                 Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) })
383             }
384             Some(nul_pos) => Err(FromBytesWithNulError::interior_nul(nul_pos)),
385             None => Err(FromBytesWithNulError::not_nul_terminated()),
386         }
387     }
388
389     /// Unsafely creates a C string wrapper from a byte slice.
390     ///
391     /// This function will cast the provided `bytes` to a `CStr` wrapper without
392     /// performing any sanity checks.
393     ///
394     /// # Safety
395     /// The provided slice **must** be nul-terminated and not contain any interior
396     /// nul bytes.
397     ///
398     /// # Examples
399     ///
400     /// ```
401     /// use std::ffi::{CStr, CString};
402     ///
403     /// unsafe {
404     ///     let cstring = CString::new("hello").expect("CString::new failed");
405     ///     let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
406     ///     assert_eq!(cstr, &*cstring);
407     /// }
408     /// ```
409     #[inline]
410     #[must_use]
411     #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
412     #[rustc_const_stable(feature = "const_cstr_unchecked", since = "1.59.0")]
413     #[rustc_allow_const_fn_unstable(const_eval_select)]
414     pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
415         #[inline]
416         fn rt_impl(bytes: &[u8]) -> &CStr {
417             // Chance at catching some UB at runtime with debug builds.
418             debug_assert!(!bytes.is_empty() && bytes[bytes.len() - 1] == 0);
419
420             // SAFETY: Casting to CStr is safe because its internal representation
421             // is a [u8] too (safe only inside std).
422             // Dereferencing the obtained pointer is safe because it comes from a
423             // reference. Making a reference is then safe because its lifetime
424             // is bound by the lifetime of the given `bytes`.
425             unsafe { &*(bytes as *const [u8] as *const CStr) }
426         }
427
428         const fn const_impl(bytes: &[u8]) -> &CStr {
429             // Saturating so that an empty slice panics in the assert with a good
430             // message, not here due to underflow.
431             let mut i = bytes.len().saturating_sub(1);
432             assert!(!bytes.is_empty() && bytes[i] == 0, "input was not nul-terminated");
433
434             // Ending null byte exists, skip to the rest.
435             while i != 0 {
436                 i -= 1;
437                 let byte = bytes[i];
438                 assert!(byte != 0, "input contained interior nul");
439             }
440
441             // SAFETY: See `rt_impl` cast.
442             unsafe { &*(bytes as *const [u8] as *const CStr) }
443         }
444
445         // SAFETY: The const and runtime versions have identical behavior
446         // unless the safety contract of `from_bytes_with_nul_unchecked` is
447         // violated, which is UB.
448         unsafe { intrinsics::const_eval_select((bytes,), const_impl, rt_impl) }
449     }
450
451     /// Returns the inner pointer to this C string.
452     ///
453     /// The returned pointer will be valid for as long as `self` is, and points
454     /// to a contiguous region of memory terminated with a 0 byte to represent
455     /// the end of the string.
456     ///
457     /// **WARNING**
458     ///
459     /// The returned pointer is read-only; writing to it (including passing it
460     /// to C code that writes to it) causes undefined behavior.
461     ///
462     /// It is your responsibility to make sure that the underlying memory is not
463     /// freed too early. For example, the following code will cause undefined
464     /// behavior when `ptr` is used inside the `unsafe` block:
465     ///
466     /// ```no_run
467     /// # #![allow(unused_must_use)] #![allow(temporary_cstring_as_ptr)]
468     /// use std::ffi::CString;
469     ///
470     /// let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
471     /// unsafe {
472     ///     // `ptr` is dangling
473     ///     *ptr;
474     /// }
475     /// ```
476     ///
477     /// This happens because the pointer returned by `as_ptr` does not carry any
478     /// lifetime information and the `CString` is deallocated immediately after
479     /// the `CString::new("Hello").expect("CString::new failed").as_ptr()`
480     /// expression is evaluated.
481     /// To fix the problem, bind the `CString` to a local variable:
482     ///
483     /// ```no_run
484     /// # #![allow(unused_must_use)]
485     /// use std::ffi::CString;
486     ///
487     /// let hello = CString::new("Hello").expect("CString::new failed");
488     /// let ptr = hello.as_ptr();
489     /// unsafe {
490     ///     // `ptr` is valid because `hello` is in scope
491     ///     *ptr;
492     /// }
493     /// ```
494     ///
495     /// This way, the lifetime of the `CString` in `hello` encompasses
496     /// the lifetime of `ptr` and the `unsafe` block.
497     #[inline]
498     #[must_use]
499     #[stable(feature = "rust1", since = "1.0.0")]
500     #[rustc_const_stable(feature = "const_str_as_ptr", since = "1.32.0")]
501     pub const fn as_ptr(&self) -> *const c_char {
502         self.inner.as_ptr()
503     }
504
505     /// Returns `true` if `self.to_bytes()` has a length of 0.
506     ///
507     /// # Examples
508     ///
509     /// ```
510     /// #![feature(cstr_is_empty)]
511     ///
512     /// use std::ffi::CStr;
513     /// # use std::ffi::FromBytesWithNulError;
514     ///
515     /// # fn main() { test().unwrap(); }
516     /// # fn test() -> Result<(), FromBytesWithNulError> {
517     /// let cstr = CStr::from_bytes_with_nul(b"foo\0")?;
518     /// assert!(!cstr.is_empty());
519     ///
520     /// let empty_cstr = CStr::from_bytes_with_nul(b"\0")?;
521     /// assert!(empty_cstr.is_empty());
522     /// # Ok(())
523     /// # }
524     /// ```
525     #[inline]
526     #[unstable(feature = "cstr_is_empty", issue = "102444")]
527     pub const fn is_empty(&self) -> bool {
528         // SAFETY: We know there is at least one byte; for empty strings it
529         // is the NUL terminator.
530         (unsafe { self.inner.get_unchecked(0) }) == &0
531     }
532
533     /// Converts this C string to a byte slice.
534     ///
535     /// The returned slice will **not** contain the trailing nul terminator that this C
536     /// string has.
537     ///
538     /// > **Note**: This method is currently implemented as a constant-time
539     /// > cast, but it is planned to alter its definition in the future to
540     /// > perform the length calculation whenever this method is called.
541     ///
542     /// # Examples
543     ///
544     /// ```
545     /// use std::ffi::CStr;
546     ///
547     /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
548     /// assert_eq!(cstr.to_bytes(), b"foo");
549     /// ```
550     #[inline]
551     #[must_use = "this returns the result of the operation, \
552                   without modifying the original"]
553     #[stable(feature = "rust1", since = "1.0.0")]
554     #[rustc_const_unstable(feature = "const_cstr_methods", issue = "101719")]
555     pub const fn to_bytes(&self) -> &[u8] {
556         let bytes = self.to_bytes_with_nul();
557         // SAFETY: to_bytes_with_nul returns slice with length at least 1
558         unsafe { bytes.get_unchecked(..bytes.len() - 1) }
559     }
560
561     /// Converts this C string to a byte slice containing the trailing 0 byte.
562     ///
563     /// This function is the equivalent of [`CStr::to_bytes`] except that it
564     /// will retain the trailing nul terminator instead of chopping it off.
565     ///
566     /// > **Note**: This method is currently implemented as a 0-cost cast, but
567     /// > it is planned to alter its definition in the future to perform the
568     /// > length calculation whenever this method is called.
569     ///
570     /// # Examples
571     ///
572     /// ```
573     /// use std::ffi::CStr;
574     ///
575     /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
576     /// assert_eq!(cstr.to_bytes_with_nul(), b"foo\0");
577     /// ```
578     #[inline]
579     #[must_use = "this returns the result of the operation, \
580                   without modifying the original"]
581     #[stable(feature = "rust1", since = "1.0.0")]
582     #[rustc_const_unstable(feature = "const_cstr_methods", issue = "101719")]
583     pub const fn to_bytes_with_nul(&self) -> &[u8] {
584         // SAFETY: Transmuting a slice of `c_char`s to a slice of `u8`s
585         // is safe on all supported targets.
586         unsafe { &*(&self.inner as *const [c_char] as *const [u8]) }
587     }
588
589     /// Yields a <code>&[str]</code> slice if the `CStr` contains valid UTF-8.
590     ///
591     /// If the contents of the `CStr` are valid UTF-8 data, this
592     /// function will return the corresponding <code>&[str]</code> slice. Otherwise,
593     /// it will return an error with details of where UTF-8 validation failed.
594     ///
595     /// [str]: prim@str "str"
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_str(), Ok("foo"));
604     /// ```
605     #[stable(feature = "cstr_to_str", since = "1.4.0")]
606     #[rustc_const_unstable(feature = "const_cstr_methods", issue = "101719")]
607     pub const fn to_str(&self) -> Result<&str, str::Utf8Error> {
608         // N.B., when `CStr` is changed to perform the length check in `.to_bytes()`
609         // instead of in `from_ptr()`, it may be worth considering if this should
610         // be rewritten to do the UTF-8 check inline with the length calculation
611         // instead of doing it afterwards.
612         str::from_utf8(self.to_bytes())
613     }
614 }
615
616 #[stable(feature = "rust1", since = "1.0.0")]
617 impl PartialEq for CStr {
618     fn eq(&self, other: &CStr) -> bool {
619         self.to_bytes().eq(other.to_bytes())
620     }
621 }
622 #[stable(feature = "rust1", since = "1.0.0")]
623 impl Eq for CStr {}
624 #[stable(feature = "rust1", since = "1.0.0")]
625 impl PartialOrd for CStr {
626     fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
627         self.to_bytes().partial_cmp(&other.to_bytes())
628     }
629 }
630 #[stable(feature = "rust1", since = "1.0.0")]
631 impl Ord for CStr {
632     fn cmp(&self, other: &CStr) -> Ordering {
633         self.to_bytes().cmp(&other.to_bytes())
634     }
635 }
636
637 #[stable(feature = "cstr_range_from", since = "1.47.0")]
638 impl ops::Index<ops::RangeFrom<usize>> for CStr {
639     type Output = CStr;
640
641     fn index(&self, index: ops::RangeFrom<usize>) -> &CStr {
642         let bytes = self.to_bytes_with_nul();
643         // we need to manually check the starting index to account for the null
644         // byte, since otherwise we could get an empty string that doesn't end
645         // in a null.
646         if index.start < bytes.len() {
647             // SAFETY: Non-empty tail of a valid `CStr` is still a valid `CStr`.
648             unsafe { CStr::from_bytes_with_nul_unchecked(&bytes[index.start..]) }
649         } else {
650             panic!(
651                 "index out of bounds: the len is {} but the index is {}",
652                 bytes.len(),
653                 index.start
654             );
655         }
656     }
657 }
658
659 #[stable(feature = "cstring_asref", since = "1.7.0")]
660 impl AsRef<CStr> for CStr {
661     #[inline]
662     fn as_ref(&self) -> &CStr {
663         self
664     }
665 }