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