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 byte,
238 /// positioned at the end.
240 /// This error is created by the [`from_bytes_with_nul`] method on [`CStr`].
241 /// See its documentation for more.
243 /// [`CStr`]: struct.CStr.html
244 /// [`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 /// An error indicating that a nul byte was not in the expected position.
261 /// The vector used to create a [`CString`] must have one and only one nul byte,
262 /// positioned at the end.
264 /// This error is created by the [`from_vec_with_nul`] method on [`CString`].
265 /// See its documentation for more.
267 /// [`CString`]: struct.CString.html
268 /// [`from_vec_with_nul`]: struct.CString.html#method.from_vec_with_nul
273 /// #![feature(cstring_from_vec_with_nul)]
274 /// use std::ffi::{CString, FromVecWithNulError};
276 /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"f\0oo".to_vec()).unwrap_err();
278 #[derive(Clone, PartialEq, Eq, Debug)]
279 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
280 pub struct FromVecWithNulError {
281 error_kind: FromBytesWithNulErrorKind,
285 #[derive(Clone, PartialEq, Eq, Debug)]
286 enum FromBytesWithNulErrorKind {
291 impl FromBytesWithNulError {
292 fn interior_nul(pos: usize) -> FromBytesWithNulError {
293 FromBytesWithNulError { kind: FromBytesWithNulErrorKind::InteriorNul(pos) }
295 fn not_nul_terminated() -> FromBytesWithNulError {
296 FromBytesWithNulError { kind: FromBytesWithNulErrorKind::NotNulTerminated }
300 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
301 impl FromVecWithNulError {
302 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a [`CString`].
309 /// #![feature(cstring_from_vec_with_nul)]
310 /// use std::ffi::CString;
312 /// // Some invalid bytes in a vector
313 /// let bytes = b"f\0oo".to_vec();
315 /// let value = CString::from_vec_with_nul(bytes.clone());
317 /// assert_eq!(&bytes[..], value.unwrap_err().as_bytes());
320 /// [`CString`]: struct.CString.html
321 pub fn as_bytes(&self) -> &[u8] {
325 /// Returns the bytes that were attempted to convert to a [`CString`].
327 /// This method is carefully constructed to avoid allocation. It will
328 /// consume the error, moving out the bytes, so that a copy of the bytes
329 /// does not need to be made.
336 /// #![feature(cstring_from_vec_with_nul)]
337 /// use std::ffi::CString;
339 /// // Some invalid bytes in a vector
340 /// let bytes = b"f\0oo".to_vec();
342 /// let value = CString::from_vec_with_nul(bytes.clone());
344 /// assert_eq!(bytes, value.unwrap_err().into_bytes());
347 /// [`CString`]: struct.CString.html
348 pub fn into_bytes(self) -> Vec<u8> {
353 /// An error indicating invalid UTF-8 when converting a [`CString`] into a [`String`].
355 /// `CString` is just a wrapper over a buffer of bytes with a nul
356 /// terminator; [`into_string`][`CString::into_string`] performs UTF-8
357 /// validation on those bytes and may return this error.
359 /// This `struct` is created by the
360 /// [`into_string`][`CString::into_string`] method on [`CString`]. See
361 /// its documentation for more.
363 /// [`String`]: ../string/struct.String.html
364 /// [`CString`]: struct.CString.html
365 /// [`CString::into_string`]: struct.CString.html#method.into_string
366 #[derive(Clone, PartialEq, Eq, Debug)]
367 #[stable(feature = "cstring_into", since = "1.7.0")]
368 pub struct IntoStringError {
374 /// Creates a new C-compatible string from a container of bytes.
376 /// This function will consume the provided data and use the
377 /// underlying bytes to construct a new string, ensuring that
378 /// there is a trailing 0 byte. This trailing 0 byte will be
379 /// appended by this function; the provided data should *not*
380 /// contain any 0 bytes in it.
384 /// ```ignore (extern-declaration)
385 /// use std::ffi::CString;
386 /// use std::os::raw::c_char;
388 /// extern { fn puts(s: *const c_char); }
390 /// let to_print = CString::new("Hello!").expect("CString::new failed");
392 /// puts(to_print.as_ptr());
398 /// This function will return an error if the supplied bytes contain an
399 /// internal 0 byte. The [`NulError`] returned will contain the bytes as well as
400 /// the position of the nul byte.
402 /// [`NulError`]: struct.NulError.html
403 #[stable(feature = "rust1", since = "1.0.0")]
404 pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
406 fn into_vec(self) -> Vec<u8>;
408 impl<T: Into<Vec<u8>>> SpecIntoVec for T {
409 default fn into_vec(self) -> Vec<u8> {
413 // Specialization for avoiding reallocation.
414 impl SpecIntoVec for &'_ [u8] {
415 fn into_vec(self) -> Vec<u8> {
416 let mut v = Vec::with_capacity(self.len() + 1);
421 impl SpecIntoVec for &'_ str {
422 fn into_vec(self) -> Vec<u8> {
423 let mut v = Vec::with_capacity(self.len() + 1);
424 v.extend(self.as_bytes());
429 Self::_new(SpecIntoVec::into_vec(t))
432 fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
433 match memchr::memchr(0, &bytes) {
434 Some(i) => Err(NulError(i, bytes)),
435 None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
439 /// Creates a C-compatible string by consuming a byte vector,
440 /// without checking for interior 0 bytes.
442 /// This method is equivalent to [`new`] except that no runtime assertion
443 /// is made that `v` contains no 0 bytes, and it requires an actual
444 /// byte vector, not anything that can be converted to one with Into.
446 /// [`new`]: #method.new
451 /// use std::ffi::CString;
453 /// let raw = b"foo".to_vec();
455 /// let c_string = CString::from_vec_unchecked(raw);
458 #[stable(feature = "rust1", since = "1.0.0")]
459 pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
462 CString { inner: v.into_boxed_slice() }
465 /// Retakes ownership of a `CString` that was transferred to C via [`into_raw`].
467 /// Additionally, the length of the string will be recalculated from the pointer.
471 /// This should only ever be called with a pointer that was earlier
472 /// obtained by calling [`into_raw`] on a `CString`. Other usage (e.g., trying to take
473 /// ownership of a string that was allocated by foreign code) is likely to lead
474 /// to undefined behavior or allocator corruption.
476 /// It should be noted that the length isn't just "recomputed," but that
477 /// the recomputed length must match the original length from the
478 /// [`into_raw`] call. This means the [`into_raw`]/`from_raw` methods
479 /// should not be used when passing the string to C functions that can
480 /// modify the string's length.
482 /// > **Note:** If you need to borrow a string that was allocated by
483 /// > foreign code, use [`CStr`]. If you need to take ownership of
484 /// > a string that was allocated by foreign code, you will need to
485 /// > make your own provisions for freeing it appropriately, likely
486 /// > with the foreign code's API to do that.
488 /// [`into_raw`]: #method.into_raw
489 /// [`CStr`]: struct.CStr.html
493 /// Creates a `CString`, pass ownership to an `extern` function (via raw pointer), then retake
494 /// ownership with `from_raw`:
496 /// ```ignore (extern-declaration)
497 /// use std::ffi::CString;
498 /// use std::os::raw::c_char;
501 /// fn some_extern_function(s: *mut c_char);
504 /// let c_string = CString::new("Hello!").expect("CString::new failed");
505 /// let raw = c_string.into_raw();
507 /// some_extern_function(raw);
508 /// let c_string = CString::from_raw(raw);
511 #[stable(feature = "cstr_memory", since = "1.4.0")]
512 pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
513 let len = sys::strlen(ptr) + 1; // Including the NUL byte
514 let slice = slice::from_raw_parts_mut(ptr, len as usize);
515 CString { inner: Box::from_raw(slice as *mut [c_char] as *mut [u8]) }
518 /// Consumes the `CString` and transfers ownership of the string to a C caller.
520 /// The pointer which this function returns must be returned to Rust and reconstituted using
521 /// [`from_raw`] to be properly deallocated. Specifically, one
522 /// should *not* use the standard C `free()` function to deallocate
525 /// Failure to call [`from_raw`] will lead to a memory leak.
527 /// The C side must **not** modify the length of the string (by writing a
528 /// `NULL` somewhere inside the string or removing the final one) before
529 /// it makes it back into Rust using [`from_raw`]. See the safety section
532 /// [`from_raw`]: #method.from_raw
537 /// use std::ffi::CString;
539 /// let c_string = CString::new("foo").expect("CString::new failed");
541 /// let ptr = c_string.into_raw();
544 /// assert_eq!(b'f', *ptr as u8);
545 /// assert_eq!(b'o', *ptr.offset(1) as u8);
546 /// assert_eq!(b'o', *ptr.offset(2) as u8);
547 /// assert_eq!(b'\0', *ptr.offset(3) as u8);
549 /// // retake pointer to free memory
550 /// let _ = CString::from_raw(ptr);
554 #[stable(feature = "cstr_memory", since = "1.4.0")]
555 pub fn into_raw(self) -> *mut c_char {
556 Box::into_raw(self.into_inner()) as *mut c_char
559 /// Converts the `CString` into a [`String`] if it contains valid UTF-8 data.
561 /// On failure, ownership of the original `CString` is returned.
563 /// [`String`]: ../string/struct.String.html
568 /// use std::ffi::CString;
570 /// let valid_utf8 = vec![b'f', b'o', b'o'];
571 /// let cstring = CString::new(valid_utf8).expect("CString::new failed");
572 /// assert_eq!(cstring.into_string().expect("into_string() call failed"), "foo");
574 /// let invalid_utf8 = vec![b'f', 0xff, b'o', b'o'];
575 /// let cstring = CString::new(invalid_utf8).expect("CString::new failed");
576 /// let err = cstring.into_string().err().expect("into_string().err() failed");
577 /// assert_eq!(err.utf8_error().valid_up_to(), 1);
580 #[stable(feature = "cstring_into", since = "1.7.0")]
581 pub fn into_string(self) -> Result<String, IntoStringError> {
582 String::from_utf8(self.into_bytes()).map_err(|e| IntoStringError {
583 error: e.utf8_error(),
584 inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
588 /// Consumes the `CString` and returns the underlying byte buffer.
590 /// The returned buffer does **not** contain the trailing nul
591 /// terminator, and it is guaranteed to not have any interior nul
597 /// use std::ffi::CString;
599 /// let c_string = CString::new("foo").expect("CString::new failed");
600 /// let bytes = c_string.into_bytes();
601 /// assert_eq!(bytes, vec![b'f', b'o', b'o']);
603 #[stable(feature = "cstring_into", since = "1.7.0")]
604 pub fn into_bytes(self) -> Vec<u8> {
605 let mut vec = self.into_inner().into_vec();
606 let _nul = vec.pop();
607 debug_assert_eq!(_nul, Some(0u8));
611 /// Equivalent to the [`into_bytes`] function except that the returned vector
612 /// includes the trailing nul terminator.
614 /// [`into_bytes`]: #method.into_bytes
619 /// use std::ffi::CString;
621 /// let c_string = CString::new("foo").expect("CString::new failed");
622 /// let bytes = c_string.into_bytes_with_nul();
623 /// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
625 #[stable(feature = "cstring_into", since = "1.7.0")]
626 pub fn into_bytes_with_nul(self) -> Vec<u8> {
627 self.into_inner().into_vec()
630 /// Returns the contents of this `CString` as a slice of bytes.
632 /// The returned slice does **not** contain the trailing nul
633 /// terminator, and it is guaranteed to not have any interior nul
634 /// bytes. If you need the nul terminator, use
635 /// [`as_bytes_with_nul`] instead.
637 /// [`as_bytes_with_nul`]: #method.as_bytes_with_nul
642 /// use std::ffi::CString;
644 /// let c_string = CString::new("foo").expect("CString::new failed");
645 /// let bytes = c_string.as_bytes();
646 /// assert_eq!(bytes, &[b'f', b'o', b'o']);
649 #[stable(feature = "rust1", since = "1.0.0")]
650 pub fn as_bytes(&self) -> &[u8] {
651 &self.inner[..self.inner.len() - 1]
654 /// Equivalent to the [`as_bytes`] function except that the returned slice
655 /// includes the trailing nul terminator.
657 /// [`as_bytes`]: #method.as_bytes
662 /// use std::ffi::CString;
664 /// let c_string = CString::new("foo").expect("CString::new failed");
665 /// let bytes = c_string.as_bytes_with_nul();
666 /// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
669 #[stable(feature = "rust1", since = "1.0.0")]
670 pub fn as_bytes_with_nul(&self) -> &[u8] {
674 /// Extracts a [`CStr`] slice containing the entire string.
676 /// [`CStr`]: struct.CStr.html
681 /// use std::ffi::{CString, CStr};
683 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
684 /// let cstr = c_string.as_c_str();
686 /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
689 #[stable(feature = "as_c_str", since = "1.20.0")]
690 pub fn as_c_str(&self) -> &CStr {
694 /// Converts this `CString` into a boxed [`CStr`].
696 /// [`CStr`]: struct.CStr.html
701 /// use std::ffi::{CString, CStr};
703 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
704 /// let boxed = c_string.into_boxed_c_str();
705 /// assert_eq!(&*boxed,
706 /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
708 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
709 pub fn into_boxed_c_str(self) -> Box<CStr> {
710 unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) }
713 /// Bypass "move out of struct which implements [`Drop`] trait" restriction.
715 /// [`Drop`]: ../ops/trait.Drop.html
716 fn into_inner(self) -> Box<[u8]> {
717 // Rationale: `mem::forget(self)` invalidates the previous call to `ptr::read(&self.inner)`
718 // so we use `ManuallyDrop` to ensure `self` is not dropped.
719 // Then we can return the box directly without invalidating it.
720 // See https://github.com/rust-lang/rust/issues/62553.
721 let this = mem::ManuallyDrop::new(self);
722 unsafe { ptr::read(&this.inner) }
725 /// Converts a `Vec` of `u8` to a `CString` without checking the invariants
726 /// on the given `Vec`.
730 /// The given `Vec` **must** have one nul byte as its last element.
731 /// This means it cannot be empty nor have any other nul byte anywhere else.
736 /// #![feature(cstring_from_vec_with_nul)]
737 /// use std::ffi::CString;
739 /// unsafe { CString::from_vec_with_nul_unchecked(b"abc\0".to_vec()) },
740 /// unsafe { CString::from_vec_unchecked(b"abc".to_vec()) }
743 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
744 pub unsafe fn from_vec_with_nul_unchecked(v: Vec<u8>) -> Self {
745 Self { inner: v.into_boxed_slice() }
748 /// Attempts to converts a `Vec` of `u8` to a `CString`.
750 /// Runtime checks are present to ensure there is only one nul byte in the
751 /// `Vec`, its last element.
755 /// If a nul byte is present and not the last element or no nul bytes
756 /// is present, an error will be returned.
760 /// A successful conversion will produce the same result as [`new`] when
761 /// called without the ending nul byte.
764 /// #![feature(cstring_from_vec_with_nul)]
765 /// use std::ffi::CString;
767 /// CString::from_vec_with_nul(b"abc\0".to_vec())
768 /// .expect("CString::from_vec_with_nul failed"),
769 /// CString::new(b"abc".to_vec()).expect("CString::new failed")
773 /// A incorrectly formatted vector will produce an error.
776 /// #![feature(cstring_from_vec_with_nul)]
777 /// use std::ffi::{CString, FromVecWithNulError};
778 /// // Interior nul byte
779 /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"a\0bc".to_vec()).unwrap_err();
781 /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"abc".to_vec()).unwrap_err();
784 /// [`new`]: #method.new
785 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
786 pub fn from_vec_with_nul(v: Vec<u8>) -> Result<Self, FromVecWithNulError> {
787 let nul_pos = memchr::memchr(0, &v);
789 Some(nul_pos) if nul_pos + 1 == v.len() => {
790 // SAFETY: We know there is only one nul byte, at the end
792 Ok(unsafe { Self::from_vec_with_nul_unchecked(v) })
794 Some(nul_pos) => Err(FromVecWithNulError {
795 error_kind: FromBytesWithNulErrorKind::InteriorNul(nul_pos),
798 None => Err(FromVecWithNulError {
799 error_kind: FromBytesWithNulErrorKind::NotNulTerminated,
806 // Turns this `CString` into an empty string to prevent
807 // memory-unsafe code from working by accident. Inline
808 // to prevent LLVM from optimizing it away in debug builds.
809 #[stable(feature = "cstring_drop", since = "1.13.0")]
810 impl Drop for CString {
814 *self.inner.get_unchecked_mut(0) = 0;
819 #[stable(feature = "rust1", since = "1.0.0")]
820 impl ops::Deref for CString {
824 fn deref(&self) -> &CStr {
825 unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
829 #[stable(feature = "rust1", since = "1.0.0")]
830 impl fmt::Debug for CString {
831 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
832 fmt::Debug::fmt(&**self, f)
836 #[stable(feature = "cstring_into", since = "1.7.0")]
837 impl From<CString> for Vec<u8> {
838 /// Converts a [`CString`] into a [`Vec`]`<u8>`.
840 /// The conversion consumes the [`CString`], and removes the terminating NUL byte.
842 /// [`Vec`]: ../vec/struct.Vec.html
843 /// [`CString`]: ../ffi/struct.CString.html
845 fn from(s: CString) -> Vec<u8> {
850 #[stable(feature = "cstr_debug", since = "1.3.0")]
851 impl fmt::Debug for CStr {
852 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
854 for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
855 f.write_char(byte as char)?;
861 #[stable(feature = "cstr_default", since = "1.10.0")]
862 impl Default for &CStr {
863 fn default() -> Self {
864 const SLICE: &[c_char] = &[0];
865 unsafe { CStr::from_ptr(SLICE.as_ptr()) }
869 #[stable(feature = "cstr_default", since = "1.10.0")]
870 impl Default for CString {
871 /// Creates an empty `CString`.
872 fn default() -> CString {
873 let a: &CStr = Default::default();
878 #[stable(feature = "cstr_borrow", since = "1.3.0")]
879 impl Borrow<CStr> for CString {
881 fn borrow(&self) -> &CStr {
886 #[stable(feature = "cstring_from_cow_cstr", since = "1.28.0")]
887 impl<'a> From<Cow<'a, CStr>> for CString {
889 fn from(s: Cow<'a, CStr>) -> Self {
894 #[stable(feature = "box_from_c_str", since = "1.17.0")]
895 impl From<&CStr> for Box<CStr> {
896 fn from(s: &CStr) -> Box<CStr> {
897 let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul());
898 unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
902 #[stable(feature = "box_from_cow", since = "1.45.0")]
903 impl From<Cow<'_, CStr>> for Box<CStr> {
905 fn from(cow: Cow<'_, CStr>) -> Box<CStr> {
907 Cow::Borrowed(s) => Box::from(s),
908 Cow::Owned(s) => Box::from(s),
913 #[stable(feature = "c_string_from_box", since = "1.18.0")]
914 impl From<Box<CStr>> for CString {
915 /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating.
917 /// [`Box`]: ../boxed/struct.Box.html
918 /// [`CString`]: ../ffi/struct.CString.html
920 fn from(s: Box<CStr>) -> CString {
925 #[stable(feature = "cstring_from_vec_of_nonzerou8", since = "1.43.0")]
926 impl From<Vec<NonZeroU8>> for CString {
927 /// Converts a [`Vec`]`<`[`NonZeroU8`]`>` into a [`CString`] without
928 /// copying nor checking for inner null bytes.
930 /// [`CString`]: ../ffi/struct.CString.html
931 /// [`NonZeroU8`]: ../num/struct.NonZeroU8.html
932 /// [`Vec`]: ../vec/struct.Vec.html
934 fn from(v: Vec<NonZeroU8>) -> CString {
936 // Transmute `Vec<NonZeroU8>` to `Vec<u8>`.
939 // - transmuting between `NonZeroU8` and `u8` is sound;
940 // - `alloc::Layout<NonZeroU8> == alloc::Layout<u8>`.
941 let (ptr, len, cap): (*mut NonZeroU8, _, _) = Vec::into_raw_parts(v);
942 Vec::from_raw_parts(ptr.cast::<u8>(), len, cap)
944 // Safety: `v` cannot contain null bytes, given the type-level
945 // invariant of `NonZeroU8`.
946 CString::from_vec_unchecked(v)
951 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
952 impl Clone for Box<CStr> {
954 fn clone(&self) -> Self {
959 #[stable(feature = "box_from_c_string", since = "1.20.0")]
960 impl From<CString> for Box<CStr> {
961 /// Converts a [`CString`] into a [`Box`]`<CStr>` without copying or allocating.
963 /// [`CString`]: ../ffi/struct.CString.html
964 /// [`Box`]: ../boxed/struct.Box.html
966 fn from(s: CString) -> Box<CStr> {
971 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
972 impl<'a> From<CString> for Cow<'a, CStr> {
974 fn from(s: CString) -> Cow<'a, CStr> {
979 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
980 impl<'a> From<&'a CStr> for Cow<'a, CStr> {
982 fn from(s: &'a CStr) -> Cow<'a, CStr> {
987 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
988 impl<'a> From<&'a CString> for Cow<'a, CStr> {
990 fn from(s: &'a CString) -> Cow<'a, CStr> {
991 Cow::Borrowed(s.as_c_str())
995 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
996 impl From<CString> for Arc<CStr> {
997 /// Converts a [`CString`] into a [`Arc`]`<CStr>` without copying or allocating.
999 /// [`CString`]: ../ffi/struct.CString.html
1000 /// [`Arc`]: ../sync/struct.Arc.html
1002 fn from(s: CString) -> Arc<CStr> {
1003 let arc: Arc<[u8]> = Arc::from(s.into_inner());
1004 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
1008 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1009 impl From<&CStr> for Arc<CStr> {
1011 fn from(s: &CStr) -> Arc<CStr> {
1012 let arc: Arc<[u8]> = Arc::from(s.to_bytes_with_nul());
1013 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
1017 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1018 impl From<CString> for Rc<CStr> {
1019 /// Converts a [`CString`] into a [`Rc`]`<CStr>` without copying or allocating.
1021 /// [`CString`]: ../ffi/struct.CString.html
1022 /// [`Rc`]: ../rc/struct.Rc.html
1024 fn from(s: CString) -> Rc<CStr> {
1025 let rc: Rc<[u8]> = Rc::from(s.into_inner());
1026 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
1030 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1031 impl From<&CStr> for Rc<CStr> {
1033 fn from(s: &CStr) -> Rc<CStr> {
1034 let rc: Rc<[u8]> = Rc::from(s.to_bytes_with_nul());
1035 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
1039 #[stable(feature = "default_box_extra", since = "1.17.0")]
1040 impl Default for Box<CStr> {
1041 fn default() -> Box<CStr> {
1042 let boxed: Box<[u8]> = Box::from([0]);
1043 unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
1048 /// Returns the position of the nul byte in the slice that caused
1049 /// [`CString::new`] to fail.
1051 /// [`CString::new`]: struct.CString.html#method.new
1056 /// use std::ffi::CString;
1058 /// let nul_error = CString::new("foo\0bar").unwrap_err();
1059 /// assert_eq!(nul_error.nul_position(), 3);
1061 /// let nul_error = CString::new("foo bar\0").unwrap_err();
1062 /// assert_eq!(nul_error.nul_position(), 7);
1064 #[stable(feature = "rust1", since = "1.0.0")]
1065 pub fn nul_position(&self) -> usize {
1069 /// Consumes this error, returning the underlying vector of bytes which
1070 /// generated the error in the first place.
1075 /// use std::ffi::CString;
1077 /// let nul_error = CString::new("foo\0bar").unwrap_err();
1078 /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 pub fn into_vec(self) -> Vec<u8> {
1086 #[stable(feature = "rust1", since = "1.0.0")]
1087 impl Error for NulError {
1088 #[allow(deprecated)]
1089 fn description(&self) -> &str {
1090 "nul byte found in data"
1094 #[stable(feature = "rust1", since = "1.0.0")]
1095 impl fmt::Display for NulError {
1096 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1097 write!(f, "nul byte found in provided data at position: {}", self.0)
1101 #[stable(feature = "rust1", since = "1.0.0")]
1102 impl From<NulError> for io::Error {
1103 /// Converts a [`NulError`] into a [`io::Error`].
1105 /// [`NulError`]: ../ffi/struct.NulError.html
1106 /// [`io::Error`]: ../io/struct.Error.html
1107 fn from(_: NulError) -> io::Error {
1108 io::Error::new(io::ErrorKind::InvalidInput, "data provided contains a nul byte")
1112 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
1113 impl Error for FromBytesWithNulError {
1114 #[allow(deprecated)]
1115 fn description(&self) -> &str {
1117 FromBytesWithNulErrorKind::InteriorNul(..) => {
1118 "data provided contains an interior nul byte"
1120 FromBytesWithNulErrorKind::NotNulTerminated => "data provided is not nul terminated",
1125 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
1126 impl fmt::Display for FromBytesWithNulError {
1127 #[allow(deprecated, deprecated_in_future)]
1128 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1129 f.write_str(self.description())?;
1130 if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind {
1131 write!(f, " at byte pos {}", pos)?;
1137 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
1138 impl Error for FromVecWithNulError {}
1140 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
1141 impl fmt::Display for FromVecWithNulError {
1142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1143 match self.error_kind {
1144 FromBytesWithNulErrorKind::InteriorNul(pos) => {
1145 write!(f, "data provided contains an interior nul byte at pos {}", pos)
1147 FromBytesWithNulErrorKind::NotNulTerminated => {
1148 write!(f, "data provided is not nul terminated")
1154 impl IntoStringError {
1155 /// Consumes this error, returning original [`CString`] which generated the
1158 /// [`CString`]: struct.CString.html
1159 #[stable(feature = "cstring_into", since = "1.7.0")]
1160 pub fn into_cstring(self) -> CString {
1164 /// Access the underlying UTF-8 error that was the cause of this error.
1165 #[stable(feature = "cstring_into", since = "1.7.0")]
1166 pub fn utf8_error(&self) -> Utf8Error {
1171 #[stable(feature = "cstring_into", since = "1.7.0")]
1172 impl Error for IntoStringError {
1173 #[allow(deprecated)]
1174 fn description(&self) -> &str {
1175 "C string contained non-utf8 bytes"
1178 fn source(&self) -> Option<&(dyn Error + 'static)> {
1183 #[stable(feature = "cstring_into", since = "1.7.0")]
1184 impl fmt::Display for IntoStringError {
1185 #[allow(deprecated, deprecated_in_future)]
1186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1187 self.description().fmt(f)
1192 /// Wraps a raw C string with a safe C string wrapper.
1194 /// This function will wrap the provided `ptr` with a `CStr` wrapper, which
1195 /// allows inspection and interoperation of non-owned C strings. The total
1196 /// size of the raw C string must be smaller than `isize::MAX` **bytes**
1197 /// in memory due to calling the `slice::from_raw_parts` function.
1198 /// This method is unsafe for a number of reasons:
1200 /// * There is no guarantee to the validity of `ptr`.
1201 /// * The returned lifetime is not guaranteed to be the actual lifetime of
1203 /// * There is no guarantee that the memory pointed to by `ptr` contains a
1204 /// valid nul terminator byte at the end of the string.
1205 /// * It is not guaranteed that the memory pointed by `ptr` won't change
1206 /// before the `CStr` has been destroyed.
1208 /// > **Note**: This operation is intended to be a 0-cost cast but it is
1209 /// > currently implemented with an up-front calculation of the length of
1210 /// > the string. This is not guaranteed to always be the case.
1214 /// ```ignore (extern-declaration)
1216 /// use std::ffi::CStr;
1217 /// use std::os::raw::c_char;
1220 /// fn my_string() -> *const c_char;
1224 /// let slice = CStr::from_ptr(my_string());
1225 /// println!("string returned: {}", slice.to_str().unwrap());
1229 #[stable(feature = "rust1", since = "1.0.0")]
1230 pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
1231 let len = sys::strlen(ptr);
1232 let ptr = ptr as *const u8;
1233 CStr::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr, len as usize + 1))
1236 /// Creates a C string wrapper from a byte slice.
1238 /// This function will cast the provided `bytes` to a `CStr`
1239 /// wrapper after ensuring that the byte slice is nul-terminated
1240 /// and does not contain any interior nul bytes.
1245 /// use std::ffi::CStr;
1247 /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
1248 /// assert!(cstr.is_ok());
1251 /// Creating a `CStr` without a trailing nul terminator is an error:
1254 /// use std::ffi::CStr;
1256 /// let cstr = CStr::from_bytes_with_nul(b"hello");
1257 /// assert!(cstr.is_err());
1260 /// Creating a `CStr` with an interior nul byte is an error:
1263 /// use std::ffi::CStr;
1265 /// let cstr = CStr::from_bytes_with_nul(b"he\0llo\0");
1266 /// assert!(cstr.is_err());
1268 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
1269 pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError> {
1270 let nul_pos = memchr::memchr(0, bytes);
1271 if let Some(nul_pos) = nul_pos {
1272 if nul_pos + 1 != bytes.len() {
1273 return Err(FromBytesWithNulError::interior_nul(nul_pos));
1275 Ok(unsafe { CStr::from_bytes_with_nul_unchecked(bytes) })
1277 Err(FromBytesWithNulError::not_nul_terminated())
1281 /// Unsafely creates a C string wrapper from a byte slice.
1283 /// This function will cast the provided `bytes` to a `CStr` wrapper without
1284 /// performing any sanity checks. The provided slice **must** be nul-terminated
1285 /// and not contain any interior nul bytes.
1290 /// use std::ffi::{CStr, CString};
1293 /// let cstring = CString::new("hello").expect("CString::new failed");
1294 /// let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
1295 /// assert_eq!(cstr, &*cstring);
1299 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
1300 #[rustc_const_unstable(feature = "const_cstr_unchecked", issue = "none")]
1301 pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
1302 &*(bytes as *const [u8] as *const CStr)
1305 /// Returns the inner pointer to this C string.
1307 /// The returned pointer will be valid for as long as `self` is, and points
1308 /// to a contiguous region of memory terminated with a 0 byte to represent
1309 /// the end of the string.
1313 /// The returned pointer is read-only; writing to it (including passing it
1314 /// to C code that writes to it) causes undefined behavior.
1316 /// It is your responsibility to make sure that the underlying memory is not
1317 /// freed too early. For example, the following code will cause undefined
1318 /// behavior when `ptr` is used inside the `unsafe` block:
1321 /// # #![allow(unused_must_use)]
1322 /// use std::ffi::CString;
1324 /// let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
1326 /// // `ptr` is dangling
1331 /// This happens because the pointer returned by `as_ptr` does not carry any
1332 /// lifetime information and the [`CString`] is deallocated immediately after
1333 /// the `CString::new("Hello").expect("CString::new failed").as_ptr()` expression is evaluated.
1334 /// To fix the problem, bind the `CString` to a local variable:
1337 /// # #![allow(unused_must_use)]
1338 /// use std::ffi::CString;
1340 /// let hello = CString::new("Hello").expect("CString::new failed");
1341 /// let ptr = hello.as_ptr();
1343 /// // `ptr` is valid because `hello` is in scope
1348 /// This way, the lifetime of the `CString` in `hello` encompasses
1349 /// the lifetime of `ptr` and the `unsafe` block.
1351 /// [`CString`]: struct.CString.html
1353 #[stable(feature = "rust1", since = "1.0.0")]
1354 #[rustc_const_stable(feature = "const_str_as_ptr", since = "1.32.0")]
1355 pub const fn as_ptr(&self) -> *const c_char {
1359 /// Converts this C string to a byte slice.
1361 /// The returned slice will **not** contain the trailing nul terminator that this C
1364 /// > **Note**: This method is currently implemented as a constant-time
1365 /// > cast, but it is planned to alter its definition in the future to
1366 /// > perform the length calculation whenever this method is called.
1371 /// use std::ffi::CStr;
1373 /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1374 /// assert_eq!(cstr.to_bytes(), b"foo");
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 pub fn to_bytes(&self) -> &[u8] {
1379 let bytes = self.to_bytes_with_nul();
1380 &bytes[..bytes.len() - 1]
1383 /// Converts this C string to a byte slice containing the trailing 0 byte.
1385 /// This function is the equivalent of [`to_bytes`] except that it will retain
1386 /// the trailing nul terminator instead of chopping it off.
1388 /// > **Note**: This method is currently implemented as a 0-cost cast, but
1389 /// > it is planned to alter its definition in the future to perform the
1390 /// > length calculation whenever this method is called.
1392 /// [`to_bytes`]: #method.to_bytes
1397 /// use std::ffi::CStr;
1399 /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1400 /// assert_eq!(cstr.to_bytes_with_nul(), b"foo\0");
1403 #[stable(feature = "rust1", since = "1.0.0")]
1404 pub fn to_bytes_with_nul(&self) -> &[u8] {
1405 unsafe { &*(&self.inner as *const [c_char] as *const [u8]) }
1408 /// Yields a [`&str`] slice if the `CStr` contains valid UTF-8.
1410 /// If the contents of the `CStr` are valid UTF-8 data, this
1411 /// function will return the corresponding [`&str`] slice. Otherwise,
1412 /// it will return an error with details of where UTF-8 validation failed.
1414 /// [`&str`]: ../primitive.str.html
1419 /// use std::ffi::CStr;
1421 /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1422 /// assert_eq!(cstr.to_str(), Ok("foo"));
1424 #[stable(feature = "cstr_to_str", since = "1.4.0")]
1425 pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
1426 // N.B., when `CStr` is changed to perform the length check in `.to_bytes()`
1427 // instead of in `from_ptr()`, it may be worth considering if this should
1428 // be rewritten to do the UTF-8 check inline with the length calculation
1429 // instead of doing it afterwards.
1430 str::from_utf8(self.to_bytes())
1433 /// Converts a `CStr` into a [`Cow`]`<`[`str`]`>`.
1435 /// If the contents of the `CStr` are valid UTF-8 data, this
1436 /// function will return a [`Cow`]`::`[`Borrowed`]`(`[`&str`]`)`
1437 /// with the corresponding [`&str`] slice. Otherwise, it will
1438 /// replace any invalid UTF-8 sequences with
1439 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD] and return a
1440 /// [`Cow`]`::`[`Owned`]`(`[`String`]`)` with the result.
1442 /// [`Cow`]: ../borrow/enum.Cow.html
1443 /// [`Borrowed`]: ../borrow/enum.Cow.html#variant.Borrowed
1444 /// [`Owned`]: ../borrow/enum.Cow.html#variant.Owned
1445 /// [`str`]: ../primitive.str.html
1446 /// [`String`]: ../string/struct.String.html
1447 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
1451 /// Calling `to_string_lossy` on a `CStr` containing valid UTF-8:
1454 /// use std::borrow::Cow;
1455 /// use std::ffi::CStr;
1457 /// let cstr = CStr::from_bytes_with_nul(b"Hello World\0")
1458 /// .expect("CStr::from_bytes_with_nul failed");
1459 /// assert_eq!(cstr.to_string_lossy(), Cow::Borrowed("Hello World"));
1462 /// Calling `to_string_lossy` on a `CStr` containing invalid UTF-8:
1465 /// use std::borrow::Cow;
1466 /// use std::ffi::CStr;
1468 /// let cstr = CStr::from_bytes_with_nul(b"Hello \xF0\x90\x80World\0")
1469 /// .expect("CStr::from_bytes_with_nul failed");
1471 /// cstr.to_string_lossy(),
1472 /// Cow::Owned(String::from("Hello �World")) as Cow<'_, str>
1475 #[stable(feature = "cstr_to_str", since = "1.4.0")]
1476 pub fn to_string_lossy(&self) -> Cow<'_, str> {
1477 String::from_utf8_lossy(self.to_bytes())
1480 /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating.
1482 /// [`Box`]: ../boxed/struct.Box.html
1483 /// [`CString`]: struct.CString.html
1488 /// use std::ffi::CString;
1490 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
1491 /// let boxed = c_string.into_boxed_c_str();
1492 /// assert_eq!(boxed.into_c_string(), CString::new("foo").expect("CString::new failed"));
1494 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
1495 pub fn into_c_string(self: Box<CStr>) -> CString {
1496 let raw = Box::into_raw(self) as *mut [u8];
1497 CString { inner: unsafe { Box::from_raw(raw) } }
1501 #[stable(feature = "rust1", since = "1.0.0")]
1502 impl PartialEq for CStr {
1503 fn eq(&self, other: &CStr) -> bool {
1504 self.to_bytes().eq(other.to_bytes())
1507 #[stable(feature = "rust1", since = "1.0.0")]
1509 #[stable(feature = "rust1", since = "1.0.0")]
1510 impl PartialOrd for CStr {
1511 fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
1512 self.to_bytes().partial_cmp(&other.to_bytes())
1515 #[stable(feature = "rust1", since = "1.0.0")]
1517 fn cmp(&self, other: &CStr) -> Ordering {
1518 self.to_bytes().cmp(&other.to_bytes())
1522 #[stable(feature = "cstr_borrow", since = "1.3.0")]
1523 impl ToOwned for CStr {
1524 type Owned = CString;
1526 fn to_owned(&self) -> CString {
1527 CString { inner: self.to_bytes_with_nul().into() }
1530 fn clone_into(&self, target: &mut CString) {
1531 let mut b = Vec::from(mem::take(&mut target.inner));
1532 self.to_bytes_with_nul().clone_into(&mut b);
1533 target.inner = b.into_boxed_slice();
1537 #[stable(feature = "cstring_asref", since = "1.7.0")]
1538 impl From<&CStr> for CString {
1539 fn from(s: &CStr) -> CString {
1544 #[stable(feature = "cstring_asref", since = "1.7.0")]
1545 impl ops::Index<ops::RangeFull> for CString {
1549 fn index(&self, _index: ops::RangeFull) -> &CStr {
1554 #[stable(feature = "cstr_range_from", since = "1.47.0")]
1555 impl ops::Index<ops::RangeFrom<usize>> for CStr {
1558 fn index(&self, index: ops::RangeFrom<usize>) -> &CStr {
1559 let bytes = self.to_bytes_with_nul();
1560 // we need to manually check the starting index to account for the null
1561 // byte, since otherwise we could get an empty string that doesn't end
1563 if index.start < bytes.len() {
1564 unsafe { CStr::from_bytes_with_nul_unchecked(&bytes[index.start..]) }
1567 "index out of bounds: the len is {} but the index is {}",
1575 #[stable(feature = "cstring_asref", since = "1.7.0")]
1576 impl AsRef<CStr> for CStr {
1578 fn as_ref(&self) -> &CStr {
1583 #[stable(feature = "cstring_asref", since = "1.7.0")]
1584 impl AsRef<CStr> for CString {
1586 fn as_ref(&self) -> &CStr {
1594 use crate::borrow::Cow::{Borrowed, Owned};
1595 use crate::collections::hash_map::DefaultHasher;
1596 use crate::hash::{Hash, Hasher};
1597 use crate::os::raw::c_char;
1599 use crate::sync::Arc;
1603 let data = b"123\0";
1604 let ptr = data.as_ptr() as *const c_char;
1606 assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
1607 assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
1613 let s = CString::new("1234").unwrap();
1614 assert_eq!(s.as_bytes(), b"1234");
1615 assert_eq!(s.as_bytes_with_nul(), b"1234\0");
1619 fn build_with_zero1() {
1620 assert!(CString::new(&b"\0"[..]).is_err());
1623 fn build_with_zero2() {
1624 assert!(CString::new(vec![0]).is_err());
1628 fn build_with_zero3() {
1630 let s = CString::from_vec_unchecked(vec![0]);
1631 assert_eq!(s.as_bytes(), b"\0");
1637 let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
1638 assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
1644 let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
1645 assert_eq!(s.to_bytes(), b"12");
1646 assert_eq!(s.to_bytes_with_nul(), b"12\0");
1652 let data = b"123\xE2\x80\xA6\0";
1653 let ptr = data.as_ptr() as *const c_char;
1655 assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
1656 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
1658 let data = b"123\xE2\0";
1659 let ptr = data.as_ptr() as *const c_char;
1661 assert!(CStr::from_ptr(ptr).to_str().is_err());
1662 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
1668 let data = b"123\0";
1669 let ptr = data.as_ptr() as *const c_char;
1671 let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
1672 assert_eq!(owned.as_bytes_with_nul(), data);
1677 let data = b"123\xE2\xFA\xA6\0";
1678 let ptr = data.as_ptr() as *const c_char;
1679 let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
1681 let mut s = DefaultHasher::new();
1683 let cstr_hash = s.finish();
1684 let mut s = DefaultHasher::new();
1685 CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
1686 let cstring_hash = s.finish();
1688 assert_eq!(cstr_hash, cstring_hash);
1692 fn from_bytes_with_nul() {
1693 let data = b"123\0";
1694 let cstr = CStr::from_bytes_with_nul(data);
1695 assert_eq!(cstr.map(CStr::to_bytes), Ok(&b"123"[..]));
1696 let cstr = CStr::from_bytes_with_nul(data);
1697 assert_eq!(cstr.map(CStr::to_bytes_with_nul), Ok(&b"123\0"[..]));
1700 let cstr = CStr::from_bytes_with_nul(data);
1701 let cstr_unchecked = CStr::from_bytes_with_nul_unchecked(data);
1702 assert_eq!(cstr, Ok(cstr_unchecked));
1707 fn from_bytes_with_nul_unterminated() {
1709 let cstr = CStr::from_bytes_with_nul(data);
1710 assert!(cstr.is_err());
1714 fn from_bytes_with_nul_interior() {
1715 let data = b"1\023\0";
1716 let cstr = CStr::from_bytes_with_nul(data);
1717 assert!(cstr.is_err());
1722 let orig: &[u8] = b"Hello, world!\0";
1723 let cstr = CStr::from_bytes_with_nul(orig).unwrap();
1724 let boxed: Box<CStr> = Box::from(cstr);
1725 let cstring = cstr.to_owned().into_boxed_c_str().into_c_string();
1726 assert_eq!(cstr, &*boxed);
1727 assert_eq!(&*boxed, &*cstring);
1728 assert_eq!(&*cstring, cstr);
1732 fn boxed_default() {
1733 let boxed = <Box<CStr>>::default();
1734 assert_eq!(boxed.to_bytes_with_nul(), &[0]);
1738 fn test_c_str_clone_into() {
1739 let mut c_string = CString::new("lorem").unwrap();
1740 let c_ptr = c_string.as_ptr();
1741 let c_str = CStr::from_bytes_with_nul(b"ipsum\0").unwrap();
1742 c_str.clone_into(&mut c_string);
1743 assert_eq!(c_str, c_string.as_c_str());
1744 // The exact same size shouldn't have needed to move its allocation
1745 assert_eq!(c_ptr, c_string.as_ptr());
1750 let orig: &[u8] = b"Hello, world!\0";
1751 let cstr = CStr::from_bytes_with_nul(orig).unwrap();
1752 let rc: Rc<CStr> = Rc::from(cstr);
1753 let arc: Arc<CStr> = Arc::from(cstr);
1755 assert_eq!(&*rc, cstr);
1756 assert_eq!(&*arc, cstr);
1758 let rc2: Rc<CStr> = Rc::from(cstr.to_owned());
1759 let arc2: Arc<CStr> = Arc::from(cstr.to_owned());
1761 assert_eq!(&*rc2, cstr);
1762 assert_eq!(&*arc2, cstr);
1766 fn cstr_const_constructor() {
1767 const CSTR: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b"Hello, world!\0") };
1769 assert_eq!(CSTR.to_str().unwrap(), "Hello, world!");
1773 fn cstr_index_from() {
1774 let original = b"Hello, world!\0";
1775 let cstr = CStr::from_bytes_with_nul(original).unwrap();
1776 let result = CStr::from_bytes_with_nul(&original[7..]).unwrap();
1778 assert_eq!(&cstr[7..], result);
1783 fn cstr_index_from_empty() {
1784 let original = b"Hello, world!\0";
1785 let cstr = CStr::from_bytes_with_nul(original).unwrap();
1786 let _ = &cstr[original.len()..];