2 use crate::borrow::{Borrow, Cow};
3 use crate::cmp::Ordering;
4 use crate::error::Error;
5 use crate::fmt::{self, Write};
10 use crate::os::raw::c_char;
14 use crate::str::{self, Utf8Error};
18 /// A type representing an owned, C-compatible, nul-terminated string with no nul bytes in the
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").
26 /// `CString` is to [`&CStr`] as [`String`] is to [`&str`]: the former
27 /// in each pair are owned strings; the latter are borrowed
30 /// # Creating a `CString`
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).
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
41 /// # Extracting a raw pointer to the whole C string
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.
50 /// # Extracting a slice of the whole C string
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.
61 /// If you need a `&[`[`u8`]`]` slice *with* the nul terminator, you
62 /// can use [`as_bytes_with_nul`] instead.
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.
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
87 /// ```ignore (extern-declaration)
89 /// use std::ffi::CString;
90 /// use std::os::raw::c_char;
93 /// fn my_printer(s: *const c_char);
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");
100 /// my_printer(c_to_print.as_ptr());
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.
116 #[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
117 #[stable(feature = "rust1", since = "1.0.0")]
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.
125 /// Representation of a borrowed C string.
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`].
133 /// `&CStr` is to [`CString`] as [`&str`] is to [`String`]: the former
134 /// in each pair are borrowed references; the latter are owned
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.
144 /// Inspecting a foreign C string:
146 /// ```ignore (extern-declaration)
147 /// use std::ffi::CStr;
148 /// use std::os::raw::c_char;
150 /// extern { fn my_string() -> *const c_char; }
153 /// let slice = CStr::from_ptr(my_string());
154 /// println!("string buffer size without nul terminator: {}", slice.to_bytes().len());
158 /// Passing a Rust-originating C string:
160 /// ```ignore (extern-declaration)
161 /// use std::ffi::{CString, CStr};
162 /// use std::os::raw::c_char;
164 /// fn work(data: &CStr) {
165 /// extern { fn work_with(data: *const c_char); }
167 /// unsafe { work_with(data.as_ptr()) }
170 /// let s = CString::new("data data data data").expect("CString::new failed");
174 /// Converting a foreign C string into a Rust [`String`]:
176 /// ```ignore (extern-declaration)
177 /// use std::ffi::CStr;
178 /// use std::os::raw::c_char;
180 /// extern { fn my_string() -> *const c_char; }
182 /// fn my_string_safe() -> String {
184 /// CStr::from_ptr(my_string()).to_string_lossy().into_owned()
188 /// println!("string: {}", my_string_safe());
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
197 #[stable(feature = "rust1", since = "1.0.0")]
199 // `fn from` in `impl From<&CStr> for Box<CStr>` current implementation relies
200 // on `CStr` being layout-compatible with `[u8]`.
201 // When attribute privacy is implemented, `CStr` should be annotated as `#[repr(transparent)]`.
202 // Anyway, `CStr` representation and layout are considered implementation detail, are
203 // not documented and must not be relied upon.
205 // FIXME: this should not be represented with a DST slice but rather with
206 // just a raw `c_char` along with some form of marker to make
207 // this an unsized type. Essentially `sizeof(&CStr)` should be the
208 // same as `sizeof(&c_char)` but `CStr` should be an unsized type.
212 /// An error indicating that an interior nul byte was found.
214 /// While Rust strings may contain nul bytes in the middle, C strings
215 /// can't, as that byte would effectively truncate the string.
217 /// This error is created by the [`new`][`CString::new`] method on
218 /// [`CString`]. See its documentation for more.
220 /// [`CString`]: struct.CString.html
221 /// [`CString::new`]: struct.CString.html#method.new
226 /// use std::ffi::{CString, NulError};
228 /// let _: NulError = CString::new(b"f\0oo".to_vec()).unwrap_err();
230 #[derive(Clone, PartialEq, Eq, Debug)]
231 #[stable(feature = "rust1", since = "1.0.0")]
232 pub struct NulError(usize, Vec<u8>);
234 /// An error indicating that a nul byte was not in the expected position.
236 /// The slice used to create a [`CStr`] must have one and only one nul
237 /// byte at the end of the slice.
239 /// This error is created by the
240 /// [`from_bytes_with_nul`][`CStr::from_bytes_with_nul`] method on
241 /// [`CStr`]. See its documentation for more.
243 /// [`CStr`]: struct.CStr.html
244 /// [`CStr::from_bytes_with_nul`]: struct.CStr.html#method.from_bytes_with_nul
249 /// use std::ffi::{CStr, FromBytesWithNulError};
251 /// let _: FromBytesWithNulError = CStr::from_bytes_with_nul(b"f\0oo").unwrap_err();
253 #[derive(Clone, PartialEq, Eq, Debug)]
254 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
255 pub struct FromBytesWithNulError {
256 kind: FromBytesWithNulErrorKind,
259 #[derive(Clone, PartialEq, Eq, Debug)]
260 enum FromBytesWithNulErrorKind {
265 impl FromBytesWithNulError {
266 fn interior_nul(pos: usize) -> FromBytesWithNulError {
267 FromBytesWithNulError { kind: FromBytesWithNulErrorKind::InteriorNul(pos) }
269 fn not_nul_terminated() -> FromBytesWithNulError {
270 FromBytesWithNulError { kind: FromBytesWithNulErrorKind::NotNulTerminated }
274 /// An error indicating invalid UTF-8 when converting a [`CString`] into a [`String`].
276 /// `CString` is just a wrapper over a buffer of bytes with a nul
277 /// terminator; [`into_string`][`CString::into_string`] performs UTF-8
278 /// validation on those bytes and may return this error.
280 /// This `struct` is created by the
281 /// [`into_string`][`CString::into_string`] method on [`CString`]. See
282 /// its documentation for more.
284 /// [`String`]: ../string/struct.String.html
285 /// [`CString`]: struct.CString.html
286 /// [`CString::into_string`]: struct.CString.html#method.into_string
287 #[derive(Clone, PartialEq, Eq, Debug)]
288 #[stable(feature = "cstring_into", since = "1.7.0")]
289 pub struct IntoStringError {
295 /// Creates a new C-compatible string from a container of bytes.
297 /// This function will consume the provided data and use the
298 /// underlying bytes to construct a new string, ensuring that
299 /// there is a trailing 0 byte. This trailing 0 byte will be
300 /// appended by this function; the provided data should *not*
301 /// contain any 0 bytes in it.
305 /// ```ignore (extern-declaration)
306 /// use std::ffi::CString;
307 /// use std::os::raw::c_char;
309 /// extern { fn puts(s: *const c_char); }
311 /// let to_print = CString::new("Hello!").expect("CString::new failed");
313 /// puts(to_print.as_ptr());
319 /// This function will return an error if the supplied bytes contain an
320 /// internal 0 byte. The [`NulError`] returned will contain the bytes as well as
321 /// the position of the nul byte.
323 /// [`NulError`]: struct.NulError.html
324 #[stable(feature = "rust1", since = "1.0.0")]
325 pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
327 fn into_vec(self) -> Vec<u8>;
329 impl<T: Into<Vec<u8>>> SpecIntoVec for T {
330 default fn into_vec(self) -> Vec<u8> {
334 // Specialization for avoiding reallocation.
335 impl SpecIntoVec for &'_ [u8] {
336 fn into_vec(self) -> Vec<u8> {
337 let mut v = Vec::with_capacity(self.len() + 1);
342 impl SpecIntoVec for &'_ str {
343 fn into_vec(self) -> Vec<u8> {
344 let mut v = Vec::with_capacity(self.len() + 1);
345 v.extend(self.as_bytes());
350 Self::_new(SpecIntoVec::into_vec(t))
353 fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
354 match memchr::memchr(0, &bytes) {
355 Some(i) => Err(NulError(i, bytes)),
356 None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
360 /// Creates a C-compatible string by consuming a byte vector,
361 /// without checking for interior 0 bytes.
363 /// This method is equivalent to [`new`] except that no runtime assertion
364 /// is made that `v` contains no 0 bytes, and it requires an actual
365 /// byte vector, not anything that can be converted to one with Into.
367 /// [`new`]: #method.new
372 /// use std::ffi::CString;
374 /// let raw = b"foo".to_vec();
376 /// let c_string = CString::from_vec_unchecked(raw);
379 #[stable(feature = "rust1", since = "1.0.0")]
380 pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
383 CString { inner: v.into_boxed_slice() }
386 /// Retakes ownership of a `CString` that was transferred to C via [`into_raw`].
388 /// Additionally, the length of the string will be recalculated from the pointer.
392 /// This should only ever be called with a pointer that was earlier
393 /// obtained by calling [`into_raw`] on a `CString`. Other usage (e.g., trying to take
394 /// ownership of a string that was allocated by foreign code) is likely to lead
395 /// to undefined behavior or allocator corruption.
397 /// > **Note:** If you need to borrow a string that was allocated by
398 /// > foreign code, use [`CStr`]. If you need to take ownership of
399 /// > a string that was allocated by foreign code, you will need to
400 /// > make your own provisions for freeing it appropriately, likely
401 /// > with the foreign code's API to do that.
403 /// [`into_raw`]: #method.into_raw
404 /// [`CStr`]: struct.CStr.html
408 /// Creates a `CString`, pass ownership to an `extern` function (via raw pointer), then retake
409 /// ownership with `from_raw`:
411 /// ```ignore (extern-declaration)
412 /// use std::ffi::CString;
413 /// use std::os::raw::c_char;
416 /// fn some_extern_function(s: *mut c_char);
419 /// let c_string = CString::new("Hello!").expect("CString::new failed");
420 /// let raw = c_string.into_raw();
422 /// some_extern_function(raw);
423 /// let c_string = CString::from_raw(raw);
426 #[stable(feature = "cstr_memory", since = "1.4.0")]
427 pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
428 let len = sys::strlen(ptr) + 1; // Including the NUL byte
429 let slice = slice::from_raw_parts_mut(ptr, len as usize);
430 CString { inner: Box::from_raw(slice as *mut [c_char] as *mut [u8]) }
433 /// Consumes the `CString` and transfers ownership of the string to a C caller.
435 /// The pointer which this function returns must be returned to Rust and reconstituted using
436 /// [`from_raw`] to be properly deallocated. Specifically, one
437 /// should *not* use the standard C `free()` function to deallocate
440 /// Failure to call [`from_raw`] will lead to a memory leak.
442 /// [`from_raw`]: #method.from_raw
447 /// use std::ffi::CString;
449 /// let c_string = CString::new("foo").expect("CString::new failed");
451 /// let ptr = c_string.into_raw();
454 /// assert_eq!(b'f', *ptr as u8);
455 /// assert_eq!(b'o', *ptr.offset(1) as u8);
456 /// assert_eq!(b'o', *ptr.offset(2) as u8);
457 /// assert_eq!(b'\0', *ptr.offset(3) as u8);
459 /// // retake pointer to free memory
460 /// let _ = CString::from_raw(ptr);
464 #[stable(feature = "cstr_memory", since = "1.4.0")]
465 pub fn into_raw(self) -> *mut c_char {
466 Box::into_raw(self.into_inner()) as *mut c_char
469 /// Converts the `CString` into a [`String`] if it contains valid UTF-8 data.
471 /// On failure, ownership of the original `CString` is returned.
473 /// [`String`]: ../string/struct.String.html
478 /// use std::ffi::CString;
480 /// let valid_utf8 = vec![b'f', b'o', b'o'];
481 /// let cstring = CString::new(valid_utf8).expect("CString::new failed");
482 /// assert_eq!(cstring.into_string().expect("into_string() call failed"), "foo");
484 /// let invalid_utf8 = vec![b'f', 0xff, b'o', b'o'];
485 /// let cstring = CString::new(invalid_utf8).expect("CString::new failed");
486 /// let err = cstring.into_string().err().expect("into_string().err() failed");
487 /// assert_eq!(err.utf8_error().valid_up_to(), 1);
490 #[stable(feature = "cstring_into", since = "1.7.0")]
491 pub fn into_string(self) -> Result<String, IntoStringError> {
492 String::from_utf8(self.into_bytes()).map_err(|e| IntoStringError {
493 error: e.utf8_error(),
494 inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
498 /// Consumes the `CString` and returns the underlying byte buffer.
500 /// The returned buffer does **not** contain the trailing nul
501 /// terminator, and it is guaranteed to not have any interior nul
507 /// use std::ffi::CString;
509 /// let c_string = CString::new("foo").expect("CString::new failed");
510 /// let bytes = c_string.into_bytes();
511 /// assert_eq!(bytes, vec![b'f', b'o', b'o']);
513 #[stable(feature = "cstring_into", since = "1.7.0")]
514 pub fn into_bytes(self) -> Vec<u8> {
515 let mut vec = self.into_inner().into_vec();
516 let _nul = vec.pop();
517 debug_assert_eq!(_nul, Some(0u8));
521 /// Equivalent to the [`into_bytes`] function except that the returned vector
522 /// includes the trailing nul terminator.
524 /// [`into_bytes`]: #method.into_bytes
529 /// use std::ffi::CString;
531 /// let c_string = CString::new("foo").expect("CString::new failed");
532 /// let bytes = c_string.into_bytes_with_nul();
533 /// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
535 #[stable(feature = "cstring_into", since = "1.7.0")]
536 pub fn into_bytes_with_nul(self) -> Vec<u8> {
537 self.into_inner().into_vec()
540 /// Returns the contents of this `CString` as a slice of bytes.
542 /// The returned slice does **not** contain the trailing nul
543 /// terminator, and it is guaranteed to not have any interior nul
544 /// bytes. If you need the nul terminator, use
545 /// [`as_bytes_with_nul`] instead.
547 /// [`as_bytes_with_nul`]: #method.as_bytes_with_nul
552 /// use std::ffi::CString;
554 /// let c_string = CString::new("foo").expect("CString::new failed");
555 /// let bytes = c_string.as_bytes();
556 /// assert_eq!(bytes, &[b'f', b'o', b'o']);
559 #[stable(feature = "rust1", since = "1.0.0")]
560 pub fn as_bytes(&self) -> &[u8] {
561 &self.inner[..self.inner.len() - 1]
564 /// Equivalent to the [`as_bytes`] function except that the returned slice
565 /// includes the trailing nul terminator.
567 /// [`as_bytes`]: #method.as_bytes
572 /// use std::ffi::CString;
574 /// let c_string = CString::new("foo").expect("CString::new failed");
575 /// let bytes = c_string.as_bytes_with_nul();
576 /// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
579 #[stable(feature = "rust1", since = "1.0.0")]
580 pub fn as_bytes_with_nul(&self) -> &[u8] {
584 /// Extracts a [`CStr`] slice containing the entire string.
586 /// [`CStr`]: struct.CStr.html
591 /// use std::ffi::{CString, CStr};
593 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
594 /// let cstr = c_string.as_c_str();
596 /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
599 #[stable(feature = "as_c_str", since = "1.20.0")]
600 pub fn as_c_str(&self) -> &CStr {
604 /// Converts this `CString` into a boxed [`CStr`].
606 /// [`CStr`]: struct.CStr.html
611 /// use std::ffi::{CString, CStr};
613 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
614 /// let boxed = c_string.into_boxed_c_str();
615 /// assert_eq!(&*boxed,
616 /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
618 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
619 pub fn into_boxed_c_str(self) -> Box<CStr> {
620 unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) }
623 /// Bypass "move out of struct which implements [`Drop`] trait" restriction.
625 /// [`Drop`]: ../ops/trait.Drop.html
626 fn into_inner(self) -> Box<[u8]> {
627 // Rationale: `mem::forget(self)` invalidates the previous call to `ptr::read(&self.inner)`
628 // so we use `ManuallyDrop` to ensure `self` is not dropped.
629 // Then we can return the box directly without invalidating it.
630 // See https://github.com/rust-lang/rust/issues/62553.
631 let this = mem::ManuallyDrop::new(self);
632 unsafe { ptr::read(&this.inner) }
636 // Turns this `CString` into an empty string to prevent
637 // memory-unsafe code from working by accident. Inline
638 // to prevent LLVM from optimizing it away in debug builds.
639 #[stable(feature = "cstring_drop", since = "1.13.0")]
640 impl Drop for CString {
644 *self.inner.get_unchecked_mut(0) = 0;
649 #[stable(feature = "rust1", since = "1.0.0")]
650 impl ops::Deref for CString {
654 fn deref(&self) -> &CStr {
655 unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
659 #[stable(feature = "rust1", since = "1.0.0")]
660 impl fmt::Debug for CString {
661 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
662 fmt::Debug::fmt(&**self, f)
666 #[stable(feature = "cstring_into", since = "1.7.0")]
667 impl From<CString> for Vec<u8> {
668 /// Converts a [`CString`] into a [`Vec`]`<u8>`.
670 /// The conversion consumes the [`CString`], and removes the terminating NUL byte.
672 /// [`Vec`]: ../vec/struct.Vec.html
673 /// [`CString`]: ../ffi/struct.CString.html
675 fn from(s: CString) -> Vec<u8> {
680 #[stable(feature = "cstr_debug", since = "1.3.0")]
681 impl fmt::Debug for CStr {
682 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
684 for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
685 f.write_char(byte as char)?;
691 #[stable(feature = "cstr_default", since = "1.10.0")]
692 impl Default for &CStr {
693 fn default() -> Self {
694 const SLICE: &[c_char] = &[0];
695 unsafe { CStr::from_ptr(SLICE.as_ptr()) }
699 #[stable(feature = "cstr_default", since = "1.10.0")]
700 impl Default for CString {
701 /// Creates an empty `CString`.
702 fn default() -> CString {
703 let a: &CStr = Default::default();
708 #[stable(feature = "cstr_borrow", since = "1.3.0")]
709 impl Borrow<CStr> for CString {
711 fn borrow(&self) -> &CStr {
716 #[stable(feature = "cstring_from_cow_cstr", since = "1.28.0")]
717 impl<'a> From<Cow<'a, CStr>> for CString {
719 fn from(s: Cow<'a, CStr>) -> Self {
724 #[stable(feature = "box_from_c_str", since = "1.17.0")]
725 impl From<&CStr> for Box<CStr> {
726 fn from(s: &CStr) -> Box<CStr> {
727 let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul());
728 unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
732 #[stable(feature = "c_string_from_box", since = "1.18.0")]
733 impl From<Box<CStr>> for CString {
734 /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating.
736 /// [`Box`]: ../boxed/struct.Box.html
737 /// [`CString`]: ../ffi/struct.CString.html
739 fn from(s: Box<CStr>) -> CString {
744 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
745 impl Clone for Box<CStr> {
747 fn clone(&self) -> Self {
752 #[stable(feature = "box_from_c_string", since = "1.20.0")]
753 impl From<CString> for Box<CStr> {
754 /// Converts a [`CString`] into a [`Box`]`<CStr>` without copying or allocating.
756 /// [`CString`]: ../ffi/struct.CString.html
757 /// [`Box`]: ../boxed/struct.Box.html
759 fn from(s: CString) -> Box<CStr> {
764 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
765 impl<'a> From<CString> for Cow<'a, CStr> {
767 fn from(s: CString) -> Cow<'a, CStr> {
772 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
773 impl<'a> From<&'a CStr> for Cow<'a, CStr> {
775 fn from(s: &'a CStr) -> Cow<'a, CStr> {
780 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
781 impl<'a> From<&'a CString> for Cow<'a, CStr> {
783 fn from(s: &'a CString) -> Cow<'a, CStr> {
784 Cow::Borrowed(s.as_c_str())
788 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
789 impl From<CString> for Arc<CStr> {
790 /// Converts a [`CString`] into a [`Arc`]`<CStr>` without copying or allocating.
792 /// [`CString`]: ../ffi/struct.CString.html
793 /// [`Arc`]: ../sync/struct.Arc.html
795 fn from(s: CString) -> Arc<CStr> {
796 let arc: Arc<[u8]> = Arc::from(s.into_inner());
797 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
801 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
802 impl From<&CStr> for Arc<CStr> {
804 fn from(s: &CStr) -> Arc<CStr> {
805 let arc: Arc<[u8]> = Arc::from(s.to_bytes_with_nul());
806 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
810 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
811 impl From<CString> for Rc<CStr> {
812 /// Converts a [`CString`] into a [`Rc`]`<CStr>` without copying or allocating.
814 /// [`CString`]: ../ffi/struct.CString.html
815 /// [`Rc`]: ../rc/struct.Rc.html
817 fn from(s: CString) -> Rc<CStr> {
818 let rc: Rc<[u8]> = Rc::from(s.into_inner());
819 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
823 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
824 impl From<&CStr> for Rc<CStr> {
826 fn from(s: &CStr) -> Rc<CStr> {
827 let rc: Rc<[u8]> = Rc::from(s.to_bytes_with_nul());
828 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
832 #[stable(feature = "default_box_extra", since = "1.17.0")]
833 impl Default for Box<CStr> {
834 fn default() -> Box<CStr> {
835 let boxed: Box<[u8]> = Box::from([0]);
836 unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
841 /// Returns the position of the nul byte in the slice that caused
842 /// [`CString::new`] to fail.
844 /// [`CString::new`]: struct.CString.html#method.new
849 /// use std::ffi::CString;
851 /// let nul_error = CString::new("foo\0bar").unwrap_err();
852 /// assert_eq!(nul_error.nul_position(), 3);
854 /// let nul_error = CString::new("foo bar\0").unwrap_err();
855 /// assert_eq!(nul_error.nul_position(), 7);
857 #[stable(feature = "rust1", since = "1.0.0")]
858 pub fn nul_position(&self) -> usize {
862 /// Consumes this error, returning the underlying vector of bytes which
863 /// generated the error in the first place.
868 /// use std::ffi::CString;
870 /// let nul_error = CString::new("foo\0bar").unwrap_err();
871 /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
873 #[stable(feature = "rust1", since = "1.0.0")]
874 pub fn into_vec(self) -> Vec<u8> {
879 #[stable(feature = "rust1", since = "1.0.0")]
880 impl Error for NulError {
882 fn description(&self) -> &str {
883 "nul byte found in data"
887 #[stable(feature = "rust1", since = "1.0.0")]
888 impl fmt::Display for NulError {
889 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
890 write!(f, "nul byte found in provided data at position: {}", self.0)
894 #[stable(feature = "rust1", since = "1.0.0")]
895 impl From<NulError> for io::Error {
896 /// Converts a [`NulError`] into a [`io::Error`].
898 /// [`NulError`]: ../ffi/struct.NulError.html
899 /// [`io::Error`]: ../io/struct.Error.html
900 fn from(_: NulError) -> io::Error {
901 io::Error::new(io::ErrorKind::InvalidInput, "data provided contains a nul byte")
905 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
906 impl Error for FromBytesWithNulError {
908 fn description(&self) -> &str {
910 FromBytesWithNulErrorKind::InteriorNul(..) => {
911 "data provided contains an interior nul byte"
913 FromBytesWithNulErrorKind::NotNulTerminated => "data provided is not nul terminated",
918 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
919 impl fmt::Display for FromBytesWithNulError {
920 #[allow(deprecated, deprecated_in_future)]
921 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
922 f.write_str(self.description())?;
923 if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind {
924 write!(f, " at byte pos {}", pos)?;
930 impl IntoStringError {
931 /// Consumes this error, returning original [`CString`] which generated the
934 /// [`CString`]: struct.CString.html
935 #[stable(feature = "cstring_into", since = "1.7.0")]
936 pub fn into_cstring(self) -> CString {
940 /// Access the underlying UTF-8 error that was the cause of this error.
941 #[stable(feature = "cstring_into", since = "1.7.0")]
942 pub fn utf8_error(&self) -> Utf8Error {
947 #[stable(feature = "cstring_into", since = "1.7.0")]
948 impl Error for IntoStringError {
950 fn description(&self) -> &str {
951 "C string contained non-utf8 bytes"
954 fn source(&self) -> Option<&(dyn Error + 'static)> {
959 #[stable(feature = "cstring_into", since = "1.7.0")]
960 impl fmt::Display for IntoStringError {
961 #[allow(deprecated, deprecated_in_future)]
962 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
963 self.description().fmt(f)
968 /// Wraps a raw C string with a safe C string wrapper.
970 /// This function will wrap the provided `ptr` with a `CStr` wrapper, which
971 /// allows inspection and interoperation of non-owned C strings. The total
972 /// size of the raw C string must be smaller than `isize::MAX` **bytes**
973 /// in memory due to calling the `slice::from_raw_parts` function.
974 /// This method is unsafe for a number of reasons:
976 /// * There is no guarantee to the validity of `ptr`.
977 /// * The returned lifetime is not guaranteed to be the actual lifetime of
979 /// * There is no guarantee that the memory pointed to by `ptr` contains a
980 /// valid nul terminator byte at the end of the string.
981 /// * It is not guaranteed that the memory pointed by `ptr` won't change
982 /// before the `CStr` has been destroyed.
984 /// > **Note**: This operation is intended to be a 0-cost cast but it is
985 /// > currently implemented with an up-front calculation of the length of
986 /// > the string. This is not guaranteed to always be the case.
990 /// ```ignore (extern-declaration)
992 /// use std::ffi::CStr;
993 /// use std::os::raw::c_char;
996 /// fn my_string() -> *const c_char;
1000 /// let slice = CStr::from_ptr(my_string());
1001 /// println!("string returned: {}", slice.to_str().unwrap());
1005 #[stable(feature = "rust1", since = "1.0.0")]
1006 pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
1007 let len = sys::strlen(ptr);
1008 let ptr = ptr as *const u8;
1009 CStr::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr, len as usize + 1))
1012 /// Creates a C string wrapper from a byte slice.
1014 /// This function will cast the provided `bytes` to a `CStr`
1015 /// wrapper after ensuring that the byte slice is nul-terminated
1016 /// and does not contain any interior nul bytes.
1021 /// use std::ffi::CStr;
1023 /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
1024 /// assert!(cstr.is_ok());
1027 /// Creating a `CStr` without a trailing nul terminator is an error:
1030 /// use std::ffi::CStr;
1032 /// let cstr = CStr::from_bytes_with_nul(b"hello");
1033 /// assert!(cstr.is_err());
1036 /// Creating a `CStr` with an interior nul byte is an error:
1039 /// use std::ffi::CStr;
1041 /// let cstr = CStr::from_bytes_with_nul(b"he\0llo\0");
1042 /// assert!(cstr.is_err());
1044 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
1045 pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError> {
1046 let nul_pos = memchr::memchr(0, bytes);
1047 if let Some(nul_pos) = nul_pos {
1048 if nul_pos + 1 != bytes.len() {
1049 return Err(FromBytesWithNulError::interior_nul(nul_pos));
1051 Ok(unsafe { CStr::from_bytes_with_nul_unchecked(bytes) })
1053 Err(FromBytesWithNulError::not_nul_terminated())
1057 /// Unsafely creates a C string wrapper from a byte slice.
1059 /// This function will cast the provided `bytes` to a `CStr` wrapper without
1060 /// performing any sanity checks. The provided slice **must** be nul-terminated
1061 /// and not contain any interior nul bytes.
1066 /// use std::ffi::{CStr, CString};
1069 /// let cstring = CString::new("hello").expect("CString::new failed");
1070 /// let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
1071 /// assert_eq!(cstr, &*cstring);
1075 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
1076 #[rustc_const_unstable(feature = "const_cstr_unchecked", issue = "none")]
1077 pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
1078 &*(bytes as *const [u8] as *const CStr)
1081 /// Returns the inner pointer to this C string.
1083 /// The returned pointer will be valid for as long as `self` is, and points
1084 /// to a contiguous region of memory terminated with a 0 byte to represent
1085 /// the end of the string.
1089 /// The returned pointer is read-only; writing to it (including passing it
1090 /// to C code that writes to it) causes undefined behavior.
1092 /// It is your responsibility to make sure that the underlying memory is not
1093 /// freed too early. For example, the following code will cause undefined
1094 /// behavior when `ptr` is used inside the `unsafe` block:
1097 /// # #![allow(unused_must_use)]
1098 /// use std::ffi::CString;
1100 /// let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
1102 /// // `ptr` is dangling
1107 /// This happens because the pointer returned by `as_ptr` does not carry any
1108 /// lifetime information and the [`CString`] is deallocated immediately after
1109 /// the `CString::new("Hello").expect("CString::new failed").as_ptr()` expression is evaluated.
1110 /// To fix the problem, bind the `CString` to a local variable:
1113 /// # #![allow(unused_must_use)]
1114 /// use std::ffi::CString;
1116 /// let hello = CString::new("Hello").expect("CString::new failed");
1117 /// let ptr = hello.as_ptr();
1119 /// // `ptr` is valid because `hello` is in scope
1124 /// This way, the lifetime of the `CString` in `hello` encompasses
1125 /// the lifetime of `ptr` and the `unsafe` block.
1127 /// [`CString`]: struct.CString.html
1129 #[stable(feature = "rust1", since = "1.0.0")]
1130 #[rustc_const_stable(feature = "const_str_as_ptr", since = "1.32.0")]
1131 pub const fn as_ptr(&self) -> *const c_char {
1135 /// Converts this C string to a byte slice.
1137 /// The returned slice will **not** contain the trailing nul terminator that this C
1140 /// > **Note**: This method is currently implemented as a constant-time
1141 /// > cast, but it is planned to alter its definition in the future to
1142 /// > perform the length calculation whenever this method is called.
1147 /// use std::ffi::CStr;
1149 /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1150 /// assert_eq!(cstr.to_bytes(), b"foo");
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 pub fn to_bytes(&self) -> &[u8] {
1155 let bytes = self.to_bytes_with_nul();
1156 &bytes[..bytes.len() - 1]
1159 /// Converts this C string to a byte slice containing the trailing 0 byte.
1161 /// This function is the equivalent of [`to_bytes`] except that it will retain
1162 /// the trailing nul terminator instead of chopping it off.
1164 /// > **Note**: This method is currently implemented as a 0-cost cast, but
1165 /// > it is planned to alter its definition in the future to perform the
1166 /// > length calculation whenever this method is called.
1168 /// [`to_bytes`]: #method.to_bytes
1173 /// use std::ffi::CStr;
1175 /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1176 /// assert_eq!(cstr.to_bytes_with_nul(), b"foo\0");
1179 #[stable(feature = "rust1", since = "1.0.0")]
1180 pub fn to_bytes_with_nul(&self) -> &[u8] {
1181 unsafe { &*(&self.inner as *const [c_char] as *const [u8]) }
1184 /// Yields a [`&str`] slice if the `CStr` contains valid UTF-8.
1186 /// If the contents of the `CStr` are valid UTF-8 data, this
1187 /// function will return the corresponding [`&str`] slice. Otherwise,
1188 /// it will return an error with details of where UTF-8 validation failed.
1190 /// [`&str`]: ../primitive.str.html
1195 /// use std::ffi::CStr;
1197 /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1198 /// assert_eq!(cstr.to_str(), Ok("foo"));
1200 #[stable(feature = "cstr_to_str", since = "1.4.0")]
1201 pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
1202 // N.B., when `CStr` is changed to perform the length check in `.to_bytes()`
1203 // instead of in `from_ptr()`, it may be worth considering if this should
1204 // be rewritten to do the UTF-8 check inline with the length calculation
1205 // instead of doing it afterwards.
1206 str::from_utf8(self.to_bytes())
1209 /// Converts a `CStr` into a [`Cow`]`<`[`str`]`>`.
1211 /// If the contents of the `CStr` are valid UTF-8 data, this
1212 /// function will return a [`Cow`]`::`[`Borrowed`]`(`[`&str`]`)`
1213 /// with the corresponding [`&str`] slice. Otherwise, it will
1214 /// replace any invalid UTF-8 sequences with
1215 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD] and return a
1216 /// [`Cow`]`::`[`Owned`]`(`[`String`]`)` with the result.
1218 /// [`Cow`]: ../borrow/enum.Cow.html
1219 /// [`Borrowed`]: ../borrow/enum.Cow.html#variant.Borrowed
1220 /// [`Owned`]: ../borrow/enum.Cow.html#variant.Owned
1221 /// [`str`]: ../primitive.str.html
1222 /// [`String`]: ../string/struct.String.html
1223 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
1227 /// Calling `to_string_lossy` on a `CStr` containing valid UTF-8:
1230 /// use std::borrow::Cow;
1231 /// use std::ffi::CStr;
1233 /// let cstr = CStr::from_bytes_with_nul(b"Hello World\0")
1234 /// .expect("CStr::from_bytes_with_nul failed");
1235 /// assert_eq!(cstr.to_string_lossy(), Cow::Borrowed("Hello World"));
1238 /// Calling `to_string_lossy` on a `CStr` containing invalid UTF-8:
1241 /// use std::borrow::Cow;
1242 /// use std::ffi::CStr;
1244 /// let cstr = CStr::from_bytes_with_nul(b"Hello \xF0\x90\x80World\0")
1245 /// .expect("CStr::from_bytes_with_nul failed");
1247 /// cstr.to_string_lossy(),
1248 /// Cow::Owned(String::from("Hello �World")) as Cow<'_, str>
1251 #[stable(feature = "cstr_to_str", since = "1.4.0")]
1252 pub fn to_string_lossy(&self) -> Cow<'_, str> {
1253 String::from_utf8_lossy(self.to_bytes())
1256 /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating.
1258 /// [`Box`]: ../boxed/struct.Box.html
1259 /// [`CString`]: struct.CString.html
1264 /// use std::ffi::CString;
1266 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
1267 /// let boxed = c_string.into_boxed_c_str();
1268 /// assert_eq!(boxed.into_c_string(), CString::new("foo").expect("CString::new failed"));
1270 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
1271 pub fn into_c_string(self: Box<CStr>) -> CString {
1272 let raw = Box::into_raw(self) as *mut [u8];
1273 CString { inner: unsafe { Box::from_raw(raw) } }
1277 #[stable(feature = "rust1", since = "1.0.0")]
1278 impl PartialEq for CStr {
1279 fn eq(&self, other: &CStr) -> bool {
1280 self.to_bytes().eq(other.to_bytes())
1283 #[stable(feature = "rust1", since = "1.0.0")]
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 impl PartialOrd for CStr {
1287 fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
1288 self.to_bytes().partial_cmp(&other.to_bytes())
1291 #[stable(feature = "rust1", since = "1.0.0")]
1293 fn cmp(&self, other: &CStr) -> Ordering {
1294 self.to_bytes().cmp(&other.to_bytes())
1298 #[stable(feature = "cstr_borrow", since = "1.3.0")]
1299 impl ToOwned for CStr {
1300 type Owned = CString;
1302 fn to_owned(&self) -> CString {
1303 CString { inner: self.to_bytes_with_nul().into() }
1307 #[stable(feature = "cstring_asref", since = "1.7.0")]
1308 impl From<&CStr> for CString {
1309 fn from(s: &CStr) -> CString {
1314 #[stable(feature = "cstring_asref", since = "1.7.0")]
1315 impl ops::Index<ops::RangeFull> for CString {
1319 fn index(&self, _index: ops::RangeFull) -> &CStr {
1324 #[stable(feature = "cstring_asref", since = "1.7.0")]
1325 impl AsRef<CStr> for CStr {
1327 fn as_ref(&self) -> &CStr {
1332 #[stable(feature = "cstring_asref", since = "1.7.0")]
1333 impl AsRef<CStr> for CString {
1335 fn as_ref(&self) -> &CStr {
1343 use crate::borrow::Cow::{Borrowed, Owned};
1344 use crate::collections::hash_map::DefaultHasher;
1345 use crate::hash::{Hash, Hasher};
1346 use crate::os::raw::c_char;
1348 use crate::sync::Arc;
1352 let data = b"123\0";
1353 let ptr = data.as_ptr() as *const c_char;
1355 assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
1356 assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
1362 let s = CString::new("1234").unwrap();
1363 assert_eq!(s.as_bytes(), b"1234");
1364 assert_eq!(s.as_bytes_with_nul(), b"1234\0");
1368 fn build_with_zero1() {
1369 assert!(CString::new(&b"\0"[..]).is_err());
1372 fn build_with_zero2() {
1373 assert!(CString::new(vec![0]).is_err());
1377 fn build_with_zero3() {
1379 let s = CString::from_vec_unchecked(vec![0]);
1380 assert_eq!(s.as_bytes(), b"\0");
1386 let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
1387 assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
1393 let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
1394 assert_eq!(s.to_bytes(), b"12");
1395 assert_eq!(s.to_bytes_with_nul(), b"12\0");
1401 let data = b"123\xE2\x80\xA6\0";
1402 let ptr = data.as_ptr() as *const c_char;
1404 assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
1405 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
1407 let data = b"123\xE2\0";
1408 let ptr = data.as_ptr() as *const c_char;
1410 assert!(CStr::from_ptr(ptr).to_str().is_err());
1411 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
1417 let data = b"123\0";
1418 let ptr = data.as_ptr() as *const c_char;
1420 let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
1421 assert_eq!(owned.as_bytes_with_nul(), data);
1426 let data = b"123\xE2\xFA\xA6\0";
1427 let ptr = data.as_ptr() as *const c_char;
1428 let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
1430 let mut s = DefaultHasher::new();
1432 let cstr_hash = s.finish();
1433 let mut s = DefaultHasher::new();
1434 CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
1435 let cstring_hash = s.finish();
1437 assert_eq!(cstr_hash, cstring_hash);
1441 fn from_bytes_with_nul() {
1442 let data = b"123\0";
1443 let cstr = CStr::from_bytes_with_nul(data);
1444 assert_eq!(cstr.map(CStr::to_bytes), Ok(&b"123"[..]));
1445 let cstr = CStr::from_bytes_with_nul(data);
1446 assert_eq!(cstr.map(CStr::to_bytes_with_nul), Ok(&b"123\0"[..]));
1449 let cstr = CStr::from_bytes_with_nul(data);
1450 let cstr_unchecked = CStr::from_bytes_with_nul_unchecked(data);
1451 assert_eq!(cstr, Ok(cstr_unchecked));
1456 fn from_bytes_with_nul_unterminated() {
1458 let cstr = CStr::from_bytes_with_nul(data);
1459 assert!(cstr.is_err());
1463 fn from_bytes_with_nul_interior() {
1464 let data = b"1\023\0";
1465 let cstr = CStr::from_bytes_with_nul(data);
1466 assert!(cstr.is_err());
1471 let orig: &[u8] = b"Hello, world!\0";
1472 let cstr = CStr::from_bytes_with_nul(orig).unwrap();
1473 let boxed: Box<CStr> = Box::from(cstr);
1474 let cstring = cstr.to_owned().into_boxed_c_str().into_c_string();
1475 assert_eq!(cstr, &*boxed);
1476 assert_eq!(&*boxed, &*cstring);
1477 assert_eq!(&*cstring, cstr);
1481 fn boxed_default() {
1482 let boxed = <Box<CStr>>::default();
1483 assert_eq!(boxed.to_bytes_with_nul(), &[0]);
1488 let orig: &[u8] = b"Hello, world!\0";
1489 let cstr = CStr::from_bytes_with_nul(orig).unwrap();
1490 let rc: Rc<CStr> = Rc::from(cstr);
1491 let arc: Arc<CStr> = Arc::from(cstr);
1493 assert_eq!(&*rc, cstr);
1494 assert_eq!(&*arc, cstr);
1496 let rc2: Rc<CStr> = Rc::from(cstr.to_owned());
1497 let arc2: Arc<CStr> = Arc::from(cstr.to_owned());
1499 assert_eq!(&*rc2, cstr);
1500 assert_eq!(&*arc2, cstr);
1504 fn cstr_const_constructor() {
1505 const CSTR: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b"Hello, world!\0") };
1507 assert_eq!(CSTR.to_str().unwrap(), "Hello, world!");