]> git.lizzy.rs Git - rust.git/blob - library/std/src/ffi/c_str.rs
Rollup merge of #89313 - durin42:llvm-14-thinLTOResolvePrevailingInModule, r=nikic
[rust.git] / library / std / src / ffi / c_str.rs
1 #![deny(unsafe_op_in_unsafe_fn)]
2
3 #[cfg(test)]
4 mod tests;
5
6 use crate::ascii;
7 use crate::borrow::{Borrow, Cow};
8 use crate::cmp::Ordering;
9 use crate::error::Error;
10 use crate::fmt::{self, Write};
11 use crate::io;
12 use crate::mem;
13 use crate::num::NonZeroU8;
14 use crate::ops;
15 use crate::os::raw::c_char;
16 use crate::ptr;
17 use crate::rc::Rc;
18 use crate::slice;
19 use crate::str::{self, Utf8Error};
20 use crate::sync::Arc;
21 use crate::sys;
22 use crate::sys_common::memchr;
23
24 /// A type representing an owned, C-compatible, nul-terminated string with no nul bytes in the
25 /// middle.
26 ///
27 /// This type serves the purpose of being able to safely generate a
28 /// C-compatible string from a Rust byte slice or vector. An instance of this
29 /// type is a static guarantee that the underlying bytes contain no interior 0
30 /// bytes ("nul characters") and that the final byte is 0 ("nul terminator").
31 ///
32 /// `CString` is to <code>&[CStr]</code> as [`String`] is to <code>&[str]</code>: the former
33 /// in each pair are owned strings; the latter are borrowed
34 /// references.
35 ///
36 /// # Creating a `CString`
37 ///
38 /// A `CString` is created from either a byte slice or a byte vector,
39 /// or anything that implements <code>[Into]<[Vec]<[u8]>></code> (for
40 /// example, you can build a `CString` straight out of a [`String`] or
41 /// a <code>&[str]</code>, since both implement that trait).
42 ///
43 /// The [`CString::new`] method will actually check that the provided <code>&[[u8]]</code>
44 /// does not have 0 bytes in the middle, and return an error if it
45 /// finds one.
46 ///
47 /// # Extracting a raw pointer to the whole C string
48 ///
49 /// `CString` implements an [`as_ptr`][`CStr::as_ptr`] method through the [`Deref`]
50 /// trait. This method will give you a `*const c_char` which you can
51 /// feed directly to extern functions that expect a nul-terminated
52 /// string, like C's `strdup()`. Notice that [`as_ptr`][`CStr::as_ptr`] returns a
53 /// read-only pointer; if the C code writes to it, that causes
54 /// undefined behavior.
55 ///
56 /// # Extracting a slice of the whole C string
57 ///
58 /// Alternatively, you can obtain a <code>&[[u8]]</code> slice from a
59 /// `CString` with the [`CString::as_bytes`] method. Slices produced in this
60 /// way do *not* contain the trailing nul terminator. This is useful
61 /// when you will be calling an extern function that takes a `*const
62 /// u8` argument which is not necessarily nul-terminated, plus another
63 /// argument with the length of the string — like C's `strndup()`.
64 /// You can of course get the slice's length with its
65 /// [`len`][slice::len] method.
66 ///
67 /// If you need a <code>&[[u8]]</code> slice *with* the nul terminator, you
68 /// can use [`CString::as_bytes_with_nul`] instead.
69 ///
70 /// Once you have the kind of slice you need (with or without a nul
71 /// terminator), you can call the slice's own
72 /// [`as_ptr`][slice::as_ptr] method to get a read-only raw pointer to pass to
73 /// extern functions. See the documentation for that function for a
74 /// discussion on ensuring the lifetime of the raw pointer.
75 ///
76 /// [str]: prim@str "str"
77 /// [`Deref`]: ops::Deref
78 ///
79 /// # Examples
80 ///
81 /// ```ignore (extern-declaration)
82 /// # fn main() {
83 /// use std::ffi::CString;
84 /// use std::os::raw::c_char;
85 ///
86 /// extern "C" {
87 ///     fn my_printer(s: *const c_char);
88 /// }
89 ///
90 /// // We are certain that our string doesn't have 0 bytes in the middle,
91 /// // so we can .expect()
92 /// let c_to_print = CString::new("Hello, world!").expect("CString::new failed");
93 /// unsafe {
94 ///     my_printer(c_to_print.as_ptr());
95 /// }
96 /// # }
97 /// ```
98 ///
99 /// # Safety
100 ///
101 /// `CString` is intended for working with traditional C-style strings
102 /// (a sequence of non-nul bytes terminated by a single nul byte); the
103 /// primary use case for these kinds of strings is interoperating with C-like
104 /// code. Often you will need to transfer ownership to/from that external
105 /// code. It is strongly recommended that you thoroughly read through the
106 /// documentation of `CString` before use, as improper ownership management
107 /// of `CString` instances can lead to invalid memory accesses, memory leaks,
108 /// and other memory errors.
109 #[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
110 #[cfg_attr(not(test), rustc_diagnostic_item = "cstring_type")]
111 #[stable(feature = "rust1", since = "1.0.0")]
112 pub struct CString {
113     // Invariant 1: the slice ends with a zero byte and has a length of at least one.
114     // Invariant 2: the slice contains only one zero byte.
115     // Improper usage of unsafe function can break Invariant 2, but not Invariant 1.
116     inner: Box<[u8]>,
117 }
118
119 /// Representation of a borrowed C string.
120 ///
121 /// This type represents a borrowed reference to a nul-terminated
122 /// array of bytes. It can be constructed safely from a <code>&[[u8]]</code>
123 /// slice, or unsafely from a raw `*const c_char`. It can then be
124 /// converted to a Rust <code>&[str]</code> by performing UTF-8 validation, or
125 /// into an owned [`CString`].
126 ///
127 /// `&CStr` is to [`CString`] as <code>&[str]</code> is to [`String`]: the former
128 /// in each pair are borrowed references; the latter are owned
129 /// strings.
130 ///
131 /// Note that this structure is **not** `repr(C)` and is not recommended to be
132 /// placed in the signatures of FFI functions. Instead, safe wrappers of FFI
133 /// functions may leverage the unsafe [`CStr::from_ptr`] constructor to provide
134 /// a safe interface to other consumers.
135 ///
136 /// # Examples
137 ///
138 /// Inspecting a foreign C string:
139 ///
140 /// ```ignore (extern-declaration)
141 /// use std::ffi::CStr;
142 /// use std::os::raw::c_char;
143 ///
144 /// extern "C" { fn my_string() -> *const c_char; }
145 ///
146 /// unsafe {
147 ///     let slice = CStr::from_ptr(my_string());
148 ///     println!("string buffer size without nul terminator: {}", slice.to_bytes().len());
149 /// }
150 /// ```
151 ///
152 /// Passing a Rust-originating C string:
153 ///
154 /// ```ignore (extern-declaration)
155 /// use std::ffi::{CString, CStr};
156 /// use std::os::raw::c_char;
157 ///
158 /// fn work(data: &CStr) {
159 ///     extern "C" { fn work_with(data: *const c_char); }
160 ///
161 ///     unsafe { work_with(data.as_ptr()) }
162 /// }
163 ///
164 /// let s = CString::new("data data data data").expect("CString::new failed");
165 /// work(&s);
166 /// ```
167 ///
168 /// Converting a foreign C string into a Rust [`String`]:
169 ///
170 /// ```ignore (extern-declaration)
171 /// use std::ffi::CStr;
172 /// use std::os::raw::c_char;
173 ///
174 /// extern "C" { fn my_string() -> *const c_char; }
175 ///
176 /// fn my_string_safe() -> String {
177 ///     unsafe {
178 ///         CStr::from_ptr(my_string()).to_string_lossy().into_owned()
179 ///     }
180 /// }
181 ///
182 /// println!("string: {}", my_string_safe());
183 /// ```
184 ///
185 /// [str]: prim@str "str"
186 #[derive(Hash)]
187 #[cfg_attr(not(test), rustc_diagnostic_item = "CStr")]
188 #[stable(feature = "rust1", since = "1.0.0")]
189 // FIXME:
190 // `fn from` in `impl From<&CStr> for Box<CStr>` current implementation relies
191 // on `CStr` being layout-compatible with `[u8]`.
192 // When attribute privacy is implemented, `CStr` should be annotated as `#[repr(transparent)]`.
193 // Anyway, `CStr` representation and layout are considered implementation detail, are
194 // not documented and must not be relied upon.
195 pub struct CStr {
196     // FIXME: this should not be represented with a DST slice but rather with
197     //        just a raw `c_char` along with some form of marker to make
198     //        this an unsized type. Essentially `sizeof(&CStr)` should be the
199     //        same as `sizeof(&c_char)` but `CStr` should be an unsized type.
200     inner: [c_char],
201 }
202
203 /// An error indicating that an interior nul byte was found.
204 ///
205 /// While Rust strings may contain nul bytes in the middle, C strings
206 /// can't, as that byte would effectively truncate the string.
207 ///
208 /// This error is created by the [`new`][`CString::new`] method on
209 /// [`CString`]. See its documentation for more.
210 ///
211 /// # Examples
212 ///
213 /// ```
214 /// use std::ffi::{CString, NulError};
215 ///
216 /// let _: NulError = CString::new(b"f\0oo".to_vec()).unwrap_err();
217 /// ```
218 #[derive(Clone, PartialEq, Eq, Debug)]
219 #[stable(feature = "rust1", since = "1.0.0")]
220 pub struct NulError(usize, Vec<u8>);
221
222 /// An error indicating that a nul byte was not in the expected position.
223 ///
224 /// The slice used to create a [`CStr`] must have one and only one nul byte,
225 /// positioned at the end.
226 ///
227 /// This error is created by the [`CStr::from_bytes_with_nul`] method.
228 /// See its documentation for more.
229 ///
230 /// # Examples
231 ///
232 /// ```
233 /// use std::ffi::{CStr, FromBytesWithNulError};
234 ///
235 /// let _: FromBytesWithNulError = CStr::from_bytes_with_nul(b"f\0oo").unwrap_err();
236 /// ```
237 #[derive(Clone, PartialEq, Eq, Debug)]
238 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
239 pub struct FromBytesWithNulError {
240     kind: FromBytesWithNulErrorKind,
241 }
242
243 /// An error indicating that a nul byte was not in the expected position.
244 ///
245 /// The vector used to create a [`CString`] must have one and only one nul byte,
246 /// positioned at the end.
247 ///
248 /// This error is created by the [`CString::from_vec_with_nul`] method.
249 /// See its documentation for more.
250 ///
251 /// # Examples
252 ///
253 /// ```
254 /// #![feature(cstring_from_vec_with_nul)]
255 /// use std::ffi::{CString, FromVecWithNulError};
256 ///
257 /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"f\0oo".to_vec()).unwrap_err();
258 /// ```
259 #[derive(Clone, PartialEq, Eq, Debug)]
260 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
261 pub struct FromVecWithNulError {
262     error_kind: FromBytesWithNulErrorKind,
263     bytes: Vec<u8>,
264 }
265
266 #[derive(Clone, PartialEq, Eq, Debug)]
267 enum FromBytesWithNulErrorKind {
268     InteriorNul(usize),
269     NotNulTerminated,
270 }
271
272 impl FromBytesWithNulError {
273     fn interior_nul(pos: usize) -> FromBytesWithNulError {
274         FromBytesWithNulError { kind: FromBytesWithNulErrorKind::InteriorNul(pos) }
275     }
276     fn not_nul_terminated() -> FromBytesWithNulError {
277         FromBytesWithNulError { kind: FromBytesWithNulErrorKind::NotNulTerminated }
278     }
279 }
280
281 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
282 impl FromVecWithNulError {
283     /// Returns a slice of [`u8`]s bytes that were attempted to convert to a [`CString`].
284     ///
285     /// # Examples
286     ///
287     /// Basic usage:
288     ///
289     /// ```
290     /// #![feature(cstring_from_vec_with_nul)]
291     /// use std::ffi::CString;
292     ///
293     /// // Some invalid bytes in a vector
294     /// let bytes = b"f\0oo".to_vec();
295     ///
296     /// let value = CString::from_vec_with_nul(bytes.clone());
297     ///
298     /// assert_eq!(&bytes[..], value.unwrap_err().as_bytes());
299     /// ```
300     pub fn as_bytes(&self) -> &[u8] {
301         &self.bytes[..]
302     }
303
304     /// Returns the bytes that were attempted to convert to a [`CString`].
305     ///
306     /// This method is carefully constructed to avoid allocation. It will
307     /// consume the error, moving out the bytes, so that a copy of the bytes
308     /// does not need to be made.
309     ///
310     /// # Examples
311     ///
312     /// Basic usage:
313     ///
314     /// ```
315     /// #![feature(cstring_from_vec_with_nul)]
316     /// use std::ffi::CString;
317     ///
318     /// // Some invalid bytes in a vector
319     /// let bytes = b"f\0oo".to_vec();
320     ///
321     /// let value = CString::from_vec_with_nul(bytes.clone());
322     ///
323     /// assert_eq!(bytes, value.unwrap_err().into_bytes());
324     /// ```
325     pub fn into_bytes(self) -> Vec<u8> {
326         self.bytes
327     }
328 }
329
330 /// An error indicating invalid UTF-8 when converting a [`CString`] into a [`String`].
331 ///
332 /// `CString` is just a wrapper over a buffer of bytes with a nul terminator;
333 /// [`CString::into_string`] performs UTF-8 validation on those bytes and may
334 /// return this error.
335 ///
336 /// This `struct` is created by [`CString::into_string()`]. See
337 /// its documentation for more.
338 #[derive(Clone, PartialEq, Eq, Debug)]
339 #[stable(feature = "cstring_into", since = "1.7.0")]
340 pub struct IntoStringError {
341     inner: CString,
342     error: Utf8Error,
343 }
344
345 impl CString {
346     /// Creates a new C-compatible string from a container of bytes.
347     ///
348     /// This function will consume the provided data and use the
349     /// underlying bytes to construct a new string, ensuring that
350     /// there is a trailing 0 byte. This trailing 0 byte will be
351     /// appended by this function; the provided data should *not*
352     /// contain any 0 bytes in it.
353     ///
354     /// # Examples
355     ///
356     /// ```ignore (extern-declaration)
357     /// use std::ffi::CString;
358     /// use std::os::raw::c_char;
359     ///
360     /// extern "C" { fn puts(s: *const c_char); }
361     ///
362     /// let to_print = CString::new("Hello!").expect("CString::new failed");
363     /// unsafe {
364     ///     puts(to_print.as_ptr());
365     /// }
366     /// ```
367     ///
368     /// # Errors
369     ///
370     /// This function will return an error if the supplied bytes contain an
371     /// internal 0 byte. The [`NulError`] returned will contain the bytes as well as
372     /// the position of the nul byte.
373     #[stable(feature = "rust1", since = "1.0.0")]
374     pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
375         trait SpecIntoVec {
376             fn into_vec(self) -> Vec<u8>;
377         }
378         impl<T: Into<Vec<u8>>> SpecIntoVec for T {
379             default fn into_vec(self) -> Vec<u8> {
380                 self.into()
381             }
382         }
383         // Specialization for avoiding reallocation.
384         impl SpecIntoVec for &'_ [u8] {
385             fn into_vec(self) -> Vec<u8> {
386                 let mut v = Vec::with_capacity(self.len() + 1);
387                 v.extend(self);
388                 v
389             }
390         }
391         impl SpecIntoVec for &'_ str {
392             fn into_vec(self) -> Vec<u8> {
393                 let mut v = Vec::with_capacity(self.len() + 1);
394                 v.extend(self.as_bytes());
395                 v
396             }
397         }
398
399         Self::_new(SpecIntoVec::into_vec(t))
400     }
401
402     fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
403         match memchr::memchr(0, &bytes) {
404             Some(i) => Err(NulError(i, bytes)),
405             None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
406         }
407     }
408
409     /// Creates a C-compatible string by consuming a byte vector,
410     /// without checking for interior 0 bytes.
411     ///
412     /// This method is equivalent to [`CString::new`] except that no runtime
413     /// assertion is made that `v` contains no 0 bytes, and it requires an
414     /// actual byte vector, not anything that can be converted to one with Into.
415     ///
416     /// # Examples
417     ///
418     /// ```
419     /// use std::ffi::CString;
420     ///
421     /// let raw = b"foo".to_vec();
422     /// unsafe {
423     ///     let c_string = CString::from_vec_unchecked(raw);
424     /// }
425     /// ```
426     #[stable(feature = "rust1", since = "1.0.0")]
427     pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
428         v.reserve_exact(1);
429         v.push(0);
430         CString { inner: v.into_boxed_slice() }
431     }
432
433     /// Retakes ownership of a `CString` that was transferred to C via
434     /// [`CString::into_raw`].
435     ///
436     /// Additionally, the length of the string will be recalculated from the pointer.
437     ///
438     /// # Safety
439     ///
440     /// This should only ever be called with a pointer that was earlier
441     /// obtained by calling [`CString::into_raw`]. Other usage (e.g., trying to take
442     /// ownership of a string that was allocated by foreign code) is likely to lead
443     /// to undefined behavior or allocator corruption.
444     ///
445     /// It should be noted that the length isn't just "recomputed," but that
446     /// the recomputed length must match the original length from the
447     /// [`CString::into_raw`] call. This means the [`CString::into_raw`]/`from_raw`
448     /// methods should not be used when passing the string to C functions that can
449     /// modify the string's length.
450     ///
451     /// > **Note:** If you need to borrow a string that was allocated by
452     /// > foreign code, use [`CStr`]. If you need to take ownership of
453     /// > a string that was allocated by foreign code, you will need to
454     /// > make your own provisions for freeing it appropriately, likely
455     /// > with the foreign code's API to do that.
456     ///
457     /// # Examples
458     ///
459     /// Creates a `CString`, pass ownership to an `extern` function (via raw pointer), then retake
460     /// ownership with `from_raw`:
461     ///
462     /// ```ignore (extern-declaration)
463     /// use std::ffi::CString;
464     /// use std::os::raw::c_char;
465     ///
466     /// extern "C" {
467     ///     fn some_extern_function(s: *mut c_char);
468     /// }
469     ///
470     /// let c_string = CString::new("Hello!").expect("CString::new failed");
471     /// let raw = c_string.into_raw();
472     /// unsafe {
473     ///     some_extern_function(raw);
474     ///     let c_string = CString::from_raw(raw);
475     /// }
476     /// ```
477     #[stable(feature = "cstr_memory", since = "1.4.0")]
478     pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
479         // SAFETY: This is called with a pointer that was obtained from a call
480         // to `CString::into_raw` and the length has not been modified. As such,
481         // we know there is a NUL byte (and only one) at the end and that the
482         // information about the size of the allocation is correct on Rust's
483         // side.
484         unsafe {
485             let len = sys::strlen(ptr) + 1; // Including the NUL byte
486             let slice = slice::from_raw_parts_mut(ptr, len as usize);
487             CString { inner: Box::from_raw(slice as *mut [c_char] as *mut [u8]) }
488         }
489     }
490
491     /// Consumes the `CString` and transfers ownership of the string to a C caller.
492     ///
493     /// The pointer which this function returns must be returned to Rust and reconstituted using
494     /// [`CString::from_raw`] to be properly deallocated. Specifically, one
495     /// should *not* use the standard C `free()` function to deallocate
496     /// this string.
497     ///
498     /// Failure to call [`CString::from_raw`] will lead to a memory leak.
499     ///
500     /// The C side must **not** modify the length of the string (by writing a
501     /// `null` somewhere inside the string or removing the final one) before
502     /// it makes it back into Rust using [`CString::from_raw`]. See the safety section
503     /// in [`CString::from_raw`].
504     ///
505     /// # Examples
506     ///
507     /// ```
508     /// use std::ffi::CString;
509     ///
510     /// let c_string = CString::new("foo").expect("CString::new failed");
511     ///
512     /// let ptr = c_string.into_raw();
513     ///
514     /// unsafe {
515     ///     assert_eq!(b'f', *ptr as u8);
516     ///     assert_eq!(b'o', *ptr.offset(1) as u8);
517     ///     assert_eq!(b'o', *ptr.offset(2) as u8);
518     ///     assert_eq!(b'\0', *ptr.offset(3) as u8);
519     ///
520     ///     // retake pointer to free memory
521     ///     let _ = CString::from_raw(ptr);
522     /// }
523     /// ```
524     #[inline]
525     #[stable(feature = "cstr_memory", since = "1.4.0")]
526     pub fn into_raw(self) -> *mut c_char {
527         Box::into_raw(self.into_inner()) as *mut c_char
528     }
529
530     /// Converts the `CString` into a [`String`] if it contains valid UTF-8 data.
531     ///
532     /// On failure, ownership of the original `CString` is returned.
533     ///
534     /// # Examples
535     ///
536     /// ```
537     /// use std::ffi::CString;
538     ///
539     /// let valid_utf8 = vec![b'f', b'o', b'o'];
540     /// let cstring = CString::new(valid_utf8).expect("CString::new failed");
541     /// assert_eq!(cstring.into_string().expect("into_string() call failed"), "foo");
542     ///
543     /// let invalid_utf8 = vec![b'f', 0xff, b'o', b'o'];
544     /// let cstring = CString::new(invalid_utf8).expect("CString::new failed");
545     /// let err = cstring.into_string().err().expect("into_string().err() failed");
546     /// assert_eq!(err.utf8_error().valid_up_to(), 1);
547     /// ```
548
549     #[stable(feature = "cstring_into", since = "1.7.0")]
550     pub fn into_string(self) -> Result<String, IntoStringError> {
551         String::from_utf8(self.into_bytes()).map_err(|e| IntoStringError {
552             error: e.utf8_error(),
553             inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
554         })
555     }
556
557     /// Consumes the `CString` and returns the underlying byte buffer.
558     ///
559     /// The returned buffer does **not** contain the trailing nul
560     /// terminator, and it is guaranteed to not have any interior nul
561     /// bytes.
562     ///
563     /// # Examples
564     ///
565     /// ```
566     /// use std::ffi::CString;
567     ///
568     /// let c_string = CString::new("foo").expect("CString::new failed");
569     /// let bytes = c_string.into_bytes();
570     /// assert_eq!(bytes, vec![b'f', b'o', b'o']);
571     /// ```
572     #[stable(feature = "cstring_into", since = "1.7.0")]
573     pub fn into_bytes(self) -> Vec<u8> {
574         let mut vec = self.into_inner().into_vec();
575         let _nul = vec.pop();
576         debug_assert_eq!(_nul, Some(0u8));
577         vec
578     }
579
580     /// Equivalent to [`CString::into_bytes()`] except that the
581     /// returned vector includes the trailing nul terminator.
582     ///
583     /// # Examples
584     ///
585     /// ```
586     /// use std::ffi::CString;
587     ///
588     /// let c_string = CString::new("foo").expect("CString::new failed");
589     /// let bytes = c_string.into_bytes_with_nul();
590     /// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
591     /// ```
592     #[stable(feature = "cstring_into", since = "1.7.0")]
593     pub fn into_bytes_with_nul(self) -> Vec<u8> {
594         self.into_inner().into_vec()
595     }
596
597     /// Returns the contents of this `CString` as a slice of bytes.
598     ///
599     /// The returned slice does **not** contain the trailing nul
600     /// terminator, and it is guaranteed to not have any interior nul
601     /// bytes. If you need the nul terminator, use
602     /// [`CString::as_bytes_with_nul`] instead.
603     ///
604     /// # Examples
605     ///
606     /// ```
607     /// use std::ffi::CString;
608     ///
609     /// let c_string = CString::new("foo").expect("CString::new failed");
610     /// let bytes = c_string.as_bytes();
611     /// assert_eq!(bytes, &[b'f', b'o', b'o']);
612     /// ```
613     #[inline]
614     #[stable(feature = "rust1", since = "1.0.0")]
615     pub fn as_bytes(&self) -> &[u8] {
616         // SAFETY: CString has a length at least 1
617         unsafe { self.inner.get_unchecked(..self.inner.len() - 1) }
618     }
619
620     /// Equivalent to [`CString::as_bytes()`] except that the
621     /// returned slice includes the trailing nul terminator.
622     ///
623     /// # Examples
624     ///
625     /// ```
626     /// use std::ffi::CString;
627     ///
628     /// let c_string = CString::new("foo").expect("CString::new failed");
629     /// let bytes = c_string.as_bytes_with_nul();
630     /// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
631     /// ```
632     #[inline]
633     #[stable(feature = "rust1", since = "1.0.0")]
634     pub fn as_bytes_with_nul(&self) -> &[u8] {
635         &self.inner
636     }
637
638     /// Extracts a [`CStr`] slice containing the entire string.
639     ///
640     /// # Examples
641     ///
642     /// ```
643     /// use std::ffi::{CString, CStr};
644     ///
645     /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
646     /// let cstr = c_string.as_c_str();
647     /// assert_eq!(cstr,
648     ///            CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
649     /// ```
650     #[inline]
651     #[stable(feature = "as_c_str", since = "1.20.0")]
652     pub fn as_c_str(&self) -> &CStr {
653         &*self
654     }
655
656     /// Converts this `CString` into a boxed [`CStr`].
657     ///
658     /// # Examples
659     ///
660     /// ```
661     /// use std::ffi::{CString, CStr};
662     ///
663     /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
664     /// let boxed = c_string.into_boxed_c_str();
665     /// assert_eq!(&*boxed,
666     ///            CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
667     /// ```
668     #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
669     pub fn into_boxed_c_str(self) -> Box<CStr> {
670         unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) }
671     }
672
673     /// Bypass "move out of struct which implements [`Drop`] trait" restriction.
674     #[inline]
675     fn into_inner(self) -> Box<[u8]> {
676         // Rationale: `mem::forget(self)` invalidates the previous call to `ptr::read(&self.inner)`
677         // so we use `ManuallyDrop` to ensure `self` is not dropped.
678         // Then we can return the box directly without invalidating it.
679         // See https://github.com/rust-lang/rust/issues/62553.
680         let this = mem::ManuallyDrop::new(self);
681         unsafe { ptr::read(&this.inner) }
682     }
683
684     /// Converts a <code>[Vec]<[u8]></code> to a [`CString`] without checking the
685     /// invariants on the given [`Vec`].
686     ///
687     /// # Safety
688     ///
689     /// The given [`Vec`] **must** have one nul byte as its last element.
690     /// This means it cannot be empty nor have any other nul byte anywhere else.
691     ///
692     /// # Example
693     ///
694     /// ```
695     /// #![feature(cstring_from_vec_with_nul)]
696     /// use std::ffi::CString;
697     /// assert_eq!(
698     ///     unsafe { CString::from_vec_with_nul_unchecked(b"abc\0".to_vec()) },
699     ///     unsafe { CString::from_vec_unchecked(b"abc".to_vec()) }
700     /// );
701     /// ```
702     #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
703     pub unsafe fn from_vec_with_nul_unchecked(v: Vec<u8>) -> Self {
704         Self { inner: v.into_boxed_slice() }
705     }
706
707     /// Attempts to converts a <code>[Vec]<[u8]></code> to a [`CString`].
708     ///
709     /// Runtime checks are present to ensure there is only one nul byte in the
710     /// [`Vec`], its last element.
711     ///
712     /// # Errors
713     ///
714     /// If a nul byte is present and not the last element or no nul bytes
715     /// is present, an error will be returned.
716     ///
717     /// # Examples
718     ///
719     /// A successful conversion will produce the same result as [`CString::new`]
720     /// when called without the ending nul byte.
721     ///
722     /// ```
723     /// #![feature(cstring_from_vec_with_nul)]
724     /// use std::ffi::CString;
725     /// assert_eq!(
726     ///     CString::from_vec_with_nul(b"abc\0".to_vec())
727     ///         .expect("CString::from_vec_with_nul failed"),
728     ///     CString::new(b"abc".to_vec()).expect("CString::new failed")
729     /// );
730     /// ```
731     ///
732     /// An incorrectly formatted [`Vec`] will produce an error.
733     ///
734     /// ```
735     /// #![feature(cstring_from_vec_with_nul)]
736     /// use std::ffi::{CString, FromVecWithNulError};
737     /// // Interior nul byte
738     /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"a\0bc".to_vec()).unwrap_err();
739     /// // No nul byte
740     /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"abc".to_vec()).unwrap_err();
741     /// ```
742     #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
743     pub fn from_vec_with_nul(v: Vec<u8>) -> Result<Self, FromVecWithNulError> {
744         let nul_pos = memchr::memchr(0, &v);
745         match nul_pos {
746             Some(nul_pos) if nul_pos + 1 == v.len() => {
747                 // SAFETY: We know there is only one nul byte, at the end
748                 // of the vec.
749                 Ok(unsafe { Self::from_vec_with_nul_unchecked(v) })
750             }
751             Some(nul_pos) => Err(FromVecWithNulError {
752                 error_kind: FromBytesWithNulErrorKind::InteriorNul(nul_pos),
753                 bytes: v,
754             }),
755             None => Err(FromVecWithNulError {
756                 error_kind: FromBytesWithNulErrorKind::NotNulTerminated,
757                 bytes: v,
758             }),
759         }
760     }
761 }
762
763 // Turns this `CString` into an empty string to prevent
764 // memory-unsafe code from working by accident. Inline
765 // to prevent LLVM from optimizing it away in debug builds.
766 #[stable(feature = "cstring_drop", since = "1.13.0")]
767 impl Drop for CString {
768     #[inline]
769     fn drop(&mut self) {
770         unsafe {
771             *self.inner.get_unchecked_mut(0) = 0;
772         }
773     }
774 }
775
776 #[stable(feature = "rust1", since = "1.0.0")]
777 impl ops::Deref for CString {
778     type Target = CStr;
779
780     #[inline]
781     fn deref(&self) -> &CStr {
782         unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
783     }
784 }
785
786 #[stable(feature = "rust1", since = "1.0.0")]
787 impl fmt::Debug for CString {
788     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
789         fmt::Debug::fmt(&**self, f)
790     }
791 }
792
793 #[stable(feature = "cstring_into", since = "1.7.0")]
794 impl From<CString> for Vec<u8> {
795     /// Converts a [`CString`] into a <code>[Vec]<[u8]></code>.
796     ///
797     /// The conversion consumes the [`CString`], and removes the terminating NUL byte.
798     #[inline]
799     fn from(s: CString) -> Vec<u8> {
800         s.into_bytes()
801     }
802 }
803
804 #[stable(feature = "cstr_debug", since = "1.3.0")]
805 impl fmt::Debug for CStr {
806     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
807         write!(f, "\"")?;
808         for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
809             f.write_char(byte as char)?;
810         }
811         write!(f, "\"")
812     }
813 }
814
815 #[stable(feature = "cstr_default", since = "1.10.0")]
816 impl Default for &CStr {
817     fn default() -> Self {
818         const SLICE: &[c_char] = &[0];
819         unsafe { CStr::from_ptr(SLICE.as_ptr()) }
820     }
821 }
822
823 #[stable(feature = "cstr_default", since = "1.10.0")]
824 impl Default for CString {
825     /// Creates an empty `CString`.
826     fn default() -> CString {
827         let a: &CStr = Default::default();
828         a.to_owned()
829     }
830 }
831
832 #[stable(feature = "cstr_borrow", since = "1.3.0")]
833 impl Borrow<CStr> for CString {
834     #[inline]
835     fn borrow(&self) -> &CStr {
836         self
837     }
838 }
839
840 #[stable(feature = "cstring_from_cow_cstr", since = "1.28.0")]
841 impl<'a> From<Cow<'a, CStr>> for CString {
842     #[inline]
843     fn from(s: Cow<'a, CStr>) -> Self {
844         s.into_owned()
845     }
846 }
847
848 #[stable(feature = "box_from_c_str", since = "1.17.0")]
849 impl From<&CStr> for Box<CStr> {
850     fn from(s: &CStr) -> Box<CStr> {
851         let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul());
852         unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
853     }
854 }
855
856 #[stable(feature = "box_from_cow", since = "1.45.0")]
857 impl From<Cow<'_, CStr>> for Box<CStr> {
858     #[inline]
859     fn from(cow: Cow<'_, CStr>) -> Box<CStr> {
860         match cow {
861             Cow::Borrowed(s) => Box::from(s),
862             Cow::Owned(s) => Box::from(s),
863         }
864     }
865 }
866
867 #[stable(feature = "c_string_from_box", since = "1.18.0")]
868 impl From<Box<CStr>> for CString {
869     /// Converts a <code>[Box]<[CStr]></code> into a [`CString`] without copying or allocating.
870     #[inline]
871     fn from(s: Box<CStr>) -> CString {
872         s.into_c_string()
873     }
874 }
875
876 #[stable(feature = "cstring_from_vec_of_nonzerou8", since = "1.43.0")]
877 impl From<Vec<NonZeroU8>> for CString {
878     /// Converts a <code>[Vec]<[NonZeroU8]></code> into a [`CString`] without
879     /// copying nor checking for inner null bytes.
880     #[inline]
881     fn from(v: Vec<NonZeroU8>) -> CString {
882         unsafe {
883             // Transmute `Vec<NonZeroU8>` to `Vec<u8>`.
884             let v: Vec<u8> = {
885                 // SAFETY:
886                 //   - transmuting between `NonZeroU8` and `u8` is sound;
887                 //   - `alloc::Layout<NonZeroU8> == alloc::Layout<u8>`.
888                 let (ptr, len, cap): (*mut NonZeroU8, _, _) = Vec::into_raw_parts(v);
889                 Vec::from_raw_parts(ptr.cast::<u8>(), len, cap)
890             };
891             // SAFETY: `v` cannot contain null bytes, given the type-level
892             // invariant of `NonZeroU8`.
893             CString::from_vec_unchecked(v)
894         }
895     }
896 }
897
898 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
899 impl Clone for Box<CStr> {
900     #[inline]
901     fn clone(&self) -> Self {
902         (**self).into()
903     }
904 }
905
906 #[stable(feature = "box_from_c_string", since = "1.20.0")]
907 impl From<CString> for Box<CStr> {
908     /// Converts a [`CString`] into a <code>[Box]<[CStr]></code> without copying or allocating.
909     #[inline]
910     fn from(s: CString) -> Box<CStr> {
911         s.into_boxed_c_str()
912     }
913 }
914
915 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
916 impl<'a> From<CString> for Cow<'a, CStr> {
917     /// Converts a [`CString`] into an owned [`Cow`] without copying or allocating.
918     #[inline]
919     fn from(s: CString) -> Cow<'a, CStr> {
920         Cow::Owned(s)
921     }
922 }
923
924 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
925 impl<'a> From<&'a CStr> for Cow<'a, CStr> {
926     /// Converts a [`CStr`] into a borrowed [`Cow`] without copying or allocating.
927     #[inline]
928     fn from(s: &'a CStr) -> Cow<'a, CStr> {
929         Cow::Borrowed(s)
930     }
931 }
932
933 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
934 impl<'a> From<&'a CString> for Cow<'a, CStr> {
935     /// Converts a `&`[`CString`] into a borrowed [`Cow`] without copying or allocating.
936     #[inline]
937     fn from(s: &'a CString) -> Cow<'a, CStr> {
938         Cow::Borrowed(s.as_c_str())
939     }
940 }
941
942 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
943 impl From<CString> for Arc<CStr> {
944     /// Converts a [`CString`] into an <code>[Arc]<[CStr]></code> without copying or allocating.
945     #[inline]
946     fn from(s: CString) -> Arc<CStr> {
947         let arc: Arc<[u8]> = Arc::from(s.into_inner());
948         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
949     }
950 }
951
952 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
953 impl From<&CStr> for Arc<CStr> {
954     #[inline]
955     fn from(s: &CStr) -> Arc<CStr> {
956         let arc: Arc<[u8]> = Arc::from(s.to_bytes_with_nul());
957         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
958     }
959 }
960
961 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
962 impl From<CString> for Rc<CStr> {
963     /// Converts a [`CString`] into an <code>[Rc]<[CStr]></code> without copying or allocating.
964     #[inline]
965     fn from(s: CString) -> Rc<CStr> {
966         let rc: Rc<[u8]> = Rc::from(s.into_inner());
967         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
968     }
969 }
970
971 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
972 impl From<&CStr> for Rc<CStr> {
973     #[inline]
974     fn from(s: &CStr) -> Rc<CStr> {
975         let rc: Rc<[u8]> = Rc::from(s.to_bytes_with_nul());
976         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
977     }
978 }
979
980 #[stable(feature = "default_box_extra", since = "1.17.0")]
981 impl Default for Box<CStr> {
982     fn default() -> Box<CStr> {
983         let boxed: Box<[u8]> = Box::from([0]);
984         unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
985     }
986 }
987
988 impl NulError {
989     /// Returns the position of the nul byte in the slice that caused
990     /// [`CString::new`] to fail.
991     ///
992     /// # Examples
993     ///
994     /// ```
995     /// use std::ffi::CString;
996     ///
997     /// let nul_error = CString::new("foo\0bar").unwrap_err();
998     /// assert_eq!(nul_error.nul_position(), 3);
999     ///
1000     /// let nul_error = CString::new("foo bar\0").unwrap_err();
1001     /// assert_eq!(nul_error.nul_position(), 7);
1002     /// ```
1003     #[stable(feature = "rust1", since = "1.0.0")]
1004     pub fn nul_position(&self) -> usize {
1005         self.0
1006     }
1007
1008     /// Consumes this error, returning the underlying vector of bytes which
1009     /// generated the error in the first place.
1010     ///
1011     /// # Examples
1012     ///
1013     /// ```
1014     /// use std::ffi::CString;
1015     ///
1016     /// let nul_error = CString::new("foo\0bar").unwrap_err();
1017     /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
1018     /// ```
1019     #[stable(feature = "rust1", since = "1.0.0")]
1020     pub fn into_vec(self) -> Vec<u8> {
1021         self.1
1022     }
1023 }
1024
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 impl Error for NulError {
1027     #[allow(deprecated)]
1028     fn description(&self) -> &str {
1029         "nul byte found in data"
1030     }
1031 }
1032
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 impl fmt::Display for NulError {
1035     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1036         write!(f, "nul byte found in provided data at position: {}", self.0)
1037     }
1038 }
1039
1040 #[stable(feature = "rust1", since = "1.0.0")]
1041 impl From<NulError> for io::Error {
1042     /// Converts a [`NulError`] into a [`io::Error`].
1043     fn from(_: NulError) -> io::Error {
1044         io::Error::new_const(io::ErrorKind::InvalidInput, &"data provided contains a nul byte")
1045     }
1046 }
1047
1048 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
1049 impl Error for FromBytesWithNulError {
1050     #[allow(deprecated)]
1051     fn description(&self) -> &str {
1052         match self.kind {
1053             FromBytesWithNulErrorKind::InteriorNul(..) => {
1054                 "data provided contains an interior nul byte"
1055             }
1056             FromBytesWithNulErrorKind::NotNulTerminated => "data provided is not nul terminated",
1057         }
1058     }
1059 }
1060
1061 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
1062 impl fmt::Display for FromBytesWithNulError {
1063     #[allow(deprecated, deprecated_in_future)]
1064     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1065         f.write_str(self.description())?;
1066         if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind {
1067             write!(f, " at byte pos {}", pos)?;
1068         }
1069         Ok(())
1070     }
1071 }
1072
1073 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
1074 impl Error for FromVecWithNulError {}
1075
1076 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
1077 impl fmt::Display for FromVecWithNulError {
1078     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1079         match self.error_kind {
1080             FromBytesWithNulErrorKind::InteriorNul(pos) => {
1081                 write!(f, "data provided contains an interior nul byte at pos {}", pos)
1082             }
1083             FromBytesWithNulErrorKind::NotNulTerminated => {
1084                 write!(f, "data provided is not nul terminated")
1085             }
1086         }
1087     }
1088 }
1089
1090 impl IntoStringError {
1091     /// Consumes this error, returning original [`CString`] which generated the
1092     /// error.
1093     #[stable(feature = "cstring_into", since = "1.7.0")]
1094     pub fn into_cstring(self) -> CString {
1095         self.inner
1096     }
1097
1098     /// Access the underlying UTF-8 error that was the cause of this error.
1099     #[stable(feature = "cstring_into", since = "1.7.0")]
1100     pub fn utf8_error(&self) -> Utf8Error {
1101         self.error
1102     }
1103 }
1104
1105 #[stable(feature = "cstring_into", since = "1.7.0")]
1106 impl Error for IntoStringError {
1107     #[allow(deprecated)]
1108     fn description(&self) -> &str {
1109         "C string contained non-utf8 bytes"
1110     }
1111
1112     fn source(&self) -> Option<&(dyn Error + 'static)> {
1113         Some(&self.error)
1114     }
1115 }
1116
1117 #[stable(feature = "cstring_into", since = "1.7.0")]
1118 impl fmt::Display for IntoStringError {
1119     #[allow(deprecated, deprecated_in_future)]
1120     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1121         self.description().fmt(f)
1122     }
1123 }
1124
1125 impl CStr {
1126     /// Wraps a raw C string with a safe C string wrapper.
1127     ///
1128     /// This function will wrap the provided `ptr` with a `CStr` wrapper, which
1129     /// allows inspection and interoperation of non-owned C strings. The total
1130     /// size of the raw C string must be smaller than `isize::MAX` **bytes**
1131     /// in memory due to calling the `slice::from_raw_parts` function.
1132     /// This method is unsafe for a number of reasons:
1133     ///
1134     /// * There is no guarantee to the validity of `ptr`.
1135     /// * The returned lifetime is not guaranteed to be the actual lifetime of
1136     ///   `ptr`.
1137     /// * There is no guarantee that the memory pointed to by `ptr` contains a
1138     ///   valid nul terminator byte at the end of the string.
1139     /// * It is not guaranteed that the memory pointed by `ptr` won't change
1140     ///   before the `CStr` has been destroyed.
1141     ///
1142     /// > **Note**: This operation is intended to be a 0-cost cast but it is
1143     /// > currently implemented with an up-front calculation of the length of
1144     /// > the string. This is not guaranteed to always be the case.
1145     ///
1146     /// # Examples
1147     ///
1148     /// ```ignore (extern-declaration)
1149     /// # fn main() {
1150     /// use std::ffi::CStr;
1151     /// use std::os::raw::c_char;
1152     ///
1153     /// extern "C" {
1154     ///     fn my_string() -> *const c_char;
1155     /// }
1156     ///
1157     /// unsafe {
1158     ///     let slice = CStr::from_ptr(my_string());
1159     ///     println!("string returned: {}", slice.to_str().unwrap());
1160     /// }
1161     /// # }
1162     /// ```
1163     #[stable(feature = "rust1", since = "1.0.0")]
1164     pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
1165         // SAFETY: The caller has provided a pointer that points to a valid C
1166         // string with a NUL terminator of size less than `isize::MAX`, whose
1167         // content remain valid and doesn't change for the lifetime of the
1168         // returned `CStr`.
1169         //
1170         // Thus computing the length is fine (a NUL byte exists), the call to
1171         // from_raw_parts is safe because we know the length is at most `isize::MAX`, meaning
1172         // the call to `from_bytes_with_nul_unchecked` is correct.
1173         //
1174         // The cast from c_char to u8 is ok because a c_char is always one byte.
1175         unsafe {
1176             let len = sys::strlen(ptr);
1177             let ptr = ptr as *const u8;
1178             CStr::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr, len as usize + 1))
1179         }
1180     }
1181
1182     /// Creates a C string wrapper from a byte slice.
1183     ///
1184     /// This function will cast the provided `bytes` to a `CStr`
1185     /// wrapper after ensuring that the byte slice is nul-terminated
1186     /// and does not contain any interior nul bytes.
1187     ///
1188     /// # Examples
1189     ///
1190     /// ```
1191     /// use std::ffi::CStr;
1192     ///
1193     /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
1194     /// assert!(cstr.is_ok());
1195     /// ```
1196     ///
1197     /// Creating a `CStr` without a trailing nul terminator is an error:
1198     ///
1199     /// ```
1200     /// use std::ffi::CStr;
1201     ///
1202     /// let cstr = CStr::from_bytes_with_nul(b"hello");
1203     /// assert!(cstr.is_err());
1204     /// ```
1205     ///
1206     /// Creating a `CStr` with an interior nul byte is an error:
1207     ///
1208     /// ```
1209     /// use std::ffi::CStr;
1210     ///
1211     /// let cstr = CStr::from_bytes_with_nul(b"he\0llo\0");
1212     /// assert!(cstr.is_err());
1213     /// ```
1214     #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
1215     pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError> {
1216         let nul_pos = memchr::memchr(0, bytes);
1217         if let Some(nul_pos) = nul_pos {
1218             if nul_pos + 1 != bytes.len() {
1219                 return Err(FromBytesWithNulError::interior_nul(nul_pos));
1220             }
1221             Ok(unsafe { CStr::from_bytes_with_nul_unchecked(bytes) })
1222         } else {
1223             Err(FromBytesWithNulError::not_nul_terminated())
1224         }
1225     }
1226
1227     /// Unsafely creates a C string wrapper from a byte slice.
1228     ///
1229     /// This function will cast the provided `bytes` to a `CStr` wrapper without
1230     /// performing any sanity checks. The provided slice **must** be nul-terminated
1231     /// and not contain any interior nul bytes.
1232     ///
1233     /// # Examples
1234     ///
1235     /// ```
1236     /// use std::ffi::{CStr, CString};
1237     ///
1238     /// unsafe {
1239     ///     let cstring = CString::new("hello").expect("CString::new failed");
1240     ///     let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
1241     ///     assert_eq!(cstr, &*cstring);
1242     /// }
1243     /// ```
1244     #[inline]
1245     #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
1246     #[rustc_const_unstable(feature = "const_cstr_unchecked", issue = "none")]
1247     pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
1248         // SAFETY: Casting to CStr is safe because its internal representation
1249         // is a [u8] too (safe only inside std).
1250         // Dereferencing the obtained pointer is safe because it comes from a
1251         // reference. Making a reference is then safe because its lifetime
1252         // is bound by the lifetime of the given `bytes`.
1253         unsafe { &*(bytes as *const [u8] as *const CStr) }
1254     }
1255
1256     /// Returns the inner pointer to this C string.
1257     ///
1258     /// The returned pointer will be valid for as long as `self` is, and points
1259     /// to a contiguous region of memory terminated with a 0 byte to represent
1260     /// the end of the string.
1261     ///
1262     /// **WARNING**
1263     ///
1264     /// The returned pointer is read-only; writing to it (including passing it
1265     /// to C code that writes to it) causes undefined behavior.
1266     ///
1267     /// It is your responsibility to make sure that the underlying memory is not
1268     /// freed too early. For example, the following code will cause undefined
1269     /// behavior when `ptr` is used inside the `unsafe` block:
1270     ///
1271     /// ```no_run
1272     /// # #![allow(unused_must_use)] #![allow(temporary_cstring_as_ptr)]
1273     /// use std::ffi::CString;
1274     ///
1275     /// let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
1276     /// unsafe {
1277     ///     // `ptr` is dangling
1278     ///     *ptr;
1279     /// }
1280     /// ```
1281     ///
1282     /// This happens because the pointer returned by `as_ptr` does not carry any
1283     /// lifetime information and the [`CString`] is deallocated immediately after
1284     /// the `CString::new("Hello").expect("CString::new failed").as_ptr()`
1285     /// expression is evaluated.
1286     /// To fix the problem, bind the `CString` to a local variable:
1287     ///
1288     /// ```no_run
1289     /// # #![allow(unused_must_use)]
1290     /// use std::ffi::CString;
1291     ///
1292     /// let hello = CString::new("Hello").expect("CString::new failed");
1293     /// let ptr = hello.as_ptr();
1294     /// unsafe {
1295     ///     // `ptr` is valid because `hello` is in scope
1296     ///     *ptr;
1297     /// }
1298     /// ```
1299     ///
1300     /// This way, the lifetime of the [`CString`] in `hello` encompasses
1301     /// the lifetime of `ptr` and the `unsafe` block.
1302     #[inline]
1303     #[stable(feature = "rust1", since = "1.0.0")]
1304     #[rustc_const_stable(feature = "const_str_as_ptr", since = "1.32.0")]
1305     pub const fn as_ptr(&self) -> *const c_char {
1306         self.inner.as_ptr()
1307     }
1308
1309     /// Converts this C string to a byte slice.
1310     ///
1311     /// The returned slice will **not** contain the trailing nul terminator that this C
1312     /// string has.
1313     ///
1314     /// > **Note**: This method is currently implemented as a constant-time
1315     /// > cast, but it is planned to alter its definition in the future to
1316     /// > perform the length calculation whenever this method is called.
1317     ///
1318     /// # Examples
1319     ///
1320     /// ```
1321     /// use std::ffi::CStr;
1322     ///
1323     /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1324     /// assert_eq!(cstr.to_bytes(), b"foo");
1325     /// ```
1326     #[inline]
1327     #[stable(feature = "rust1", since = "1.0.0")]
1328     pub fn to_bytes(&self) -> &[u8] {
1329         let bytes = self.to_bytes_with_nul();
1330         // SAFETY: to_bytes_with_nul returns slice with length at least 1
1331         unsafe { bytes.get_unchecked(..bytes.len() - 1) }
1332     }
1333
1334     /// Converts this C string to a byte slice containing the trailing 0 byte.
1335     ///
1336     /// This function is the equivalent of [`CStr::to_bytes`] except that it
1337     /// will retain the trailing nul terminator instead of chopping it off.
1338     ///
1339     /// > **Note**: This method is currently implemented as a 0-cost cast, but
1340     /// > it is planned to alter its definition in the future to perform the
1341     /// > length calculation whenever this method is called.
1342     ///
1343     /// # Examples
1344     ///
1345     /// ```
1346     /// use std::ffi::CStr;
1347     ///
1348     /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1349     /// assert_eq!(cstr.to_bytes_with_nul(), b"foo\0");
1350     /// ```
1351     #[inline]
1352     #[stable(feature = "rust1", since = "1.0.0")]
1353     pub fn to_bytes_with_nul(&self) -> &[u8] {
1354         unsafe { &*(&self.inner as *const [c_char] as *const [u8]) }
1355     }
1356
1357     /// Yields a <code>&[str]</code> slice if the `CStr` contains valid UTF-8.
1358     ///
1359     /// If the contents of the `CStr` are valid UTF-8 data, this
1360     /// function will return the corresponding <code>&[str]</code> slice. Otherwise,
1361     /// it will return an error with details of where UTF-8 validation failed.
1362     ///
1363     /// [str]: prim@str "str"
1364     ///
1365     /// # Examples
1366     ///
1367     /// ```
1368     /// use std::ffi::CStr;
1369     ///
1370     /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1371     /// assert_eq!(cstr.to_str(), Ok("foo"));
1372     /// ```
1373     #[stable(feature = "cstr_to_str", since = "1.4.0")]
1374     pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
1375         // N.B., when `CStr` is changed to perform the length check in `.to_bytes()`
1376         // instead of in `from_ptr()`, it may be worth considering if this should
1377         // be rewritten to do the UTF-8 check inline with the length calculation
1378         // instead of doing it afterwards.
1379         str::from_utf8(self.to_bytes())
1380     }
1381
1382     /// Converts a `CStr` into a <code>[Cow]<[str]></code>.
1383     ///
1384     /// If the contents of the `CStr` are valid UTF-8 data, this
1385     /// function will return a <code>[Cow]::[Borrowed]\(&[str])</code>
1386     /// with the corresponding <code>&[str]</code> slice. Otherwise, it will
1387     /// replace any invalid UTF-8 sequences with
1388     /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD] and return a
1389     /// <code>[Cow]::[Owned]\(&[str])</code> with the result.
1390     ///
1391     /// [str]: prim@str "str"
1392     /// [Borrowed]: Cow::Borrowed
1393     /// [Owned]: Cow::Owned
1394     /// [U+FFFD]: crate::char::REPLACEMENT_CHARACTER "std::char::REPLACEMENT_CHARACTER"
1395     ///
1396     /// # Examples
1397     ///
1398     /// Calling `to_string_lossy` on a `CStr` containing valid UTF-8:
1399     ///
1400     /// ```
1401     /// use std::borrow::Cow;
1402     /// use std::ffi::CStr;
1403     ///
1404     /// let cstr = CStr::from_bytes_with_nul(b"Hello World\0")
1405     ///                  .expect("CStr::from_bytes_with_nul failed");
1406     /// assert_eq!(cstr.to_string_lossy(), Cow::Borrowed("Hello World"));
1407     /// ```
1408     ///
1409     /// Calling `to_string_lossy` on a `CStr` containing invalid UTF-8:
1410     ///
1411     /// ```
1412     /// use std::borrow::Cow;
1413     /// use std::ffi::CStr;
1414     ///
1415     /// let cstr = CStr::from_bytes_with_nul(b"Hello \xF0\x90\x80World\0")
1416     ///                  .expect("CStr::from_bytes_with_nul failed");
1417     /// assert_eq!(
1418     ///     cstr.to_string_lossy(),
1419     ///     Cow::Owned(String::from("Hello �World")) as Cow<'_, str>
1420     /// );
1421     /// ```
1422     #[stable(feature = "cstr_to_str", since = "1.4.0")]
1423     pub fn to_string_lossy(&self) -> Cow<'_, str> {
1424         String::from_utf8_lossy(self.to_bytes())
1425     }
1426
1427     /// Converts a <code>[Box]<[CStr]></code> into a [`CString`] without copying or allocating.
1428     ///
1429     /// # Examples
1430     ///
1431     /// ```
1432     /// use std::ffi::CString;
1433     ///
1434     /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
1435     /// let boxed = c_string.into_boxed_c_str();
1436     /// assert_eq!(boxed.into_c_string(), CString::new("foo").expect("CString::new failed"));
1437     /// ```
1438     #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
1439     pub fn into_c_string(self: Box<CStr>) -> CString {
1440         let raw = Box::into_raw(self) as *mut [u8];
1441         CString { inner: unsafe { Box::from_raw(raw) } }
1442     }
1443 }
1444
1445 #[stable(feature = "rust1", since = "1.0.0")]
1446 impl PartialEq for CStr {
1447     fn eq(&self, other: &CStr) -> bool {
1448         self.to_bytes().eq(other.to_bytes())
1449     }
1450 }
1451 #[stable(feature = "rust1", since = "1.0.0")]
1452 impl Eq for CStr {}
1453 #[stable(feature = "rust1", since = "1.0.0")]
1454 impl PartialOrd for CStr {
1455     fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
1456         self.to_bytes().partial_cmp(&other.to_bytes())
1457     }
1458 }
1459 #[stable(feature = "rust1", since = "1.0.0")]
1460 impl Ord for CStr {
1461     fn cmp(&self, other: &CStr) -> Ordering {
1462         self.to_bytes().cmp(&other.to_bytes())
1463     }
1464 }
1465
1466 #[stable(feature = "cstr_borrow", since = "1.3.0")]
1467 impl ToOwned for CStr {
1468     type Owned = CString;
1469
1470     fn to_owned(&self) -> CString {
1471         CString { inner: self.to_bytes_with_nul().into() }
1472     }
1473
1474     fn clone_into(&self, target: &mut CString) {
1475         let mut b = Vec::from(mem::take(&mut target.inner));
1476         self.to_bytes_with_nul().clone_into(&mut b);
1477         target.inner = b.into_boxed_slice();
1478     }
1479 }
1480
1481 #[stable(feature = "cstring_asref", since = "1.7.0")]
1482 impl From<&CStr> for CString {
1483     fn from(s: &CStr) -> CString {
1484         s.to_owned()
1485     }
1486 }
1487
1488 #[stable(feature = "cstring_asref", since = "1.7.0")]
1489 impl ops::Index<ops::RangeFull> for CString {
1490     type Output = CStr;
1491
1492     #[inline]
1493     fn index(&self, _index: ops::RangeFull) -> &CStr {
1494         self
1495     }
1496 }
1497
1498 #[stable(feature = "cstr_range_from", since = "1.47.0")]
1499 impl ops::Index<ops::RangeFrom<usize>> for CStr {
1500     type Output = CStr;
1501
1502     fn index(&self, index: ops::RangeFrom<usize>) -> &CStr {
1503         let bytes = self.to_bytes_with_nul();
1504         // we need to manually check the starting index to account for the null
1505         // byte, since otherwise we could get an empty string that doesn't end
1506         // in a null.
1507         if index.start < bytes.len() {
1508             unsafe { CStr::from_bytes_with_nul_unchecked(&bytes[index.start..]) }
1509         } else {
1510             panic!(
1511                 "index out of bounds: the len is {} but the index is {}",
1512                 bytes.len(),
1513                 index.start
1514             );
1515         }
1516     }
1517 }
1518
1519 #[stable(feature = "cstring_asref", since = "1.7.0")]
1520 impl AsRef<CStr> for CStr {
1521     #[inline]
1522     fn as_ref(&self) -> &CStr {
1523         self
1524     }
1525 }
1526
1527 #[stable(feature = "cstring_asref", since = "1.7.0")]
1528 impl AsRef<CStr> for CString {
1529     #[inline]
1530     fn as_ref(&self) -> &CStr {
1531         self
1532     }
1533 }