]> git.lizzy.rs Git - rust.git/blob - src/libstd/ffi/c_str.rs
Add methods to go from a nul-terminated Vec<u8> to a CString, checked and unchecked.
[rust.git] / src / libstd / 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`] or the vector used to create a
238 /// [`CString`] must have one and only one nul byte, positioned at the end.
239 ///
240 /// This error is created by the
241 /// [`from_bytes_with_nul`][`CStr::from_bytes_with_nul`] method on
242 /// [`CStr`] or the [`from_vec_with_nul`][`CString::from_vec_with_nul`] method
243 /// on [`CString`]. See their documentation for more.
244 ///
245 /// [`CStr`]: struct.CStr.html
246 /// [`CStr::from_bytes_with_nul`]: struct.CStr.html#method.from_bytes_with_nul
247 /// [`CString`]: struct.CString.html
248 /// [`CString::from_vec_with_nul`]: struct.CString.html#method.from_vec_with_nul
249 ///
250 /// # Examples
251 ///
252 /// ```
253 /// use std::ffi::{CStr, FromBytesWithNulError};
254 ///
255 /// let _: FromBytesWithNulError = CStr::from_bytes_with_nul(b"f\0oo").unwrap_err();
256 /// ```
257 #[derive(Clone, PartialEq, Eq, Debug)]
258 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
259 pub struct FromBytesWithNulError {
260     kind: FromBytesWithNulErrorKind,
261 }
262
263 #[derive(Clone, PartialEq, Eq, Debug)]
264 enum FromBytesWithNulErrorKind {
265     InteriorNul(usize),
266     NotNulTerminated,
267 }
268
269 impl FromBytesWithNulError {
270     fn interior_nul(pos: usize) -> FromBytesWithNulError {
271         FromBytesWithNulError { kind: FromBytesWithNulErrorKind::InteriorNul(pos) }
272     }
273     fn not_nul_terminated() -> FromBytesWithNulError {
274         FromBytesWithNulError { kind: FromBytesWithNulErrorKind::NotNulTerminated }
275     }
276 }
277
278 /// An error indicating invalid UTF-8 when converting a [`CString`] into a [`String`].
279 ///
280 /// `CString` is just a wrapper over a buffer of bytes with a nul
281 /// terminator; [`into_string`][`CString::into_string`] performs UTF-8
282 /// validation on those bytes and may return this error.
283 ///
284 /// This `struct` is created by the
285 /// [`into_string`][`CString::into_string`] method on [`CString`]. See
286 /// its documentation for more.
287 ///
288 /// [`String`]: ../string/struct.String.html
289 /// [`CString`]: struct.CString.html
290 /// [`CString::into_string`]: struct.CString.html#method.into_string
291 #[derive(Clone, PartialEq, Eq, Debug)]
292 #[stable(feature = "cstring_into", since = "1.7.0")]
293 pub struct IntoStringError {
294     inner: CString,
295     error: Utf8Error,
296 }
297
298 impl CString {
299     /// Creates a new C-compatible string from a container of bytes.
300     ///
301     /// This function will consume the provided data and use the
302     /// underlying bytes to construct a new string, ensuring that
303     /// there is a trailing 0 byte. This trailing 0 byte will be
304     /// appended by this function; the provided data should *not*
305     /// contain any 0 bytes in it.
306     ///
307     /// # Examples
308     ///
309     /// ```ignore (extern-declaration)
310     /// use std::ffi::CString;
311     /// use std::os::raw::c_char;
312     ///
313     /// extern { fn puts(s: *const c_char); }
314     ///
315     /// let to_print = CString::new("Hello!").expect("CString::new failed");
316     /// unsafe {
317     ///     puts(to_print.as_ptr());
318     /// }
319     /// ```
320     ///
321     /// # Errors
322     ///
323     /// This function will return an error if the supplied bytes contain an
324     /// internal 0 byte. The [`NulError`] returned will contain the bytes as well as
325     /// the position of the nul byte.
326     ///
327     /// [`NulError`]: struct.NulError.html
328     #[stable(feature = "rust1", since = "1.0.0")]
329     pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
330         trait SpecIntoVec {
331             fn into_vec(self) -> Vec<u8>;
332         }
333         impl<T: Into<Vec<u8>>> SpecIntoVec for T {
334             default fn into_vec(self) -> Vec<u8> {
335                 self.into()
336             }
337         }
338         // Specialization for avoiding reallocation.
339         impl SpecIntoVec for &'_ [u8] {
340             fn into_vec(self) -> Vec<u8> {
341                 let mut v = Vec::with_capacity(self.len() + 1);
342                 v.extend(self);
343                 v
344             }
345         }
346         impl SpecIntoVec for &'_ str {
347             fn into_vec(self) -> Vec<u8> {
348                 let mut v = Vec::with_capacity(self.len() + 1);
349                 v.extend(self.as_bytes());
350                 v
351             }
352         }
353
354         Self::_new(SpecIntoVec::into_vec(t))
355     }
356
357     fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
358         match memchr::memchr(0, &bytes) {
359             Some(i) => Err(NulError(i, bytes)),
360             None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
361         }
362     }
363
364     /// Creates a C-compatible string by consuming a byte vector,
365     /// without checking for interior 0 bytes.
366     ///
367     /// This method is equivalent to [`new`] except that no runtime assertion
368     /// is made that `v` contains no 0 bytes, and it requires an actual
369     /// byte vector, not anything that can be converted to one with Into.
370     ///
371     /// [`new`]: #method.new
372     ///
373     /// # Examples
374     ///
375     /// ```
376     /// use std::ffi::CString;
377     ///
378     /// let raw = b"foo".to_vec();
379     /// unsafe {
380     ///     let c_string = CString::from_vec_unchecked(raw);
381     /// }
382     /// ```
383     #[stable(feature = "rust1", since = "1.0.0")]
384     pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
385         v.reserve_exact(1);
386         v.push(0);
387         CString { inner: v.into_boxed_slice() }
388     }
389
390     /// Retakes ownership of a `CString` that was transferred to C via [`into_raw`].
391     ///
392     /// Additionally, the length of the string will be recalculated from the pointer.
393     ///
394     /// # Safety
395     ///
396     /// This should only ever be called with a pointer that was earlier
397     /// obtained by calling [`into_raw`] on a `CString`. Other usage (e.g., trying to take
398     /// ownership of a string that was allocated by foreign code) is likely to lead
399     /// to undefined behavior or allocator corruption.
400     ///
401     /// > **Note:** If you need to borrow a string that was allocated by
402     /// > foreign code, use [`CStr`]. If you need to take ownership of
403     /// > a string that was allocated by foreign code, you will need to
404     /// > make your own provisions for freeing it appropriately, likely
405     /// > with the foreign code's API to do that.
406     ///
407     /// [`into_raw`]: #method.into_raw
408     /// [`CStr`]: struct.CStr.html
409     ///
410     /// # Examples
411     ///
412     /// Creates a `CString`, pass ownership to an `extern` function (via raw pointer), then retake
413     /// ownership with `from_raw`:
414     ///
415     /// ```ignore (extern-declaration)
416     /// use std::ffi::CString;
417     /// use std::os::raw::c_char;
418     ///
419     /// extern {
420     ///     fn some_extern_function(s: *mut c_char);
421     /// }
422     ///
423     /// let c_string = CString::new("Hello!").expect("CString::new failed");
424     /// let raw = c_string.into_raw();
425     /// unsafe {
426     ///     some_extern_function(raw);
427     ///     let c_string = CString::from_raw(raw);
428     /// }
429     /// ```
430     #[stable(feature = "cstr_memory", since = "1.4.0")]
431     pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
432         let len = sys::strlen(ptr) + 1; // Including the NUL byte
433         let slice = slice::from_raw_parts_mut(ptr, len as usize);
434         CString { inner: Box::from_raw(slice as *mut [c_char] as *mut [u8]) }
435     }
436
437     /// Consumes the `CString` and transfers ownership of the string to a C caller.
438     ///
439     /// The pointer which this function returns must be returned to Rust and reconstituted using
440     /// [`from_raw`] to be properly deallocated. Specifically, one
441     /// should *not* use the standard C `free()` function to deallocate
442     /// this string.
443     ///
444     /// Failure to call [`from_raw`] will lead to a memory leak.
445     ///
446     /// [`from_raw`]: #method.from_raw
447     ///
448     /// # Examples
449     ///
450     /// ```
451     /// use std::ffi::CString;
452     ///
453     /// let c_string = CString::new("foo").expect("CString::new failed");
454     ///
455     /// let ptr = c_string.into_raw();
456     ///
457     /// unsafe {
458     ///     assert_eq!(b'f', *ptr as u8);
459     ///     assert_eq!(b'o', *ptr.offset(1) as u8);
460     ///     assert_eq!(b'o', *ptr.offset(2) as u8);
461     ///     assert_eq!(b'\0', *ptr.offset(3) as u8);
462     ///
463     ///     // retake pointer to free memory
464     ///     let _ = CString::from_raw(ptr);
465     /// }
466     /// ```
467     #[inline]
468     #[stable(feature = "cstr_memory", since = "1.4.0")]
469     pub fn into_raw(self) -> *mut c_char {
470         Box::into_raw(self.into_inner()) as *mut c_char
471     }
472
473     /// Converts the `CString` into a [`String`] if it contains valid UTF-8 data.
474     ///
475     /// On failure, ownership of the original `CString` is returned.
476     ///
477     /// [`String`]: ../string/struct.String.html
478     ///
479     /// # Examples
480     ///
481     /// ```
482     /// use std::ffi::CString;
483     ///
484     /// let valid_utf8 = vec![b'f', b'o', b'o'];
485     /// let cstring = CString::new(valid_utf8).expect("CString::new failed");
486     /// assert_eq!(cstring.into_string().expect("into_string() call failed"), "foo");
487     ///
488     /// let invalid_utf8 = vec![b'f', 0xff, b'o', b'o'];
489     /// let cstring = CString::new(invalid_utf8).expect("CString::new failed");
490     /// let err = cstring.into_string().err().expect("into_string().err() failed");
491     /// assert_eq!(err.utf8_error().valid_up_to(), 1);
492     /// ```
493
494     #[stable(feature = "cstring_into", since = "1.7.0")]
495     pub fn into_string(self) -> Result<String, IntoStringError> {
496         String::from_utf8(self.into_bytes()).map_err(|e| IntoStringError {
497             error: e.utf8_error(),
498             inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
499         })
500     }
501
502     /// Consumes the `CString` and returns the underlying byte buffer.
503     ///
504     /// The returned buffer does **not** contain the trailing nul
505     /// terminator, and it is guaranteed to not have any interior nul
506     /// bytes.
507     ///
508     /// # Examples
509     ///
510     /// ```
511     /// use std::ffi::CString;
512     ///
513     /// let c_string = CString::new("foo").expect("CString::new failed");
514     /// let bytes = c_string.into_bytes();
515     /// assert_eq!(bytes, vec![b'f', b'o', b'o']);
516     /// ```
517     #[stable(feature = "cstring_into", since = "1.7.0")]
518     pub fn into_bytes(self) -> Vec<u8> {
519         let mut vec = self.into_inner().into_vec();
520         let _nul = vec.pop();
521         debug_assert_eq!(_nul, Some(0u8));
522         vec
523     }
524
525     /// Equivalent to the [`into_bytes`] function except that the returned vector
526     /// includes the trailing nul terminator.
527     ///
528     /// [`into_bytes`]: #method.into_bytes
529     ///
530     /// # Examples
531     ///
532     /// ```
533     /// use std::ffi::CString;
534     ///
535     /// let c_string = CString::new("foo").expect("CString::new failed");
536     /// let bytes = c_string.into_bytes_with_nul();
537     /// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
538     /// ```
539     #[stable(feature = "cstring_into", since = "1.7.0")]
540     pub fn into_bytes_with_nul(self) -> Vec<u8> {
541         self.into_inner().into_vec()
542     }
543
544     /// Returns the contents of this `CString` as a slice of bytes.
545     ///
546     /// The returned slice does **not** contain the trailing nul
547     /// terminator, and it is guaranteed to not have any interior nul
548     /// bytes. If you need the nul terminator, use
549     /// [`as_bytes_with_nul`] instead.
550     ///
551     /// [`as_bytes_with_nul`]: #method.as_bytes_with_nul
552     ///
553     /// # Examples
554     ///
555     /// ```
556     /// use std::ffi::CString;
557     ///
558     /// let c_string = CString::new("foo").expect("CString::new failed");
559     /// let bytes = c_string.as_bytes();
560     /// assert_eq!(bytes, &[b'f', b'o', b'o']);
561     /// ```
562     #[inline]
563     #[stable(feature = "rust1", since = "1.0.0")]
564     pub fn as_bytes(&self) -> &[u8] {
565         &self.inner[..self.inner.len() - 1]
566     }
567
568     /// Equivalent to the [`as_bytes`] function except that the returned slice
569     /// includes the trailing nul terminator.
570     ///
571     /// [`as_bytes`]: #method.as_bytes
572     ///
573     /// # Examples
574     ///
575     /// ```
576     /// use std::ffi::CString;
577     ///
578     /// let c_string = CString::new("foo").expect("CString::new failed");
579     /// let bytes = c_string.as_bytes_with_nul();
580     /// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
581     /// ```
582     #[inline]
583     #[stable(feature = "rust1", since = "1.0.0")]
584     pub fn as_bytes_with_nul(&self) -> &[u8] {
585         &self.inner
586     }
587
588     /// Extracts a [`CStr`] slice containing the entire string.
589     ///
590     /// [`CStr`]: struct.CStr.html
591     ///
592     /// # Examples
593     ///
594     /// ```
595     /// use std::ffi::{CString, CStr};
596     ///
597     /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
598     /// let cstr = c_string.as_c_str();
599     /// assert_eq!(cstr,
600     ///            CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
601     /// ```
602     #[inline]
603     #[stable(feature = "as_c_str", since = "1.20.0")]
604     pub fn as_c_str(&self) -> &CStr {
605         &*self
606     }
607
608     /// Converts this `CString` into a boxed [`CStr`].
609     ///
610     /// [`CStr`]: struct.CStr.html
611     ///
612     /// # Examples
613     ///
614     /// ```
615     /// use std::ffi::{CString, CStr};
616     ///
617     /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
618     /// let boxed = c_string.into_boxed_c_str();
619     /// assert_eq!(&*boxed,
620     ///            CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
621     /// ```
622     #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
623     pub fn into_boxed_c_str(self) -> Box<CStr> {
624         unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) }
625     }
626
627     /// Bypass "move out of struct which implements [`Drop`] trait" restriction.
628     ///
629     /// [`Drop`]: ../ops/trait.Drop.html
630     fn into_inner(self) -> Box<[u8]> {
631         // Rationale: `mem::forget(self)` invalidates the previous call to `ptr::read(&self.inner)`
632         // so we use `ManuallyDrop` to ensure `self` is not dropped.
633         // Then we can return the box directly without invalidating it.
634         // See https://github.com/rust-lang/rust/issues/62553.
635         let this = mem::ManuallyDrop::new(self);
636         unsafe { ptr::read(&this.inner) }
637     }
638
639     /// Converts a `Vec` of `u8` to a `CString` without checking the invariants
640     /// on the given `Vec`.
641     ///
642     /// # Safety
643     ///
644     /// The given `Vec` **must** have one nul byte as its last element.
645     /// This means it cannot be empty nor have any other nul byte anywhere else.
646     ///
647     /// # Example
648     ///
649     /// ```
650     /// use std::ffi::CString;
651     /// assert_eq!(
652     ///     unsafe { CString::from_vec_with_nul_unchecked(b"abc\0".to_vec()) },
653     ///     unsafe { CString::from_vec_unchecked(b"abc".to_vec()) }
654     /// );
655     /// ```
656     #[stable(feature = "cstring_from_vec_with_nul", since = "1.46.0")]
657     pub unsafe fn from_vec_with_nul_unchecked(v: Vec<u8>) -> Self {
658         Self { inner: v.into_boxed_slice() }
659     }
660
661     /// Attempts to converts a `Vec` of `u8` to a `CString`.
662     ///
663     /// Runtime checks are present to ensure there is only one nul byte in the
664     /// `Vec`, its last element.
665     ///
666     /// # Errors
667     ///
668     /// If a nul byte is present and not the last element or no nul bytes
669     /// is present, an error will be returned.
670     ///
671     /// # Examples
672     ///
673     /// A successful conversion will produce the same result as [`new`] when
674     /// called without the ending nul byte.
675     ///
676     /// ```
677     /// use std::ffi::CString;
678     /// assert_eq!(
679     ///     CString::from_vec_with_nul(b"abc\0".to_vec())
680     ///         .expect("CString::from_vec_with_nul failed"),
681     ///     CString::new(b"abc".to_vec())
682     /// );
683     /// ```
684     ///
685     /// A incorrectly formatted vector will produce an error.
686     ///
687     /// ```
688     /// use std::ffi::{CString, FromBytesWithNulError};
689     /// // Interior nul byte
690     /// let _: FromBytesWithNulError = CString::from_vec_with_nul(b"a\0bc".to_vec()).unwrap_err();
691     /// // No nul byte
692     /// let _: FromBytesWithNulError = CString::from_vec_with_nul(b"abc".to_vec()).unwrap_err();
693     /// ```
694     ///
695     /// [`new`]: #method.new
696     #[stable(feature = "cstring_from_vec_with_nul", since = "1.46.0")]
697     pub fn from_vec_with_nul(v: Vec<u8>) -> Result<Self, FromBytesWithNulError> {
698         let nul_pos = memchr::memchr(0, &v);
699         match nul_pos {
700             Some(nul_pos) if nul_pos + 1 == v.len() => {
701                 // SAFETY: We know there is only one nul byte, at the end
702                 // of the vec.
703                 Ok(unsafe { Self::from_vec_with_nul_unchecked(v) })
704             }
705             Some(nul_pos) => Err(FromBytesWithNulError::interior_nul(nul_pos)),
706             None => Err(FromBytesWithNulError::not_nul_terminated()),
707         }
708     }
709 }
710
711 // Turns this `CString` into an empty string to prevent
712 // memory-unsafe code from working by accident. Inline
713 // to prevent LLVM from optimizing it away in debug builds.
714 #[stable(feature = "cstring_drop", since = "1.13.0")]
715 impl Drop for CString {
716     #[inline]
717     fn drop(&mut self) {
718         unsafe {
719             *self.inner.get_unchecked_mut(0) = 0;
720         }
721     }
722 }
723
724 #[stable(feature = "rust1", since = "1.0.0")]
725 impl ops::Deref for CString {
726     type Target = CStr;
727
728     #[inline]
729     fn deref(&self) -> &CStr {
730         unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
731     }
732 }
733
734 #[stable(feature = "rust1", since = "1.0.0")]
735 impl fmt::Debug for CString {
736     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
737         fmt::Debug::fmt(&**self, f)
738     }
739 }
740
741 #[stable(feature = "cstring_into", since = "1.7.0")]
742 impl From<CString> for Vec<u8> {
743     /// Converts a [`CString`] into a [`Vec`]`<u8>`.
744     ///
745     /// The conversion consumes the [`CString`], and removes the terminating NUL byte.
746     ///
747     /// [`Vec`]: ../vec/struct.Vec.html
748     /// [`CString`]: ../ffi/struct.CString.html
749     #[inline]
750     fn from(s: CString) -> Vec<u8> {
751         s.into_bytes()
752     }
753 }
754
755 #[stable(feature = "cstr_debug", since = "1.3.0")]
756 impl fmt::Debug for CStr {
757     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
758         write!(f, "\"")?;
759         for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
760             f.write_char(byte as char)?;
761         }
762         write!(f, "\"")
763     }
764 }
765
766 #[stable(feature = "cstr_default", since = "1.10.0")]
767 impl Default for &CStr {
768     fn default() -> Self {
769         const SLICE: &[c_char] = &[0];
770         unsafe { CStr::from_ptr(SLICE.as_ptr()) }
771     }
772 }
773
774 #[stable(feature = "cstr_default", since = "1.10.0")]
775 impl Default for CString {
776     /// Creates an empty `CString`.
777     fn default() -> CString {
778         let a: &CStr = Default::default();
779         a.to_owned()
780     }
781 }
782
783 #[stable(feature = "cstr_borrow", since = "1.3.0")]
784 impl Borrow<CStr> for CString {
785     #[inline]
786     fn borrow(&self) -> &CStr {
787         self
788     }
789 }
790
791 #[stable(feature = "cstring_from_cow_cstr", since = "1.28.0")]
792 impl<'a> From<Cow<'a, CStr>> for CString {
793     #[inline]
794     fn from(s: Cow<'a, CStr>) -> Self {
795         s.into_owned()
796     }
797 }
798
799 #[stable(feature = "box_from_c_str", since = "1.17.0")]
800 impl From<&CStr> for Box<CStr> {
801     fn from(s: &CStr) -> Box<CStr> {
802         let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul());
803         unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
804     }
805 }
806
807 #[stable(feature = "box_from_cow", since = "1.45.0")]
808 impl From<Cow<'_, CStr>> for Box<CStr> {
809     #[inline]
810     fn from(cow: Cow<'_, CStr>) -> Box<CStr> {
811         match cow {
812             Cow::Borrowed(s) => Box::from(s),
813             Cow::Owned(s) => Box::from(s),
814         }
815     }
816 }
817
818 #[stable(feature = "c_string_from_box", since = "1.18.0")]
819 impl From<Box<CStr>> for CString {
820     /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating.
821     ///
822     /// [`Box`]: ../boxed/struct.Box.html
823     /// [`CString`]: ../ffi/struct.CString.html
824     #[inline]
825     fn from(s: Box<CStr>) -> CString {
826         s.into_c_string()
827     }
828 }
829
830 #[stable(feature = "cstring_from_vec_of_nonzerou8", since = "1.43.0")]
831 impl From<Vec<NonZeroU8>> for CString {
832     /// Converts a [`Vec`]`<`[`NonZeroU8`]`>` into a [`CString`] without
833     /// copying nor checking for inner null bytes.
834     ///
835     /// [`CString`]: ../ffi/struct.CString.html
836     /// [`NonZeroU8`]: ../num/struct.NonZeroU8.html
837     /// [`Vec`]: ../vec/struct.Vec.html
838     #[inline]
839     fn from(v: Vec<NonZeroU8>) -> CString {
840         unsafe {
841             // Transmute `Vec<NonZeroU8>` to `Vec<u8>`.
842             let v: Vec<u8> = {
843                 // Safety:
844                 //   - transmuting between `NonZeroU8` and `u8` is sound;
845                 //   - `alloc::Layout<NonZeroU8> == alloc::Layout<u8>`.
846                 let (ptr, len, cap): (*mut NonZeroU8, _, _) = Vec::into_raw_parts(v);
847                 Vec::from_raw_parts(ptr.cast::<u8>(), len, cap)
848             };
849             // Safety: `v` cannot contain null bytes, given the type-level
850             // invariant of `NonZeroU8`.
851             CString::from_vec_unchecked(v)
852         }
853     }
854 }
855
856 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
857 impl Clone for Box<CStr> {
858     #[inline]
859     fn clone(&self) -> Self {
860         (**self).into()
861     }
862 }
863
864 #[stable(feature = "box_from_c_string", since = "1.20.0")]
865 impl From<CString> for Box<CStr> {
866     /// Converts a [`CString`] into a [`Box`]`<CStr>` without copying or allocating.
867     ///
868     /// [`CString`]: ../ffi/struct.CString.html
869     /// [`Box`]: ../boxed/struct.Box.html
870     #[inline]
871     fn from(s: CString) -> Box<CStr> {
872         s.into_boxed_c_str()
873     }
874 }
875
876 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
877 impl<'a> From<CString> for Cow<'a, CStr> {
878     #[inline]
879     fn from(s: CString) -> Cow<'a, CStr> {
880         Cow::Owned(s)
881     }
882 }
883
884 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
885 impl<'a> From<&'a CStr> for Cow<'a, CStr> {
886     #[inline]
887     fn from(s: &'a CStr) -> Cow<'a, CStr> {
888         Cow::Borrowed(s)
889     }
890 }
891
892 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
893 impl<'a> From<&'a CString> for Cow<'a, CStr> {
894     #[inline]
895     fn from(s: &'a CString) -> Cow<'a, CStr> {
896         Cow::Borrowed(s.as_c_str())
897     }
898 }
899
900 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
901 impl From<CString> for Arc<CStr> {
902     /// Converts a [`CString`] into a [`Arc`]`<CStr>` without copying or allocating.
903     ///
904     /// [`CString`]: ../ffi/struct.CString.html
905     /// [`Arc`]: ../sync/struct.Arc.html
906     #[inline]
907     fn from(s: CString) -> Arc<CStr> {
908         let arc: Arc<[u8]> = Arc::from(s.into_inner());
909         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
910     }
911 }
912
913 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
914 impl From<&CStr> for Arc<CStr> {
915     #[inline]
916     fn from(s: &CStr) -> Arc<CStr> {
917         let arc: Arc<[u8]> = Arc::from(s.to_bytes_with_nul());
918         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
919     }
920 }
921
922 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
923 impl From<CString> for Rc<CStr> {
924     /// Converts a [`CString`] into a [`Rc`]`<CStr>` without copying or allocating.
925     ///
926     /// [`CString`]: ../ffi/struct.CString.html
927     /// [`Rc`]: ../rc/struct.Rc.html
928     #[inline]
929     fn from(s: CString) -> Rc<CStr> {
930         let rc: Rc<[u8]> = Rc::from(s.into_inner());
931         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
932     }
933 }
934
935 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
936 impl From<&CStr> for Rc<CStr> {
937     #[inline]
938     fn from(s: &CStr) -> Rc<CStr> {
939         let rc: Rc<[u8]> = Rc::from(s.to_bytes_with_nul());
940         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
941     }
942 }
943
944 #[stable(feature = "default_box_extra", since = "1.17.0")]
945 impl Default for Box<CStr> {
946     fn default() -> Box<CStr> {
947         let boxed: Box<[u8]> = Box::from([0]);
948         unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
949     }
950 }
951
952 impl NulError {
953     /// Returns the position of the nul byte in the slice that caused
954     /// [`CString::new`] to fail.
955     ///
956     /// [`CString::new`]: struct.CString.html#method.new
957     ///
958     /// # Examples
959     ///
960     /// ```
961     /// use std::ffi::CString;
962     ///
963     /// let nul_error = CString::new("foo\0bar").unwrap_err();
964     /// assert_eq!(nul_error.nul_position(), 3);
965     ///
966     /// let nul_error = CString::new("foo bar\0").unwrap_err();
967     /// assert_eq!(nul_error.nul_position(), 7);
968     /// ```
969     #[stable(feature = "rust1", since = "1.0.0")]
970     pub fn nul_position(&self) -> usize {
971         self.0
972     }
973
974     /// Consumes this error, returning the underlying vector of bytes which
975     /// generated the error in the first place.
976     ///
977     /// # Examples
978     ///
979     /// ```
980     /// use std::ffi::CString;
981     ///
982     /// let nul_error = CString::new("foo\0bar").unwrap_err();
983     /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
984     /// ```
985     #[stable(feature = "rust1", since = "1.0.0")]
986     pub fn into_vec(self) -> Vec<u8> {
987         self.1
988     }
989 }
990
991 #[stable(feature = "rust1", since = "1.0.0")]
992 impl Error for NulError {
993     #[allow(deprecated)]
994     fn description(&self) -> &str {
995         "nul byte found in data"
996     }
997 }
998
999 #[stable(feature = "rust1", since = "1.0.0")]
1000 impl fmt::Display for NulError {
1001     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1002         write!(f, "nul byte found in provided data at position: {}", self.0)
1003     }
1004 }
1005
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 impl From<NulError> for io::Error {
1008     /// Converts a [`NulError`] into a [`io::Error`].
1009     ///
1010     /// [`NulError`]: ../ffi/struct.NulError.html
1011     /// [`io::Error`]: ../io/struct.Error.html
1012     fn from(_: NulError) -> io::Error {
1013         io::Error::new(io::ErrorKind::InvalidInput, "data provided contains a nul byte")
1014     }
1015 }
1016
1017 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
1018 impl Error for FromBytesWithNulError {
1019     #[allow(deprecated)]
1020     fn description(&self) -> &str {
1021         match self.kind {
1022             FromBytesWithNulErrorKind::InteriorNul(..) => {
1023                 "data provided contains an interior nul byte"
1024             }
1025             FromBytesWithNulErrorKind::NotNulTerminated => "data provided is not nul terminated",
1026         }
1027     }
1028 }
1029
1030 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
1031 impl fmt::Display for FromBytesWithNulError {
1032     #[allow(deprecated, deprecated_in_future)]
1033     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1034         f.write_str(self.description())?;
1035         if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind {
1036             write!(f, " at byte pos {}", pos)?;
1037         }
1038         Ok(())
1039     }
1040 }
1041
1042 impl IntoStringError {
1043     /// Consumes this error, returning original [`CString`] which generated the
1044     /// error.
1045     ///
1046     /// [`CString`]: struct.CString.html
1047     #[stable(feature = "cstring_into", since = "1.7.0")]
1048     pub fn into_cstring(self) -> CString {
1049         self.inner
1050     }
1051
1052     /// Access the underlying UTF-8 error that was the cause of this error.
1053     #[stable(feature = "cstring_into", since = "1.7.0")]
1054     pub fn utf8_error(&self) -> Utf8Error {
1055         self.error
1056     }
1057 }
1058
1059 #[stable(feature = "cstring_into", since = "1.7.0")]
1060 impl Error for IntoStringError {
1061     #[allow(deprecated)]
1062     fn description(&self) -> &str {
1063         "C string contained non-utf8 bytes"
1064     }
1065
1066     fn source(&self) -> Option<&(dyn Error + 'static)> {
1067         Some(&self.error)
1068     }
1069 }
1070
1071 #[stable(feature = "cstring_into", since = "1.7.0")]
1072 impl fmt::Display for IntoStringError {
1073     #[allow(deprecated, deprecated_in_future)]
1074     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1075         self.description().fmt(f)
1076     }
1077 }
1078
1079 impl CStr {
1080     /// Wraps a raw C string with a safe C string wrapper.
1081     ///
1082     /// This function will wrap the provided `ptr` with a `CStr` wrapper, which
1083     /// allows inspection and interoperation of non-owned C strings. The total
1084     /// size of the raw C string must be smaller than `isize::MAX` **bytes**
1085     /// in memory due to calling the `slice::from_raw_parts` function.
1086     /// This method is unsafe for a number of reasons:
1087     ///
1088     /// * There is no guarantee to the validity of `ptr`.
1089     /// * The returned lifetime is not guaranteed to be the actual lifetime of
1090     ///   `ptr`.
1091     /// * There is no guarantee that the memory pointed to by `ptr` contains a
1092     ///   valid nul terminator byte at the end of the string.
1093     /// * It is not guaranteed that the memory pointed by `ptr` won't change
1094     ///   before the `CStr` has been destroyed.
1095     ///
1096     /// > **Note**: This operation is intended to be a 0-cost cast but it is
1097     /// > currently implemented with an up-front calculation of the length of
1098     /// > the string. This is not guaranteed to always be the case.
1099     ///
1100     /// # Examples
1101     ///
1102     /// ```ignore (extern-declaration)
1103     /// # fn main() {
1104     /// use std::ffi::CStr;
1105     /// use std::os::raw::c_char;
1106     ///
1107     /// extern {
1108     ///     fn my_string() -> *const c_char;
1109     /// }
1110     ///
1111     /// unsafe {
1112     ///     let slice = CStr::from_ptr(my_string());
1113     ///     println!("string returned: {}", slice.to_str().unwrap());
1114     /// }
1115     /// # }
1116     /// ```
1117     #[stable(feature = "rust1", since = "1.0.0")]
1118     pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
1119         let len = sys::strlen(ptr);
1120         let ptr = ptr as *const u8;
1121         CStr::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr, len as usize + 1))
1122     }
1123
1124     /// Creates a C string wrapper from a byte slice.
1125     ///
1126     /// This function will cast the provided `bytes` to a `CStr`
1127     /// wrapper after ensuring that the byte slice is nul-terminated
1128     /// and does not contain any interior nul bytes.
1129     ///
1130     /// # Examples
1131     ///
1132     /// ```
1133     /// use std::ffi::CStr;
1134     ///
1135     /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
1136     /// assert!(cstr.is_ok());
1137     /// ```
1138     ///
1139     /// Creating a `CStr` without a trailing nul terminator is an error:
1140     ///
1141     /// ```
1142     /// use std::ffi::CStr;
1143     ///
1144     /// let cstr = CStr::from_bytes_with_nul(b"hello");
1145     /// assert!(cstr.is_err());
1146     /// ```
1147     ///
1148     /// Creating a `CStr` with an interior nul byte is an error:
1149     ///
1150     /// ```
1151     /// use std::ffi::CStr;
1152     ///
1153     /// let cstr = CStr::from_bytes_with_nul(b"he\0llo\0");
1154     /// assert!(cstr.is_err());
1155     /// ```
1156     #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
1157     pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError> {
1158         let nul_pos = memchr::memchr(0, bytes);
1159         if let Some(nul_pos) = nul_pos {
1160             if nul_pos + 1 != bytes.len() {
1161                 return Err(FromBytesWithNulError::interior_nul(nul_pos));
1162             }
1163             Ok(unsafe { CStr::from_bytes_with_nul_unchecked(bytes) })
1164         } else {
1165             Err(FromBytesWithNulError::not_nul_terminated())
1166         }
1167     }
1168
1169     /// Unsafely creates a C string wrapper from a byte slice.
1170     ///
1171     /// This function will cast the provided `bytes` to a `CStr` wrapper without
1172     /// performing any sanity checks. The provided slice **must** be nul-terminated
1173     /// and not contain any interior nul bytes.
1174     ///
1175     /// # Examples
1176     ///
1177     /// ```
1178     /// use std::ffi::{CStr, CString};
1179     ///
1180     /// unsafe {
1181     ///     let cstring = CString::new("hello").expect("CString::new failed");
1182     ///     let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
1183     ///     assert_eq!(cstr, &*cstring);
1184     /// }
1185     /// ```
1186     #[inline]
1187     #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
1188     #[rustc_const_unstable(feature = "const_cstr_unchecked", issue = "none")]
1189     pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
1190         &*(bytes as *const [u8] as *const CStr)
1191     }
1192
1193     /// Returns the inner pointer to this C string.
1194     ///
1195     /// The returned pointer will be valid for as long as `self` is, and points
1196     /// to a contiguous region of memory terminated with a 0 byte to represent
1197     /// the end of the string.
1198     ///
1199     /// **WARNING**
1200     ///
1201     /// The returned pointer is read-only; writing to it (including passing it
1202     /// to C code that writes to it) causes undefined behavior.
1203     ///
1204     /// It is your responsibility to make sure that the underlying memory is not
1205     /// freed too early. For example, the following code will cause undefined
1206     /// behavior when `ptr` is used inside the `unsafe` block:
1207     ///
1208     /// ```no_run
1209     /// # #![allow(unused_must_use)]
1210     /// use std::ffi::CString;
1211     ///
1212     /// let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
1213     /// unsafe {
1214     ///     // `ptr` is dangling
1215     ///     *ptr;
1216     /// }
1217     /// ```
1218     ///
1219     /// This happens because the pointer returned by `as_ptr` does not carry any
1220     /// lifetime information and the [`CString`] is deallocated immediately after
1221     /// the `CString::new("Hello").expect("CString::new failed").as_ptr()` expression is evaluated.
1222     /// To fix the problem, bind the `CString` to a local variable:
1223     ///
1224     /// ```no_run
1225     /// # #![allow(unused_must_use)]
1226     /// use std::ffi::CString;
1227     ///
1228     /// let hello = CString::new("Hello").expect("CString::new failed");
1229     /// let ptr = hello.as_ptr();
1230     /// unsafe {
1231     ///     // `ptr` is valid because `hello` is in scope
1232     ///     *ptr;
1233     /// }
1234     /// ```
1235     ///
1236     /// This way, the lifetime of the `CString` in `hello` encompasses
1237     /// the lifetime of `ptr` and the `unsafe` block.
1238     ///
1239     /// [`CString`]: struct.CString.html
1240     #[inline]
1241     #[stable(feature = "rust1", since = "1.0.0")]
1242     #[rustc_const_stable(feature = "const_str_as_ptr", since = "1.32.0")]
1243     pub const fn as_ptr(&self) -> *const c_char {
1244         self.inner.as_ptr()
1245     }
1246
1247     /// Converts this C string to a byte slice.
1248     ///
1249     /// The returned slice will **not** contain the trailing nul terminator that this C
1250     /// string has.
1251     ///
1252     /// > **Note**: This method is currently implemented as a constant-time
1253     /// > cast, but it is planned to alter its definition in the future to
1254     /// > perform the length calculation whenever this method is called.
1255     ///
1256     /// # Examples
1257     ///
1258     /// ```
1259     /// use std::ffi::CStr;
1260     ///
1261     /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1262     /// assert_eq!(cstr.to_bytes(), b"foo");
1263     /// ```
1264     #[inline]
1265     #[stable(feature = "rust1", since = "1.0.0")]
1266     pub fn to_bytes(&self) -> &[u8] {
1267         let bytes = self.to_bytes_with_nul();
1268         &bytes[..bytes.len() - 1]
1269     }
1270
1271     /// Converts this C string to a byte slice containing the trailing 0 byte.
1272     ///
1273     /// This function is the equivalent of [`to_bytes`] except that it will retain
1274     /// the trailing nul terminator instead of chopping it off.
1275     ///
1276     /// > **Note**: This method is currently implemented as a 0-cost cast, but
1277     /// > it is planned to alter its definition in the future to perform the
1278     /// > length calculation whenever this method is called.
1279     ///
1280     /// [`to_bytes`]: #method.to_bytes
1281     ///
1282     /// # Examples
1283     ///
1284     /// ```
1285     /// use std::ffi::CStr;
1286     ///
1287     /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1288     /// assert_eq!(cstr.to_bytes_with_nul(), b"foo\0");
1289     /// ```
1290     #[inline]
1291     #[stable(feature = "rust1", since = "1.0.0")]
1292     pub fn to_bytes_with_nul(&self) -> &[u8] {
1293         unsafe { &*(&self.inner as *const [c_char] as *const [u8]) }
1294     }
1295
1296     /// Yields a [`&str`] slice if the `CStr` contains valid UTF-8.
1297     ///
1298     /// If the contents of the `CStr` are valid UTF-8 data, this
1299     /// function will return the corresponding [`&str`] slice. Otherwise,
1300     /// it will return an error with details of where UTF-8 validation failed.
1301     ///
1302     /// [`&str`]: ../primitive.str.html
1303     ///
1304     /// # Examples
1305     ///
1306     /// ```
1307     /// use std::ffi::CStr;
1308     ///
1309     /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1310     /// assert_eq!(cstr.to_str(), Ok("foo"));
1311     /// ```
1312     #[stable(feature = "cstr_to_str", since = "1.4.0")]
1313     pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
1314         // N.B., when `CStr` is changed to perform the length check in `.to_bytes()`
1315         // instead of in `from_ptr()`, it may be worth considering if this should
1316         // be rewritten to do the UTF-8 check inline with the length calculation
1317         // instead of doing it afterwards.
1318         str::from_utf8(self.to_bytes())
1319     }
1320
1321     /// Converts a `CStr` into a [`Cow`]`<`[`str`]`>`.
1322     ///
1323     /// If the contents of the `CStr` are valid UTF-8 data, this
1324     /// function will return a [`Cow`]`::`[`Borrowed`]`(`[`&str`]`)`
1325     /// with the corresponding [`&str`] slice. Otherwise, it will
1326     /// replace any invalid UTF-8 sequences with
1327     /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD] and return a
1328     /// [`Cow`]`::`[`Owned`]`(`[`String`]`)` with the result.
1329     ///
1330     /// [`Cow`]: ../borrow/enum.Cow.html
1331     /// [`Borrowed`]: ../borrow/enum.Cow.html#variant.Borrowed
1332     /// [`Owned`]: ../borrow/enum.Cow.html#variant.Owned
1333     /// [`str`]: ../primitive.str.html
1334     /// [`String`]: ../string/struct.String.html
1335     /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
1336     ///
1337     /// # Examples
1338     ///
1339     /// Calling `to_string_lossy` on a `CStr` containing valid UTF-8:
1340     ///
1341     /// ```
1342     /// use std::borrow::Cow;
1343     /// use std::ffi::CStr;
1344     ///
1345     /// let cstr = CStr::from_bytes_with_nul(b"Hello World\0")
1346     ///                  .expect("CStr::from_bytes_with_nul failed");
1347     /// assert_eq!(cstr.to_string_lossy(), Cow::Borrowed("Hello World"));
1348     /// ```
1349     ///
1350     /// Calling `to_string_lossy` on a `CStr` containing invalid UTF-8:
1351     ///
1352     /// ```
1353     /// use std::borrow::Cow;
1354     /// use std::ffi::CStr;
1355     ///
1356     /// let cstr = CStr::from_bytes_with_nul(b"Hello \xF0\x90\x80World\0")
1357     ///                  .expect("CStr::from_bytes_with_nul failed");
1358     /// assert_eq!(
1359     ///     cstr.to_string_lossy(),
1360     ///     Cow::Owned(String::from("Hello �World")) as Cow<'_, str>
1361     /// );
1362     /// ```
1363     #[stable(feature = "cstr_to_str", since = "1.4.0")]
1364     pub fn to_string_lossy(&self) -> Cow<'_, str> {
1365         String::from_utf8_lossy(self.to_bytes())
1366     }
1367
1368     /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating.
1369     ///
1370     /// [`Box`]: ../boxed/struct.Box.html
1371     /// [`CString`]: struct.CString.html
1372     ///
1373     /// # Examples
1374     ///
1375     /// ```
1376     /// use std::ffi::CString;
1377     ///
1378     /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
1379     /// let boxed = c_string.into_boxed_c_str();
1380     /// assert_eq!(boxed.into_c_string(), CString::new("foo").expect("CString::new failed"));
1381     /// ```
1382     #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
1383     pub fn into_c_string(self: Box<CStr>) -> CString {
1384         let raw = Box::into_raw(self) as *mut [u8];
1385         CString { inner: unsafe { Box::from_raw(raw) } }
1386     }
1387 }
1388
1389 #[stable(feature = "rust1", since = "1.0.0")]
1390 impl PartialEq for CStr {
1391     fn eq(&self, other: &CStr) -> bool {
1392         self.to_bytes().eq(other.to_bytes())
1393     }
1394 }
1395 #[stable(feature = "rust1", since = "1.0.0")]
1396 impl Eq for CStr {}
1397 #[stable(feature = "rust1", since = "1.0.0")]
1398 impl PartialOrd for CStr {
1399     fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
1400         self.to_bytes().partial_cmp(&other.to_bytes())
1401     }
1402 }
1403 #[stable(feature = "rust1", since = "1.0.0")]
1404 impl Ord for CStr {
1405     fn cmp(&self, other: &CStr) -> Ordering {
1406         self.to_bytes().cmp(&other.to_bytes())
1407     }
1408 }
1409
1410 #[stable(feature = "cstr_borrow", since = "1.3.0")]
1411 impl ToOwned for CStr {
1412     type Owned = CString;
1413
1414     fn to_owned(&self) -> CString {
1415         CString { inner: self.to_bytes_with_nul().into() }
1416     }
1417
1418     fn clone_into(&self, target: &mut CString) {
1419         let mut b = Vec::from(mem::take(&mut target.inner));
1420         self.to_bytes_with_nul().clone_into(&mut b);
1421         target.inner = b.into_boxed_slice();
1422     }
1423 }
1424
1425 #[stable(feature = "cstring_asref", since = "1.7.0")]
1426 impl From<&CStr> for CString {
1427     fn from(s: &CStr) -> CString {
1428         s.to_owned()
1429     }
1430 }
1431
1432 #[stable(feature = "cstring_asref", since = "1.7.0")]
1433 impl ops::Index<ops::RangeFull> for CString {
1434     type Output = CStr;
1435
1436     #[inline]
1437     fn index(&self, _index: ops::RangeFull) -> &CStr {
1438         self
1439     }
1440 }
1441
1442 #[stable(feature = "cstring_asref", since = "1.7.0")]
1443 impl AsRef<CStr> for CStr {
1444     #[inline]
1445     fn as_ref(&self) -> &CStr {
1446         self
1447     }
1448 }
1449
1450 #[stable(feature = "cstring_asref", since = "1.7.0")]
1451 impl AsRef<CStr> for CString {
1452     #[inline]
1453     fn as_ref(&self) -> &CStr {
1454         self
1455     }
1456 }
1457
1458 #[cfg(test)]
1459 mod tests {
1460     use super::*;
1461     use crate::borrow::Cow::{Borrowed, Owned};
1462     use crate::collections::hash_map::DefaultHasher;
1463     use crate::hash::{Hash, Hasher};
1464     use crate::os::raw::c_char;
1465     use crate::rc::Rc;
1466     use crate::sync::Arc;
1467
1468     #[test]
1469     fn c_to_rust() {
1470         let data = b"123\0";
1471         let ptr = data.as_ptr() as *const c_char;
1472         unsafe {
1473             assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
1474             assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
1475         }
1476     }
1477
1478     #[test]
1479     fn simple() {
1480         let s = CString::new("1234").unwrap();
1481         assert_eq!(s.as_bytes(), b"1234");
1482         assert_eq!(s.as_bytes_with_nul(), b"1234\0");
1483     }
1484
1485     #[test]
1486     fn build_with_zero1() {
1487         assert!(CString::new(&b"\0"[..]).is_err());
1488     }
1489     #[test]
1490     fn build_with_zero2() {
1491         assert!(CString::new(vec![0]).is_err());
1492     }
1493
1494     #[test]
1495     fn build_with_zero3() {
1496         unsafe {
1497             let s = CString::from_vec_unchecked(vec![0]);
1498             assert_eq!(s.as_bytes(), b"\0");
1499         }
1500     }
1501
1502     #[test]
1503     fn formatted() {
1504         let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
1505         assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
1506     }
1507
1508     #[test]
1509     fn borrowed() {
1510         unsafe {
1511             let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
1512             assert_eq!(s.to_bytes(), b"12");
1513             assert_eq!(s.to_bytes_with_nul(), b"12\0");
1514         }
1515     }
1516
1517     #[test]
1518     fn to_str() {
1519         let data = b"123\xE2\x80\xA6\0";
1520         let ptr = data.as_ptr() as *const c_char;
1521         unsafe {
1522             assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
1523             assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
1524         }
1525         let data = b"123\xE2\0";
1526         let ptr = data.as_ptr() as *const c_char;
1527         unsafe {
1528             assert!(CStr::from_ptr(ptr).to_str().is_err());
1529             assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
1530         }
1531     }
1532
1533     #[test]
1534     fn to_owned() {
1535         let data = b"123\0";
1536         let ptr = data.as_ptr() as *const c_char;
1537
1538         let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
1539         assert_eq!(owned.as_bytes_with_nul(), data);
1540     }
1541
1542     #[test]
1543     fn equal_hash() {
1544         let data = b"123\xE2\xFA\xA6\0";
1545         let ptr = data.as_ptr() as *const c_char;
1546         let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
1547
1548         let mut s = DefaultHasher::new();
1549         cstr.hash(&mut s);
1550         let cstr_hash = s.finish();
1551         let mut s = DefaultHasher::new();
1552         CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
1553         let cstring_hash = s.finish();
1554
1555         assert_eq!(cstr_hash, cstring_hash);
1556     }
1557
1558     #[test]
1559     fn from_bytes_with_nul() {
1560         let data = b"123\0";
1561         let cstr = CStr::from_bytes_with_nul(data);
1562         assert_eq!(cstr.map(CStr::to_bytes), Ok(&b"123"[..]));
1563         let cstr = CStr::from_bytes_with_nul(data);
1564         assert_eq!(cstr.map(CStr::to_bytes_with_nul), Ok(&b"123\0"[..]));
1565
1566         unsafe {
1567             let cstr = CStr::from_bytes_with_nul(data);
1568             let cstr_unchecked = CStr::from_bytes_with_nul_unchecked(data);
1569             assert_eq!(cstr, Ok(cstr_unchecked));
1570         }
1571     }
1572
1573     #[test]
1574     fn from_bytes_with_nul_unterminated() {
1575         let data = b"123";
1576         let cstr = CStr::from_bytes_with_nul(data);
1577         assert!(cstr.is_err());
1578     }
1579
1580     #[test]
1581     fn from_bytes_with_nul_interior() {
1582         let data = b"1\023\0";
1583         let cstr = CStr::from_bytes_with_nul(data);
1584         assert!(cstr.is_err());
1585     }
1586
1587     #[test]
1588     fn into_boxed() {
1589         let orig: &[u8] = b"Hello, world!\0";
1590         let cstr = CStr::from_bytes_with_nul(orig).unwrap();
1591         let boxed: Box<CStr> = Box::from(cstr);
1592         let cstring = cstr.to_owned().into_boxed_c_str().into_c_string();
1593         assert_eq!(cstr, &*boxed);
1594         assert_eq!(&*boxed, &*cstring);
1595         assert_eq!(&*cstring, cstr);
1596     }
1597
1598     #[test]
1599     fn boxed_default() {
1600         let boxed = <Box<CStr>>::default();
1601         assert_eq!(boxed.to_bytes_with_nul(), &[0]);
1602     }
1603
1604     #[test]
1605     fn test_c_str_clone_into() {
1606         let mut c_string = CString::new("lorem").unwrap();
1607         let c_ptr = c_string.as_ptr();
1608         let c_str = CStr::from_bytes_with_nul(b"ipsum\0").unwrap();
1609         c_str.clone_into(&mut c_string);
1610         assert_eq!(c_str, c_string.as_c_str());
1611         // The exact same size shouldn't have needed to move its allocation
1612         assert_eq!(c_ptr, c_string.as_ptr());
1613     }
1614
1615     #[test]
1616     fn into_rc() {
1617         let orig: &[u8] = b"Hello, world!\0";
1618         let cstr = CStr::from_bytes_with_nul(orig).unwrap();
1619         let rc: Rc<CStr> = Rc::from(cstr);
1620         let arc: Arc<CStr> = Arc::from(cstr);
1621
1622         assert_eq!(&*rc, cstr);
1623         assert_eq!(&*arc, cstr);
1624
1625         let rc2: Rc<CStr> = Rc::from(cstr.to_owned());
1626         let arc2: Arc<CStr> = Arc::from(cstr.to_owned());
1627
1628         assert_eq!(&*rc2, cstr);
1629         assert_eq!(&*arc2, cstr);
1630     }
1631
1632     #[test]
1633     fn cstr_const_constructor() {
1634         const CSTR: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b"Hello, world!\0") };
1635
1636         assert_eq!(CSTR.to_str().unwrap(), "Hello, world!");
1637     }
1638 }