2 use crate::borrow::{Borrow, Cow};
3 use crate::cmp::Ordering;
4 use crate::error::Error;
5 use crate::fmt::{self, Write};
9 use crate::num::NonZeroU8;
11 use crate::os::raw::c_char;
15 use crate::str::{self, Utf8Error};
19 /// A type representing an owned, C-compatible, nul-terminated string with no nul bytes in the
22 /// This type serves the purpose of being able to safely generate a
23 /// C-compatible string from a Rust byte slice or vector. An instance of this
24 /// type is a static guarantee that the underlying bytes contain no interior 0
25 /// bytes ("nul characters") and that the final byte is 0 ("nul terminator").
27 /// `CString` is to [`&CStr`] as [`String`] is to [`&str`]: the former
28 /// in each pair are owned strings; the latter are borrowed
31 /// # Creating a `CString`
33 /// A `CString` is created from either a byte slice or a byte vector,
34 /// or anything that implements [`Into`]`<`[`Vec`]`<`[`u8`]`>>` (for
35 /// example, you can build a `CString` straight out of a [`String`] or
36 /// a [`&str`], since both implement that trait).
38 /// The [`new`] method will actually check that the provided `&[u8]`
39 /// does not have 0 bytes in the middle, and return an error if it
42 /// # Extracting a raw pointer to the whole C string
44 /// `CString` implements a [`as_ptr`] method through the [`Deref`]
45 /// trait. This method will give you a `*const c_char` which you can
46 /// feed directly to extern functions that expect a nul-terminated
47 /// string, like C's `strdup()`. Notice that [`as_ptr`] returns a
48 /// read-only pointer; if the C code writes to it, that causes
49 /// undefined behavior.
51 /// # Extracting a slice of the whole C string
53 /// Alternatively, you can obtain a `&[`[`u8`]`]` slice from a
54 /// `CString` with the [`as_bytes`] method. Slices produced in this
55 /// way do *not* contain the trailing nul terminator. This is useful
56 /// when you will be calling an extern function that takes a `*const
57 /// u8` argument which is not necessarily nul-terminated, plus another
58 /// argument with the length of the string — like C's `strndup()`.
59 /// You can of course get the slice's length with its
60 /// [`len`][slice.len] method.
62 /// If you need a `&[`[`u8`]`]` slice *with* the nul terminator, you
63 /// can use [`as_bytes_with_nul`] instead.
65 /// Once you have the kind of slice you need (with or without a nul
66 /// terminator), you can call the slice's own
67 /// [`as_ptr`][slice.as_ptr] method to get a read-only raw pointer to pass to
68 /// extern functions. See the documentation for that function for a
69 /// discussion on ensuring the lifetime of the raw pointer.
71 /// [`Into`]: ../convert/trait.Into.html
72 /// [`Vec`]: ../vec/struct.Vec.html
73 /// [`String`]: ../string/struct.String.html
74 /// [`&str`]: ../primitive.str.html
75 /// [`u8`]: ../primitive.u8.html
76 /// [`new`]: #method.new
77 /// [`as_bytes`]: #method.as_bytes
78 /// [`as_bytes_with_nul`]: #method.as_bytes_with_nul
79 /// [`as_ptr`]: #method.as_ptr
80 /// [slice.as_ptr]: ../primitive.slice.html#method.as_ptr
81 /// [slice.len]: ../primitive.slice.html#method.len
82 /// [`Deref`]: ../ops/trait.Deref.html
83 /// [`CStr`]: struct.CStr.html
84 /// [`&CStr`]: struct.CStr.html
88 /// ```ignore (extern-declaration)
90 /// use std::ffi::CString;
91 /// use std::os::raw::c_char;
94 /// fn my_printer(s: *const c_char);
97 /// // We are certain that our string doesn't have 0 bytes in the middle,
98 /// // so we can .expect()
99 /// let c_to_print = CString::new("Hello, world!").expect("CString::new failed");
101 /// my_printer(c_to_print.as_ptr());
108 /// `CString` is intended for working with traditional C-style strings
109 /// (a sequence of non-nul bytes terminated by a single nul byte); the
110 /// primary use case for these kinds of strings is interoperating with C-like
111 /// code. Often you will need to transfer ownership to/from that external
112 /// code. It is strongly recommended that you thoroughly read through the
113 /// documentation of `CString` before use, as improper ownership management
114 /// of `CString` instances can lead to invalid memory accesses, memory leaks,
115 /// and other memory errors.
117 #[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
118 #[stable(feature = "rust1", since = "1.0.0")]
120 // Invariant 1: the slice ends with a zero byte and has a length of at least one.
121 // Invariant 2: the slice contains only one zero byte.
122 // Improper usage of unsafe function can break Invariant 2, but not Invariant 1.
126 /// Representation of a borrowed C string.
128 /// This type represents a borrowed reference to a nul-terminated
129 /// array of bytes. It can be constructed safely from a `&[`[`u8`]`]`
130 /// slice, or unsafely from a raw `*const c_char`. It can then be
131 /// converted to a Rust [`&str`] by performing UTF-8 validation, or
132 /// into an owned [`CString`].
134 /// `&CStr` is to [`CString`] as [`&str`] is to [`String`]: the former
135 /// in each pair are borrowed references; the latter are owned
138 /// Note that this structure is **not** `repr(C)` and is not recommended to be
139 /// placed in the signatures of FFI functions. Instead, safe wrappers of FFI
140 /// functions may leverage the unsafe [`from_ptr`] constructor to provide a safe
141 /// interface to other consumers.
145 /// Inspecting a foreign C string:
147 /// ```ignore (extern-declaration)
148 /// use std::ffi::CStr;
149 /// use std::os::raw::c_char;
151 /// extern { fn my_string() -> *const c_char; }
154 /// let slice = CStr::from_ptr(my_string());
155 /// println!("string buffer size without nul terminator: {}", slice.to_bytes().len());
159 /// Passing a Rust-originating C string:
161 /// ```ignore (extern-declaration)
162 /// use std::ffi::{CString, CStr};
163 /// use std::os::raw::c_char;
165 /// fn work(data: &CStr) {
166 /// extern { fn work_with(data: *const c_char); }
168 /// unsafe { work_with(data.as_ptr()) }
171 /// let s = CString::new("data data data data").expect("CString::new failed");
175 /// Converting a foreign C string into a Rust [`String`]:
177 /// ```ignore (extern-declaration)
178 /// use std::ffi::CStr;
179 /// use std::os::raw::c_char;
181 /// extern { fn my_string() -> *const c_char; }
183 /// fn my_string_safe() -> String {
185 /// CStr::from_ptr(my_string()).to_string_lossy().into_owned()
189 /// println!("string: {}", my_string_safe());
192 /// [`u8`]: ../primitive.u8.html
193 /// [`&str`]: ../primitive.str.html
194 /// [`String`]: ../string/struct.String.html
195 /// [`CString`]: struct.CString.html
196 /// [`from_ptr`]: #method.from_ptr
198 #[stable(feature = "rust1", since = "1.0.0")]
200 // `fn from` in `impl From<&CStr> for Box<CStr>` current implementation relies
201 // on `CStr` being layout-compatible with `[u8]`.
202 // When attribute privacy is implemented, `CStr` should be annotated as `#[repr(transparent)]`.
203 // Anyway, `CStr` representation and layout are considered implementation detail, are
204 // not documented and must not be relied upon.
206 // FIXME: this should not be represented with a DST slice but rather with
207 // just a raw `c_char` along with some form of marker to make
208 // this an unsized type. Essentially `sizeof(&CStr)` should be the
209 // same as `sizeof(&c_char)` but `CStr` should be an unsized type.
213 /// An error indicating that an interior nul byte was found.
215 /// While Rust strings may contain nul bytes in the middle, C strings
216 /// can't, as that byte would effectively truncate the string.
218 /// This error is created by the [`new`][`CString::new`] method on
219 /// [`CString`]. See its documentation for more.
221 /// [`CString`]: struct.CString.html
222 /// [`CString::new`]: struct.CString.html#method.new
227 /// use std::ffi::{CString, NulError};
229 /// let _: NulError = CString::new(b"f\0oo".to_vec()).unwrap_err();
231 #[derive(Clone, PartialEq, Eq, Debug)]
232 #[stable(feature = "rust1", since = "1.0.0")]
233 pub struct NulError(usize, Vec<u8>);
235 /// An error indicating that a nul byte was not in the expected position.
237 /// The slice used to create a [`CStr`] must have one and only one nul
238 /// byte at the end of the slice.
240 /// This error is created by the
241 /// [`from_bytes_with_nul`][`CStr::from_bytes_with_nul`] method on
242 /// [`CStr`]. See its documentation for more.
244 /// [`CStr`]: struct.CStr.html
245 /// [`CStr::from_bytes_with_nul`]: struct.CStr.html#method.from_bytes_with_nul
250 /// use std::ffi::{CStr, FromBytesWithNulError};
252 /// let _: FromBytesWithNulError = CStr::from_bytes_with_nul(b"f\0oo").unwrap_err();
254 #[derive(Clone, PartialEq, Eq, Debug)]
255 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
256 pub struct FromBytesWithNulError {
257 kind: FromBytesWithNulErrorKind,
260 #[derive(Clone, PartialEq, Eq, Debug)]
261 enum FromBytesWithNulErrorKind {
266 impl FromBytesWithNulError {
267 fn interior_nul(pos: usize) -> FromBytesWithNulError {
268 FromBytesWithNulError { kind: FromBytesWithNulErrorKind::InteriorNul(pos) }
270 fn not_nul_terminated() -> FromBytesWithNulError {
271 FromBytesWithNulError { kind: FromBytesWithNulErrorKind::NotNulTerminated }
275 /// An error indicating invalid UTF-8 when converting a [`CString`] into a [`String`].
277 /// `CString` is just a wrapper over a buffer of bytes with a nul
278 /// terminator; [`into_string`][`CString::into_string`] performs UTF-8
279 /// validation on those bytes and may return this error.
281 /// This `struct` is created by the
282 /// [`into_string`][`CString::into_string`] method on [`CString`]. See
283 /// its documentation for more.
285 /// [`String`]: ../string/struct.String.html
286 /// [`CString`]: struct.CString.html
287 /// [`CString::into_string`]: struct.CString.html#method.into_string
288 #[derive(Clone, PartialEq, Eq, Debug)]
289 #[stable(feature = "cstring_into", since = "1.7.0")]
290 pub struct IntoStringError {
296 /// Creates a new C-compatible string from a container of bytes.
298 /// This function will consume the provided data and use the
299 /// underlying bytes to construct a new string, ensuring that
300 /// there is a trailing 0 byte. This trailing 0 byte will be
301 /// appended by this function; the provided data should *not*
302 /// contain any 0 bytes in it.
306 /// ```ignore (extern-declaration)
307 /// use std::ffi::CString;
308 /// use std::os::raw::c_char;
310 /// extern { fn puts(s: *const c_char); }
312 /// let to_print = CString::new("Hello!").expect("CString::new failed");
314 /// puts(to_print.as_ptr());
320 /// This function will return an error if the supplied bytes contain an
321 /// internal 0 byte. The [`NulError`] returned will contain the bytes as well as
322 /// the position of the nul byte.
324 /// [`NulError`]: struct.NulError.html
325 #[stable(feature = "rust1", since = "1.0.0")]
326 pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
328 fn into_vec(self) -> Vec<u8>;
330 impl<T: Into<Vec<u8>>> SpecIntoVec for T {
331 default fn into_vec(self) -> Vec<u8> {
335 // Specialization for avoiding reallocation.
336 impl SpecIntoVec for &'_ [u8] {
337 fn into_vec(self) -> Vec<u8> {
338 let mut v = Vec::with_capacity(self.len() + 1);
343 impl SpecIntoVec for &'_ str {
344 fn into_vec(self) -> Vec<u8> {
345 let mut v = Vec::with_capacity(self.len() + 1);
346 v.extend(self.as_bytes());
351 Self::_new(SpecIntoVec::into_vec(t))
354 fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
355 match memchr::memchr(0, &bytes) {
356 Some(i) => Err(NulError(i, bytes)),
357 None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
361 /// Creates a C-compatible string by consuming a byte vector,
362 /// without checking for interior 0 bytes.
364 /// This method is equivalent to [`new`] except that no runtime assertion
365 /// is made that `v` contains no 0 bytes, and it requires an actual
366 /// byte vector, not anything that can be converted to one with Into.
368 /// [`new`]: #method.new
373 /// use std::ffi::CString;
375 /// let raw = b"foo".to_vec();
377 /// let c_string = CString::from_vec_unchecked(raw);
380 #[stable(feature = "rust1", since = "1.0.0")]
381 pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
384 CString { inner: v.into_boxed_slice() }
387 /// Retakes ownership of a `CString` that was transferred to C via [`into_raw`].
389 /// Additionally, the length of the string will be recalculated from the pointer.
393 /// This should only ever be called with a pointer that was earlier
394 /// obtained by calling [`into_raw`] on a `CString`. Other usage (e.g., trying to take
395 /// ownership of a string that was allocated by foreign code) is likely to lead
396 /// to undefined behavior or allocator corruption.
398 /// > **Note:** If you need to borrow a string that was allocated by
399 /// > foreign code, use [`CStr`]. If you need to take ownership of
400 /// > a string that was allocated by foreign code, you will need to
401 /// > make your own provisions for freeing it appropriately, likely
402 /// > with the foreign code's API to do that.
404 /// [`into_raw`]: #method.into_raw
405 /// [`CStr`]: struct.CStr.html
409 /// Creates a `CString`, pass ownership to an `extern` function (via raw pointer), then retake
410 /// ownership with `from_raw`:
412 /// ```ignore (extern-declaration)
413 /// use std::ffi::CString;
414 /// use std::os::raw::c_char;
417 /// fn some_extern_function(s: *mut c_char);
420 /// let c_string = CString::new("Hello!").expect("CString::new failed");
421 /// let raw = c_string.into_raw();
423 /// some_extern_function(raw);
424 /// let c_string = CString::from_raw(raw);
427 #[stable(feature = "cstr_memory", since = "1.4.0")]
428 pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
429 let len = sys::strlen(ptr) + 1; // Including the NUL byte
430 let slice = slice::from_raw_parts_mut(ptr, len as usize);
431 CString { inner: Box::from_raw(slice as *mut [c_char] as *mut [u8]) }
434 /// Consumes the `CString` and transfers ownership of the string to a C caller.
436 /// The pointer which this function returns must be returned to Rust and reconstituted using
437 /// [`from_raw`] to be properly deallocated. Specifically, one
438 /// should *not* use the standard C `free()` function to deallocate
441 /// Failure to call [`from_raw`] will lead to a memory leak.
443 /// [`from_raw`]: #method.from_raw
448 /// use std::ffi::CString;
450 /// let c_string = CString::new("foo").expect("CString::new failed");
452 /// let ptr = c_string.into_raw();
455 /// assert_eq!(b'f', *ptr as u8);
456 /// assert_eq!(b'o', *ptr.offset(1) as u8);
457 /// assert_eq!(b'o', *ptr.offset(2) as u8);
458 /// assert_eq!(b'\0', *ptr.offset(3) as u8);
460 /// // retake pointer to free memory
461 /// let _ = CString::from_raw(ptr);
465 #[stable(feature = "cstr_memory", since = "1.4.0")]
466 pub fn into_raw(self) -> *mut c_char {
467 Box::into_raw(self.into_inner()) as *mut c_char
470 /// Converts the `CString` into a [`String`] if it contains valid UTF-8 data.
472 /// On failure, ownership of the original `CString` is returned.
474 /// [`String`]: ../string/struct.String.html
479 /// use std::ffi::CString;
481 /// let valid_utf8 = vec![b'f', b'o', b'o'];
482 /// let cstring = CString::new(valid_utf8).expect("CString::new failed");
483 /// assert_eq!(cstring.into_string().expect("into_string() call failed"), "foo");
485 /// let invalid_utf8 = vec![b'f', 0xff, b'o', b'o'];
486 /// let cstring = CString::new(invalid_utf8).expect("CString::new failed");
487 /// let err = cstring.into_string().err().expect("into_string().err() failed");
488 /// assert_eq!(err.utf8_error().valid_up_to(), 1);
491 #[stable(feature = "cstring_into", since = "1.7.0")]
492 pub fn into_string(self) -> Result<String, IntoStringError> {
493 String::from_utf8(self.into_bytes()).map_err(|e| IntoStringError {
494 error: e.utf8_error(),
495 inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
499 /// Consumes the `CString` and returns the underlying byte buffer.
501 /// The returned buffer does **not** contain the trailing nul
502 /// terminator, and it is guaranteed to not have any interior nul
508 /// use std::ffi::CString;
510 /// let c_string = CString::new("foo").expect("CString::new failed");
511 /// let bytes = c_string.into_bytes();
512 /// assert_eq!(bytes, vec![b'f', b'o', b'o']);
514 #[stable(feature = "cstring_into", since = "1.7.0")]
515 pub fn into_bytes(self) -> Vec<u8> {
516 let mut vec = self.into_inner().into_vec();
517 let _nul = vec.pop();
518 debug_assert_eq!(_nul, Some(0u8));
522 /// Equivalent to the [`into_bytes`] function except that the returned vector
523 /// includes the trailing nul terminator.
525 /// [`into_bytes`]: #method.into_bytes
530 /// use std::ffi::CString;
532 /// let c_string = CString::new("foo").expect("CString::new failed");
533 /// let bytes = c_string.into_bytes_with_nul();
534 /// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
536 #[stable(feature = "cstring_into", since = "1.7.0")]
537 pub fn into_bytes_with_nul(self) -> Vec<u8> {
538 self.into_inner().into_vec()
541 /// Returns the contents of this `CString` as a slice of bytes.
543 /// The returned slice does **not** contain the trailing nul
544 /// terminator, and it is guaranteed to not have any interior nul
545 /// bytes. If you need the nul terminator, use
546 /// [`as_bytes_with_nul`] instead.
548 /// [`as_bytes_with_nul`]: #method.as_bytes_with_nul
553 /// use std::ffi::CString;
555 /// let c_string = CString::new("foo").expect("CString::new failed");
556 /// let bytes = c_string.as_bytes();
557 /// assert_eq!(bytes, &[b'f', b'o', b'o']);
560 #[stable(feature = "rust1", since = "1.0.0")]
561 pub fn as_bytes(&self) -> &[u8] {
562 &self.inner[..self.inner.len() - 1]
565 /// Equivalent to the [`as_bytes`] function except that the returned slice
566 /// includes the trailing nul terminator.
568 /// [`as_bytes`]: #method.as_bytes
573 /// use std::ffi::CString;
575 /// let c_string = CString::new("foo").expect("CString::new failed");
576 /// let bytes = c_string.as_bytes_with_nul();
577 /// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
580 #[stable(feature = "rust1", since = "1.0.0")]
581 pub fn as_bytes_with_nul(&self) -> &[u8] {
585 /// Extracts a [`CStr`] slice containing the entire string.
587 /// [`CStr`]: struct.CStr.html
592 /// use std::ffi::{CString, CStr};
594 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
595 /// let cstr = c_string.as_c_str();
597 /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
600 #[stable(feature = "as_c_str", since = "1.20.0")]
601 pub fn as_c_str(&self) -> &CStr {
605 /// Converts this `CString` into a boxed [`CStr`].
607 /// [`CStr`]: struct.CStr.html
612 /// use std::ffi::{CString, CStr};
614 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
615 /// let boxed = c_string.into_boxed_c_str();
616 /// assert_eq!(&*boxed,
617 /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
619 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
620 pub fn into_boxed_c_str(self) -> Box<CStr> {
621 unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) }
624 /// Bypass "move out of struct which implements [`Drop`] trait" restriction.
626 /// [`Drop`]: ../ops/trait.Drop.html
627 fn into_inner(self) -> Box<[u8]> {
628 // Rationale: `mem::forget(self)` invalidates the previous call to `ptr::read(&self.inner)`
629 // so we use `ManuallyDrop` to ensure `self` is not dropped.
630 // Then we can return the box directly without invalidating it.
631 // See https://github.com/rust-lang/rust/issues/62553.
632 let this = mem::ManuallyDrop::new(self);
633 unsafe { ptr::read(&this.inner) }
637 // Turns this `CString` into an empty string to prevent
638 // memory-unsafe code from working by accident. Inline
639 // to prevent LLVM from optimizing it away in debug builds.
640 #[stable(feature = "cstring_drop", since = "1.13.0")]
641 impl Drop for CString {
645 *self.inner.get_unchecked_mut(0) = 0;
650 #[stable(feature = "rust1", since = "1.0.0")]
651 impl ops::Deref for CString {
655 fn deref(&self) -> &CStr {
656 unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
660 #[stable(feature = "rust1", since = "1.0.0")]
661 impl fmt::Debug for CString {
662 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
663 fmt::Debug::fmt(&**self, f)
667 #[stable(feature = "cstring_into", since = "1.7.0")]
668 impl From<CString> for Vec<u8> {
669 /// Converts a [`CString`] into a [`Vec`]`<u8>`.
671 /// The conversion consumes the [`CString`], and removes the terminating NUL byte.
673 /// [`Vec`]: ../vec/struct.Vec.html
674 /// [`CString`]: ../ffi/struct.CString.html
676 fn from(s: CString) -> Vec<u8> {
681 #[stable(feature = "cstr_debug", since = "1.3.0")]
682 impl fmt::Debug for CStr {
683 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
685 for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
686 f.write_char(byte as char)?;
692 #[stable(feature = "cstr_default", since = "1.10.0")]
693 impl Default for &CStr {
694 fn default() -> Self {
695 const SLICE: &[c_char] = &[0];
696 unsafe { CStr::from_ptr(SLICE.as_ptr()) }
700 #[stable(feature = "cstr_default", since = "1.10.0")]
701 impl Default for CString {
702 /// Creates an empty `CString`.
703 fn default() -> CString {
704 let a: &CStr = Default::default();
709 #[stable(feature = "cstr_borrow", since = "1.3.0")]
710 impl Borrow<CStr> for CString {
712 fn borrow(&self) -> &CStr {
717 #[stable(feature = "cstring_from_cow_cstr", since = "1.28.0")]
718 impl<'a> From<Cow<'a, CStr>> for CString {
720 fn from(s: Cow<'a, CStr>) -> Self {
725 #[stable(feature = "box_from_c_str", since = "1.17.0")]
726 impl From<&CStr> for Box<CStr> {
727 fn from(s: &CStr) -> Box<CStr> {
728 let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul());
729 unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
733 #[stable(feature = "box_from_cow", since = "1.45.0")]
734 impl From<Cow<'_, CStr>> for Box<CStr> {
736 fn from(cow: Cow<'_, CStr>) -> Box<CStr> {
738 Cow::Borrowed(s) => Box::from(s),
739 Cow::Owned(s) => Box::from(s),
744 #[stable(feature = "c_string_from_box", since = "1.18.0")]
745 impl From<Box<CStr>> for CString {
746 /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating.
748 /// [`Box`]: ../boxed/struct.Box.html
749 /// [`CString`]: ../ffi/struct.CString.html
751 fn from(s: Box<CStr>) -> CString {
756 #[stable(feature = "cstring_from_vec_of_nonzerou8", since = "1.43.0")]
757 impl From<Vec<NonZeroU8>> for CString {
758 /// Converts a [`Vec`]`<`[`NonZeroU8`]`>` into a [`CString`] without
759 /// copying nor checking for inner null bytes.
761 /// [`CString`]: ../ffi/struct.CString.html
762 /// [`NonZeroU8`]: ../num/struct.NonZeroU8.html
763 /// [`Vec`]: ../vec/struct.Vec.html
765 fn from(v: Vec<NonZeroU8>) -> CString {
767 // Transmute `Vec<NonZeroU8>` to `Vec<u8>`.
770 // - transmuting between `NonZeroU8` and `u8` is sound;
771 // - `alloc::Layout<NonZeroU8> == alloc::Layout<u8>`.
772 let (ptr, len, cap): (*mut NonZeroU8, _, _) = Vec::into_raw_parts(v);
773 Vec::from_raw_parts(ptr.cast::<u8>(), len, cap)
775 // Safety: `v` cannot contain null bytes, given the type-level
776 // invariant of `NonZeroU8`.
777 CString::from_vec_unchecked(v)
782 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
783 impl Clone for Box<CStr> {
785 fn clone(&self) -> Self {
790 #[stable(feature = "box_from_c_string", since = "1.20.0")]
791 impl From<CString> for Box<CStr> {
792 /// Converts a [`CString`] into a [`Box`]`<CStr>` without copying or allocating.
794 /// [`CString`]: ../ffi/struct.CString.html
795 /// [`Box`]: ../boxed/struct.Box.html
797 fn from(s: CString) -> Box<CStr> {
802 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
803 impl<'a> From<CString> for Cow<'a, CStr> {
805 fn from(s: CString) -> Cow<'a, CStr> {
810 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
811 impl<'a> From<&'a CStr> for Cow<'a, CStr> {
813 fn from(s: &'a CStr) -> Cow<'a, CStr> {
818 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
819 impl<'a> From<&'a CString> for Cow<'a, CStr> {
821 fn from(s: &'a CString) -> Cow<'a, CStr> {
822 Cow::Borrowed(s.as_c_str())
826 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
827 impl From<CString> for Arc<CStr> {
828 /// Converts a [`CString`] into a [`Arc`]`<CStr>` without copying or allocating.
830 /// [`CString`]: ../ffi/struct.CString.html
831 /// [`Arc`]: ../sync/struct.Arc.html
833 fn from(s: CString) -> Arc<CStr> {
834 let arc: Arc<[u8]> = Arc::from(s.into_inner());
835 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
839 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
840 impl From<&CStr> for Arc<CStr> {
842 fn from(s: &CStr) -> Arc<CStr> {
843 let arc: Arc<[u8]> = Arc::from(s.to_bytes_with_nul());
844 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
848 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
849 impl From<CString> for Rc<CStr> {
850 /// Converts a [`CString`] into a [`Rc`]`<CStr>` without copying or allocating.
852 /// [`CString`]: ../ffi/struct.CString.html
853 /// [`Rc`]: ../rc/struct.Rc.html
855 fn from(s: CString) -> Rc<CStr> {
856 let rc: Rc<[u8]> = Rc::from(s.into_inner());
857 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
861 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
862 impl From<&CStr> for Rc<CStr> {
864 fn from(s: &CStr) -> Rc<CStr> {
865 let rc: Rc<[u8]> = Rc::from(s.to_bytes_with_nul());
866 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
870 #[stable(feature = "default_box_extra", since = "1.17.0")]
871 impl Default for Box<CStr> {
872 fn default() -> Box<CStr> {
873 let boxed: Box<[u8]> = Box::from([0]);
874 unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
879 /// Returns the position of the nul byte in the slice that caused
880 /// [`CString::new`] to fail.
882 /// [`CString::new`]: struct.CString.html#method.new
887 /// use std::ffi::CString;
889 /// let nul_error = CString::new("foo\0bar").unwrap_err();
890 /// assert_eq!(nul_error.nul_position(), 3);
892 /// let nul_error = CString::new("foo bar\0").unwrap_err();
893 /// assert_eq!(nul_error.nul_position(), 7);
895 #[stable(feature = "rust1", since = "1.0.0")]
896 pub fn nul_position(&self) -> usize {
900 /// Consumes this error, returning the underlying vector of bytes which
901 /// generated the error in the first place.
906 /// use std::ffi::CString;
908 /// let nul_error = CString::new("foo\0bar").unwrap_err();
909 /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
911 #[stable(feature = "rust1", since = "1.0.0")]
912 pub fn into_vec(self) -> Vec<u8> {
917 #[stable(feature = "rust1", since = "1.0.0")]
918 impl Error for NulError {
920 fn description(&self) -> &str {
921 "nul byte found in data"
925 #[stable(feature = "rust1", since = "1.0.0")]
926 impl fmt::Display for NulError {
927 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
928 write!(f, "nul byte found in provided data at position: {}", self.0)
932 #[stable(feature = "rust1", since = "1.0.0")]
933 impl From<NulError> for io::Error {
934 /// Converts a [`NulError`] into a [`io::Error`].
936 /// [`NulError`]: ../ffi/struct.NulError.html
937 /// [`io::Error`]: ../io/struct.Error.html
938 fn from(_: NulError) -> io::Error {
939 io::Error::new(io::ErrorKind::InvalidInput, "data provided contains a nul byte")
943 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
944 impl Error for FromBytesWithNulError {
946 fn description(&self) -> &str {
948 FromBytesWithNulErrorKind::InteriorNul(..) => {
949 "data provided contains an interior nul byte"
951 FromBytesWithNulErrorKind::NotNulTerminated => "data provided is not nul terminated",
956 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
957 impl fmt::Display for FromBytesWithNulError {
958 #[allow(deprecated, deprecated_in_future)]
959 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
960 f.write_str(self.description())?;
961 if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind {
962 write!(f, " at byte pos {}", pos)?;
968 impl IntoStringError {
969 /// Consumes this error, returning original [`CString`] which generated the
972 /// [`CString`]: struct.CString.html
973 #[stable(feature = "cstring_into", since = "1.7.0")]
974 pub fn into_cstring(self) -> CString {
978 /// Access the underlying UTF-8 error that was the cause of this error.
979 #[stable(feature = "cstring_into", since = "1.7.0")]
980 pub fn utf8_error(&self) -> Utf8Error {
985 #[stable(feature = "cstring_into", since = "1.7.0")]
986 impl Error for IntoStringError {
988 fn description(&self) -> &str {
989 "C string contained non-utf8 bytes"
992 fn source(&self) -> Option<&(dyn Error + 'static)> {
997 #[stable(feature = "cstring_into", since = "1.7.0")]
998 impl fmt::Display for IntoStringError {
999 #[allow(deprecated, deprecated_in_future)]
1000 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1001 self.description().fmt(f)
1006 /// Wraps a raw C string with a safe C string wrapper.
1008 /// This function will wrap the provided `ptr` with a `CStr` wrapper, which
1009 /// allows inspection and interoperation of non-owned C strings. The total
1010 /// size of the raw C string must be smaller than `isize::MAX` **bytes**
1011 /// in memory due to calling the `slice::from_raw_parts` function.
1012 /// This method is unsafe for a number of reasons:
1014 /// * There is no guarantee to the validity of `ptr`.
1015 /// * The returned lifetime is not guaranteed to be the actual lifetime of
1017 /// * There is no guarantee that the memory pointed to by `ptr` contains a
1018 /// valid nul terminator byte at the end of the string.
1019 /// * It is not guaranteed that the memory pointed by `ptr` won't change
1020 /// before the `CStr` has been destroyed.
1022 /// > **Note**: This operation is intended to be a 0-cost cast but it is
1023 /// > currently implemented with an up-front calculation of the length of
1024 /// > the string. This is not guaranteed to always be the case.
1028 /// ```ignore (extern-declaration)
1030 /// use std::ffi::CStr;
1031 /// use std::os::raw::c_char;
1034 /// fn my_string() -> *const c_char;
1038 /// let slice = CStr::from_ptr(my_string());
1039 /// println!("string returned: {}", slice.to_str().unwrap());
1043 #[stable(feature = "rust1", since = "1.0.0")]
1044 pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
1045 let len = sys::strlen(ptr);
1046 let ptr = ptr as *const u8;
1047 CStr::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr, len as usize + 1))
1050 /// Creates a C string wrapper from a byte slice.
1052 /// This function will cast the provided `bytes` to a `CStr`
1053 /// wrapper after ensuring that the byte slice is nul-terminated
1054 /// and does not contain any interior nul bytes.
1059 /// use std::ffi::CStr;
1061 /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
1062 /// assert!(cstr.is_ok());
1065 /// Creating a `CStr` without a trailing nul terminator is an error:
1068 /// use std::ffi::CStr;
1070 /// let cstr = CStr::from_bytes_with_nul(b"hello");
1071 /// assert!(cstr.is_err());
1074 /// Creating a `CStr` with an interior nul byte is an error:
1077 /// use std::ffi::CStr;
1079 /// let cstr = CStr::from_bytes_with_nul(b"he\0llo\0");
1080 /// assert!(cstr.is_err());
1082 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
1083 pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError> {
1084 let nul_pos = memchr::memchr(0, bytes);
1085 if let Some(nul_pos) = nul_pos {
1086 if nul_pos + 1 != bytes.len() {
1087 return Err(FromBytesWithNulError::interior_nul(nul_pos));
1089 Ok(unsafe { CStr::from_bytes_with_nul_unchecked(bytes) })
1091 Err(FromBytesWithNulError::not_nul_terminated())
1095 /// Unsafely creates a C string wrapper from a byte slice.
1097 /// This function will cast the provided `bytes` to a `CStr` wrapper without
1098 /// performing any sanity checks. The provided slice **must** be nul-terminated
1099 /// and not contain any interior nul bytes.
1104 /// use std::ffi::{CStr, CString};
1107 /// let cstring = CString::new("hello").expect("CString::new failed");
1108 /// let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
1109 /// assert_eq!(cstr, &*cstring);
1113 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
1114 #[rustc_const_unstable(feature = "const_cstr_unchecked", issue = "none")]
1115 pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
1116 &*(bytes as *const [u8] as *const CStr)
1119 /// Returns the inner pointer to this C string.
1121 /// The returned pointer will be valid for as long as `self` is, and points
1122 /// to a contiguous region of memory terminated with a 0 byte to represent
1123 /// the end of the string.
1127 /// The returned pointer is read-only; writing to it (including passing it
1128 /// to C code that writes to it) causes undefined behavior.
1130 /// It is your responsibility to make sure that the underlying memory is not
1131 /// freed too early. For example, the following code will cause undefined
1132 /// behavior when `ptr` is used inside the `unsafe` block:
1135 /// # #![allow(unused_must_use)]
1136 /// use std::ffi::CString;
1138 /// let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
1140 /// // `ptr` is dangling
1145 /// This happens because the pointer returned by `as_ptr` does not carry any
1146 /// lifetime information and the [`CString`] is deallocated immediately after
1147 /// the `CString::new("Hello").expect("CString::new failed").as_ptr()` expression is evaluated.
1148 /// To fix the problem, bind the `CString` to a local variable:
1151 /// # #![allow(unused_must_use)]
1152 /// use std::ffi::CString;
1154 /// let hello = CString::new("Hello").expect("CString::new failed");
1155 /// let ptr = hello.as_ptr();
1157 /// // `ptr` is valid because `hello` is in scope
1162 /// This way, the lifetime of the `CString` in `hello` encompasses
1163 /// the lifetime of `ptr` and the `unsafe` block.
1165 /// [`CString`]: struct.CString.html
1167 #[stable(feature = "rust1", since = "1.0.0")]
1168 #[rustc_const_stable(feature = "const_str_as_ptr", since = "1.32.0")]
1169 pub const fn as_ptr(&self) -> *const c_char {
1173 /// Converts this C string to a byte slice.
1175 /// The returned slice will **not** contain the trailing nul terminator that this C
1178 /// > **Note**: This method is currently implemented as a constant-time
1179 /// > cast, but it is planned to alter its definition in the future to
1180 /// > perform the length calculation whenever this method is called.
1185 /// use std::ffi::CStr;
1187 /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1188 /// assert_eq!(cstr.to_bytes(), b"foo");
1191 #[stable(feature = "rust1", since = "1.0.0")]
1192 pub fn to_bytes(&self) -> &[u8] {
1193 let bytes = self.to_bytes_with_nul();
1194 &bytes[..bytes.len() - 1]
1197 /// Converts this C string to a byte slice containing the trailing 0 byte.
1199 /// This function is the equivalent of [`to_bytes`] except that it will retain
1200 /// the trailing nul terminator instead of chopping it off.
1202 /// > **Note**: This method is currently implemented as a 0-cost cast, but
1203 /// > it is planned to alter its definition in the future to perform the
1204 /// > length calculation whenever this method is called.
1206 /// [`to_bytes`]: #method.to_bytes
1211 /// use std::ffi::CStr;
1213 /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1214 /// assert_eq!(cstr.to_bytes_with_nul(), b"foo\0");
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 pub fn to_bytes_with_nul(&self) -> &[u8] {
1219 unsafe { &*(&self.inner as *const [c_char] as *const [u8]) }
1222 /// Yields a [`&str`] slice if the `CStr` contains valid UTF-8.
1224 /// If the contents of the `CStr` are valid UTF-8 data, this
1225 /// function will return the corresponding [`&str`] slice. Otherwise,
1226 /// it will return an error with details of where UTF-8 validation failed.
1228 /// [`&str`]: ../primitive.str.html
1233 /// use std::ffi::CStr;
1235 /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1236 /// assert_eq!(cstr.to_str(), Ok("foo"));
1238 #[stable(feature = "cstr_to_str", since = "1.4.0")]
1239 pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
1240 // N.B., when `CStr` is changed to perform the length check in `.to_bytes()`
1241 // instead of in `from_ptr()`, it may be worth considering if this should
1242 // be rewritten to do the UTF-8 check inline with the length calculation
1243 // instead of doing it afterwards.
1244 str::from_utf8(self.to_bytes())
1247 /// Converts a `CStr` into a [`Cow`]`<`[`str`]`>`.
1249 /// If the contents of the `CStr` are valid UTF-8 data, this
1250 /// function will return a [`Cow`]`::`[`Borrowed`]`(`[`&str`]`)`
1251 /// with the corresponding [`&str`] slice. Otherwise, it will
1252 /// replace any invalid UTF-8 sequences with
1253 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD] and return a
1254 /// [`Cow`]`::`[`Owned`]`(`[`String`]`)` with the result.
1256 /// [`Cow`]: ../borrow/enum.Cow.html
1257 /// [`Borrowed`]: ../borrow/enum.Cow.html#variant.Borrowed
1258 /// [`Owned`]: ../borrow/enum.Cow.html#variant.Owned
1259 /// [`str`]: ../primitive.str.html
1260 /// [`String`]: ../string/struct.String.html
1261 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
1265 /// Calling `to_string_lossy` on a `CStr` containing valid UTF-8:
1268 /// use std::borrow::Cow;
1269 /// use std::ffi::CStr;
1271 /// let cstr = CStr::from_bytes_with_nul(b"Hello World\0")
1272 /// .expect("CStr::from_bytes_with_nul failed");
1273 /// assert_eq!(cstr.to_string_lossy(), Cow::Borrowed("Hello World"));
1276 /// Calling `to_string_lossy` on a `CStr` containing invalid UTF-8:
1279 /// use std::borrow::Cow;
1280 /// use std::ffi::CStr;
1282 /// let cstr = CStr::from_bytes_with_nul(b"Hello \xF0\x90\x80World\0")
1283 /// .expect("CStr::from_bytes_with_nul failed");
1285 /// cstr.to_string_lossy(),
1286 /// Cow::Owned(String::from("Hello �World")) as Cow<'_, str>
1289 #[stable(feature = "cstr_to_str", since = "1.4.0")]
1290 pub fn to_string_lossy(&self) -> Cow<'_, str> {
1291 String::from_utf8_lossy(self.to_bytes())
1294 /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating.
1296 /// [`Box`]: ../boxed/struct.Box.html
1297 /// [`CString`]: struct.CString.html
1302 /// use std::ffi::CString;
1304 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
1305 /// let boxed = c_string.into_boxed_c_str();
1306 /// assert_eq!(boxed.into_c_string(), CString::new("foo").expect("CString::new failed"));
1308 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
1309 pub fn into_c_string(self: Box<CStr>) -> CString {
1310 let raw = Box::into_raw(self) as *mut [u8];
1311 CString { inner: unsafe { Box::from_raw(raw) } }
1315 #[stable(feature = "rust1", since = "1.0.0")]
1316 impl PartialEq for CStr {
1317 fn eq(&self, other: &CStr) -> bool {
1318 self.to_bytes().eq(other.to_bytes())
1321 #[stable(feature = "rust1", since = "1.0.0")]
1323 #[stable(feature = "rust1", since = "1.0.0")]
1324 impl PartialOrd for CStr {
1325 fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
1326 self.to_bytes().partial_cmp(&other.to_bytes())
1329 #[stable(feature = "rust1", since = "1.0.0")]
1331 fn cmp(&self, other: &CStr) -> Ordering {
1332 self.to_bytes().cmp(&other.to_bytes())
1336 #[stable(feature = "cstr_borrow", since = "1.3.0")]
1337 impl ToOwned for CStr {
1338 type Owned = CString;
1340 fn to_owned(&self) -> CString {
1341 CString { inner: self.to_bytes_with_nul().into() }
1344 fn clone_into(&self, target: &mut CString) {
1345 let mut b = Vec::from(mem::take(&mut target.inner));
1346 self.to_bytes_with_nul().clone_into(&mut b);
1347 target.inner = b.into_boxed_slice();
1351 #[stable(feature = "cstring_asref", since = "1.7.0")]
1352 impl From<&CStr> for CString {
1353 fn from(s: &CStr) -> CString {
1358 #[stable(feature = "cstring_asref", since = "1.7.0")]
1359 impl ops::Index<ops::RangeFull> for CString {
1363 fn index(&self, _index: ops::RangeFull) -> &CStr {
1368 #[stable(feature = "cstring_asref", since = "1.7.0")]
1369 impl AsRef<CStr> for CStr {
1371 fn as_ref(&self) -> &CStr {
1376 #[stable(feature = "cstring_asref", since = "1.7.0")]
1377 impl AsRef<CStr> for CString {
1379 fn as_ref(&self) -> &CStr {
1387 use crate::borrow::Cow::{Borrowed, Owned};
1388 use crate::collections::hash_map::DefaultHasher;
1389 use crate::hash::{Hash, Hasher};
1390 use crate::os::raw::c_char;
1392 use crate::sync::Arc;
1396 let data = b"123\0";
1397 let ptr = data.as_ptr() as *const c_char;
1399 assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
1400 assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
1406 let s = CString::new("1234").unwrap();
1407 assert_eq!(s.as_bytes(), b"1234");
1408 assert_eq!(s.as_bytes_with_nul(), b"1234\0");
1412 fn build_with_zero1() {
1413 assert!(CString::new(&b"\0"[..]).is_err());
1416 fn build_with_zero2() {
1417 assert!(CString::new(vec![0]).is_err());
1421 fn build_with_zero3() {
1423 let s = CString::from_vec_unchecked(vec![0]);
1424 assert_eq!(s.as_bytes(), b"\0");
1430 let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
1431 assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
1437 let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
1438 assert_eq!(s.to_bytes(), b"12");
1439 assert_eq!(s.to_bytes_with_nul(), b"12\0");
1445 let data = b"123\xE2\x80\xA6\0";
1446 let ptr = data.as_ptr() as *const c_char;
1448 assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
1449 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
1451 let data = b"123\xE2\0";
1452 let ptr = data.as_ptr() as *const c_char;
1454 assert!(CStr::from_ptr(ptr).to_str().is_err());
1455 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
1461 let data = b"123\0";
1462 let ptr = data.as_ptr() as *const c_char;
1464 let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
1465 assert_eq!(owned.as_bytes_with_nul(), data);
1470 let data = b"123\xE2\xFA\xA6\0";
1471 let ptr = data.as_ptr() as *const c_char;
1472 let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
1474 let mut s = DefaultHasher::new();
1476 let cstr_hash = s.finish();
1477 let mut s = DefaultHasher::new();
1478 CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
1479 let cstring_hash = s.finish();
1481 assert_eq!(cstr_hash, cstring_hash);
1485 fn from_bytes_with_nul() {
1486 let data = b"123\0";
1487 let cstr = CStr::from_bytes_with_nul(data);
1488 assert_eq!(cstr.map(CStr::to_bytes), Ok(&b"123"[..]));
1489 let cstr = CStr::from_bytes_with_nul(data);
1490 assert_eq!(cstr.map(CStr::to_bytes_with_nul), Ok(&b"123\0"[..]));
1493 let cstr = CStr::from_bytes_with_nul(data);
1494 let cstr_unchecked = CStr::from_bytes_with_nul_unchecked(data);
1495 assert_eq!(cstr, Ok(cstr_unchecked));
1500 fn from_bytes_with_nul_unterminated() {
1502 let cstr = CStr::from_bytes_with_nul(data);
1503 assert!(cstr.is_err());
1507 fn from_bytes_with_nul_interior() {
1508 let data = b"1\023\0";
1509 let cstr = CStr::from_bytes_with_nul(data);
1510 assert!(cstr.is_err());
1515 let orig: &[u8] = b"Hello, world!\0";
1516 let cstr = CStr::from_bytes_with_nul(orig).unwrap();
1517 let boxed: Box<CStr> = Box::from(cstr);
1518 let cstring = cstr.to_owned().into_boxed_c_str().into_c_string();
1519 assert_eq!(cstr, &*boxed);
1520 assert_eq!(&*boxed, &*cstring);
1521 assert_eq!(&*cstring, cstr);
1525 fn boxed_default() {
1526 let boxed = <Box<CStr>>::default();
1527 assert_eq!(boxed.to_bytes_with_nul(), &[0]);
1531 fn test_c_str_clone_into() {
1532 let mut c_string = CString::new("lorem").unwrap();
1533 let c_ptr = c_string.as_ptr();
1534 let c_str = CStr::from_bytes_with_nul(b"ipsum\0").unwrap();
1535 c_str.clone_into(&mut c_string);
1536 assert_eq!(c_str, c_string.as_c_str());
1537 // The exact same size shouldn't have needed to move its allocation
1538 assert_eq!(c_ptr, c_string.as_ptr());
1543 let orig: &[u8] = b"Hello, world!\0";
1544 let cstr = CStr::from_bytes_with_nul(orig).unwrap();
1545 let rc: Rc<CStr> = Rc::from(cstr);
1546 let arc: Arc<CStr> = Arc::from(cstr);
1548 assert_eq!(&*rc, cstr);
1549 assert_eq!(&*arc, cstr);
1551 let rc2: Rc<CStr> = Rc::from(cstr.to_owned());
1552 let arc2: Arc<CStr> = Arc::from(cstr.to_owned());
1554 assert_eq!(&*rc2, cstr);
1555 assert_eq!(&*arc2, cstr);
1559 fn cstr_const_constructor() {
1560 const CSTR: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b"Hello, world!\0") };
1562 assert_eq!(CSTR.to_str().unwrap(), "Hello, world!");