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