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