1 #![deny(unsafe_op_in_unsafe_fn)]
7 use crate::borrow::{Borrow, Cow};
8 use crate::cmp::Ordering;
9 use crate::error::Error;
10 use crate::fmt::{self, Write};
13 use crate::num::NonZeroU8;
15 use crate::os::raw::c_char;
19 use crate::str::{self, Utf8Error};
22 use crate::sys_common::memchr;
24 /// A type representing an owned, C-compatible, nul-terminated string with no nul bytes in the
27 /// This type serves the purpose of being able to safely generate a
28 /// C-compatible string from a Rust byte slice or vector. An instance of this
29 /// type is a static guarantee that the underlying bytes contain no interior 0
30 /// bytes ("nul characters") and that the final byte is 0 ("nul terminator").
32 /// `CString` is to [`&CStr`] as [`String`] is to [`&str`]: the former
33 /// in each pair are owned strings; the latter are borrowed
36 /// # Creating a `CString`
38 /// A `CString` is created from either a byte slice or a byte vector,
39 /// or anything that implements [`Into`]`<`[`Vec`]`<`[`u8`]`>>` (for
40 /// example, you can build a `CString` straight out of a [`String`] or
41 /// a [`&str`], since both implement that trait).
43 /// The [`CString::new`] method will actually check that the provided `&[u8]`
44 /// does not have 0 bytes in the middle, and return an error if it
47 /// # Extracting a raw pointer to the whole C string
49 /// `CString` implements an [`as_ptr`][`CStr::as_ptr`] method through the [`Deref`]
50 /// trait. This method will give you a `*const c_char` which you can
51 /// feed directly to extern functions that expect a nul-terminated
52 /// string, like C's `strdup()`. Notice that [`as_ptr`][`CStr::as_ptr`] returns a
53 /// read-only pointer; if the C code writes to it, that causes
54 /// undefined behavior.
56 /// # Extracting a slice of the whole C string
58 /// Alternatively, you can obtain a `&[`[`u8`]`]` slice from a
59 /// `CString` with the [`CString::as_bytes`] method. Slices produced in this
60 /// way do *not* contain the trailing nul terminator. This is useful
61 /// when you will be calling an extern function that takes a `*const
62 /// u8` argument which is not necessarily nul-terminated, plus another
63 /// argument with the length of the string — like C's `strndup()`.
64 /// You can of course get the slice's length with its
65 /// [`len`][slice::len] method.
67 /// If you need a `&[`[`u8`]`]` slice *with* the nul terminator, you
68 /// can use [`CString::as_bytes_with_nul`] instead.
70 /// Once you have the kind of slice you need (with or without a nul
71 /// terminator), you can call the slice's own
72 /// [`as_ptr`][slice::as_ptr] method to get a read-only raw pointer to pass to
73 /// extern functions. See the documentation for that function for a
74 /// discussion on ensuring the lifetime of the raw pointer.
76 /// [`&str`]: prim@str
77 /// [`Deref`]: ops::Deref
82 /// ```ignore (extern-declaration)
84 /// use std::ffi::CString;
85 /// use std::os::raw::c_char;
88 /// fn my_printer(s: *const c_char);
91 /// // We are certain that our string doesn't have 0 bytes in the middle,
92 /// // so we can .expect()
93 /// let c_to_print = CString::new("Hello, world!").expect("CString::new failed");
95 /// my_printer(c_to_print.as_ptr());
102 /// `CString` is intended for working with traditional C-style strings
103 /// (a sequence of non-nul bytes terminated by a single nul byte); the
104 /// primary use case for these kinds of strings is interoperating with C-like
105 /// code. Often you will need to transfer ownership to/from that external
106 /// code. It is strongly recommended that you thoroughly read through the
107 /// documentation of `CString` before use, as improper ownership management
108 /// of `CString` instances can lead to invalid memory accesses, memory leaks,
109 /// and other memory errors.
110 #[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
111 #[cfg_attr(not(test), rustc_diagnostic_item = "cstring_type")]
112 #[stable(feature = "rust1", since = "1.0.0")]
114 // Invariant 1: the slice ends with a zero byte and has a length of at least one.
115 // Invariant 2: the slice contains only one zero byte.
116 // Improper usage of unsafe function can break Invariant 2, but not Invariant 1.
120 /// Representation of a borrowed C string.
122 /// This type represents a borrowed reference to a nul-terminated
123 /// array of bytes. It can be constructed safely from a `&[`[`u8`]`]`
124 /// slice, or unsafely from a raw `*const c_char`. It can then be
125 /// converted to a Rust [`&str`] by performing UTF-8 validation, or
126 /// into an owned [`CString`].
128 /// `&CStr` is to [`CString`] as [`&str`] is to [`String`]: the former
129 /// in each pair are borrowed references; the latter are owned
132 /// Note that this structure is **not** `repr(C)` and is not recommended to be
133 /// placed in the signatures of FFI functions. Instead, safe wrappers of FFI
134 /// functions may leverage the unsafe [`CStr::from_ptr`] constructor to provide
135 /// a safe interface to other consumers.
139 /// Inspecting a foreign C string:
141 /// ```ignore (extern-declaration)
142 /// use std::ffi::CStr;
143 /// use std::os::raw::c_char;
145 /// extern "C" { fn my_string() -> *const c_char; }
148 /// let slice = CStr::from_ptr(my_string());
149 /// println!("string buffer size without nul terminator: {}", slice.to_bytes().len());
153 /// Passing a Rust-originating C string:
155 /// ```ignore (extern-declaration)
156 /// use std::ffi::{CString, CStr};
157 /// use std::os::raw::c_char;
159 /// fn work(data: &CStr) {
160 /// extern "C" { fn work_with(data: *const c_char); }
162 /// unsafe { work_with(data.as_ptr()) }
165 /// let s = CString::new("data data data data").expect("CString::new failed");
169 /// Converting a foreign C string into a Rust [`String`]:
171 /// ```ignore (extern-declaration)
172 /// use std::ffi::CStr;
173 /// use std::os::raw::c_char;
175 /// extern "C" { fn my_string() -> *const c_char; }
177 /// fn my_string_safe() -> String {
179 /// CStr::from_ptr(my_string()).to_string_lossy().into_owned()
183 /// println!("string: {}", my_string_safe());
186 /// [`&str`]: prim@str
188 #[cfg_attr(not(test), rustc_diagnostic_item = "CStr")]
189 #[stable(feature = "rust1", since = "1.0.0")]
191 // `fn from` in `impl From<&CStr> for Box<CStr>` current implementation relies
192 // on `CStr` being layout-compatible with `[u8]`.
193 // When attribute privacy is implemented, `CStr` should be annotated as `#[repr(transparent)]`.
194 // Anyway, `CStr` representation and layout are considered implementation detail, are
195 // not documented and must not be relied upon.
197 // FIXME: this should not be represented with a DST slice but rather with
198 // just a raw `c_char` along with some form of marker to make
199 // this an unsized type. Essentially `sizeof(&CStr)` should be the
200 // same as `sizeof(&c_char)` but `CStr` should be an unsized type.
204 /// An error indicating that an interior nul byte was found.
206 /// While Rust strings may contain nul bytes in the middle, C strings
207 /// can't, as that byte would effectively truncate the string.
209 /// This error is created by the [`new`][`CString::new`] method on
210 /// [`CString`]. See its documentation for more.
215 /// use std::ffi::{CString, NulError};
217 /// let _: NulError = CString::new(b"f\0oo".to_vec()).unwrap_err();
219 #[derive(Clone, PartialEq, Eq, Debug)]
220 #[stable(feature = "rust1", since = "1.0.0")]
221 pub struct NulError(usize, Vec<u8>);
223 /// An error indicating that a nul byte was not in the expected position.
225 /// The slice used to create a [`CStr`] must have one and only one nul byte,
226 /// positioned at the end.
228 /// This error is created by the [`CStr::from_bytes_with_nul`] method.
229 /// See its documentation for more.
234 /// use std::ffi::{CStr, FromBytesWithNulError};
236 /// let _: FromBytesWithNulError = CStr::from_bytes_with_nul(b"f\0oo").unwrap_err();
238 #[derive(Clone, PartialEq, Eq, Debug)]
239 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
240 pub struct FromBytesWithNulError {
241 kind: FromBytesWithNulErrorKind,
244 /// An error indicating that a nul byte was not in the expected position.
246 /// The vector used to create a [`CString`] must have one and only one nul byte,
247 /// positioned at the end.
249 /// This error is created by the [`CString::from_vec_with_nul`] method.
250 /// See its documentation for more.
255 /// #![feature(cstring_from_vec_with_nul)]
256 /// use std::ffi::{CString, FromVecWithNulError};
258 /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"f\0oo".to_vec()).unwrap_err();
260 #[derive(Clone, PartialEq, Eq, Debug)]
261 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
262 pub struct FromVecWithNulError {
263 error_kind: FromBytesWithNulErrorKind,
267 #[derive(Clone, PartialEq, Eq, Debug)]
268 enum FromBytesWithNulErrorKind {
273 impl FromBytesWithNulError {
274 fn interior_nul(pos: usize) -> FromBytesWithNulError {
275 FromBytesWithNulError { kind: FromBytesWithNulErrorKind::InteriorNul(pos) }
277 fn not_nul_terminated() -> FromBytesWithNulError {
278 FromBytesWithNulError { kind: FromBytesWithNulErrorKind::NotNulTerminated }
282 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
283 impl FromVecWithNulError {
284 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a [`CString`].
291 /// #![feature(cstring_from_vec_with_nul)]
292 /// use std::ffi::CString;
294 /// // Some invalid bytes in a vector
295 /// let bytes = b"f\0oo".to_vec();
297 /// let value = CString::from_vec_with_nul(bytes.clone());
299 /// assert_eq!(&bytes[..], value.unwrap_err().as_bytes());
301 pub fn as_bytes(&self) -> &[u8] {
305 /// Returns the bytes that were attempted to convert to a [`CString`].
307 /// This method is carefully constructed to avoid allocation. It will
308 /// consume the error, moving out the bytes, so that a copy of the bytes
309 /// does not need to be made.
316 /// #![feature(cstring_from_vec_with_nul)]
317 /// use std::ffi::CString;
319 /// // Some invalid bytes in a vector
320 /// let bytes = b"f\0oo".to_vec();
322 /// let value = CString::from_vec_with_nul(bytes.clone());
324 /// assert_eq!(bytes, value.unwrap_err().into_bytes());
326 pub fn into_bytes(self) -> Vec<u8> {
331 /// An error indicating invalid UTF-8 when converting a [`CString`] into a [`String`].
333 /// `CString` is just a wrapper over a buffer of bytes with a nul terminator;
334 /// [`CString::into_string`] performs UTF-8 validation on those bytes and may
335 /// return this error.
337 /// This `struct` is created by [`CString::into_string()`]. See
338 /// its documentation for more.
339 #[derive(Clone, PartialEq, Eq, Debug)]
340 #[stable(feature = "cstring_into", since = "1.7.0")]
341 pub struct IntoStringError {
347 /// Creates a new C-compatible string from a container of bytes.
349 /// This function will consume the provided data and use the
350 /// underlying bytes to construct a new string, ensuring that
351 /// there is a trailing 0 byte. This trailing 0 byte will be
352 /// appended by this function; the provided data should *not*
353 /// contain any 0 bytes in it.
357 /// ```ignore (extern-declaration)
358 /// use std::ffi::CString;
359 /// use std::os::raw::c_char;
361 /// extern "C" { fn puts(s: *const c_char); }
363 /// let to_print = CString::new("Hello!").expect("CString::new failed");
365 /// puts(to_print.as_ptr());
371 /// This function will return an error if the supplied bytes contain an
372 /// internal 0 byte. The [`NulError`] returned will contain the bytes as well as
373 /// the position of the nul byte.
374 #[stable(feature = "rust1", since = "1.0.0")]
375 pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
377 fn into_vec(self) -> Vec<u8>;
379 impl<T: Into<Vec<u8>>> SpecIntoVec for T {
380 default fn into_vec(self) -> Vec<u8> {
384 // Specialization for avoiding reallocation.
385 impl SpecIntoVec for &'_ [u8] {
386 fn into_vec(self) -> Vec<u8> {
387 let mut v = Vec::with_capacity(self.len() + 1);
392 impl SpecIntoVec for &'_ str {
393 fn into_vec(self) -> Vec<u8> {
394 let mut v = Vec::with_capacity(self.len() + 1);
395 v.extend(self.as_bytes());
400 Self::_new(SpecIntoVec::into_vec(t))
403 fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
404 match memchr::memchr(0, &bytes) {
405 Some(i) => Err(NulError(i, bytes)),
406 None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
410 /// Creates a C-compatible string by consuming a byte vector,
411 /// without checking for interior 0 bytes.
413 /// This method is equivalent to [`CString::new`] except that no runtime
414 /// assertion is made that `v` contains no 0 bytes, and it requires an
415 /// actual byte vector, not anything that can be converted to one with Into.
420 /// use std::ffi::CString;
422 /// let raw = b"foo".to_vec();
424 /// let c_string = CString::from_vec_unchecked(raw);
427 #[stable(feature = "rust1", since = "1.0.0")]
428 pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
431 CString { inner: v.into_boxed_slice() }
434 /// Retakes ownership of a `CString` that was transferred to C via
435 /// [`CString::into_raw`].
437 /// Additionally, the length of the string will be recalculated from the pointer.
441 /// This should only ever be called with a pointer that was earlier
442 /// obtained by calling [`CString::into_raw`]. Other usage (e.g., trying to take
443 /// ownership of a string that was allocated by foreign code) is likely to lead
444 /// to undefined behavior or allocator corruption.
446 /// It should be noted that the length isn't just "recomputed," but that
447 /// the recomputed length must match the original length from the
448 /// [`CString::into_raw`] call. This means the [`CString::into_raw`]/`from_raw`
449 /// methods should not be used when passing the string to C functions that can
450 /// modify the string's length.
452 /// > **Note:** If you need to borrow a string that was allocated by
453 /// > foreign code, use [`CStr`]. If you need to take ownership of
454 /// > a string that was allocated by foreign code, you will need to
455 /// > make your own provisions for freeing it appropriately, likely
456 /// > with the foreign code's API to do that.
460 /// Creates a `CString`, pass ownership to an `extern` function (via raw pointer), then retake
461 /// ownership with `from_raw`:
463 /// ```ignore (extern-declaration)
464 /// use std::ffi::CString;
465 /// use std::os::raw::c_char;
468 /// fn some_extern_function(s: *mut c_char);
471 /// let c_string = CString::new("Hello!").expect("CString::new failed");
472 /// let raw = c_string.into_raw();
474 /// some_extern_function(raw);
475 /// let c_string = CString::from_raw(raw);
478 #[stable(feature = "cstr_memory", since = "1.4.0")]
479 pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
480 // SAFETY: This is called with a pointer that was obtained from a call
481 // to `CString::into_raw` and the length has not been modified. As such,
482 // we know there is a NUL byte (and only one) at the end and that the
483 // information about the size of the allocation is correct on Rust's
486 let len = sys::strlen(ptr) + 1; // Including the NUL byte
487 let slice = slice::from_raw_parts_mut(ptr, len as usize);
488 CString { inner: Box::from_raw(slice as *mut [c_char] as *mut [u8]) }
492 /// Consumes the `CString` and transfers ownership of the string to a C caller.
494 /// The pointer which this function returns must be returned to Rust and reconstituted using
495 /// [`CString::from_raw`] to be properly deallocated. Specifically, one
496 /// should *not* use the standard C `free()` function to deallocate
499 /// Failure to call [`CString::from_raw`] will lead to a memory leak.
501 /// The C side must **not** modify the length of the string (by writing a
502 /// `null` somewhere inside the string or removing the final one) before
503 /// it makes it back into Rust using [`CString::from_raw`]. See the safety section
504 /// in [`CString::from_raw`].
509 /// use std::ffi::CString;
511 /// let c_string = CString::new("foo").expect("CString::new failed");
513 /// let ptr = c_string.into_raw();
516 /// assert_eq!(b'f', *ptr as u8);
517 /// assert_eq!(b'o', *ptr.offset(1) as u8);
518 /// assert_eq!(b'o', *ptr.offset(2) as u8);
519 /// assert_eq!(b'\0', *ptr.offset(3) as u8);
521 /// // retake pointer to free memory
522 /// let _ = CString::from_raw(ptr);
526 #[stable(feature = "cstr_memory", since = "1.4.0")]
527 pub fn into_raw(self) -> *mut c_char {
528 Box::into_raw(self.into_inner()) as *mut c_char
531 /// Converts the `CString` into a [`String`] if it contains valid UTF-8 data.
533 /// On failure, ownership of the original `CString` is returned.
538 /// use std::ffi::CString;
540 /// let valid_utf8 = vec![b'f', b'o', b'o'];
541 /// let cstring = CString::new(valid_utf8).expect("CString::new failed");
542 /// assert_eq!(cstring.into_string().expect("into_string() call failed"), "foo");
544 /// let invalid_utf8 = vec![b'f', 0xff, b'o', b'o'];
545 /// let cstring = CString::new(invalid_utf8).expect("CString::new failed");
546 /// let err = cstring.into_string().err().expect("into_string().err() failed");
547 /// assert_eq!(err.utf8_error().valid_up_to(), 1);
550 #[stable(feature = "cstring_into", since = "1.7.0")]
551 pub fn into_string(self) -> Result<String, IntoStringError> {
552 String::from_utf8(self.into_bytes()).map_err(|e| IntoStringError {
553 error: e.utf8_error(),
554 inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
558 /// Consumes the `CString` and returns the underlying byte buffer.
560 /// The returned buffer does **not** contain the trailing nul
561 /// terminator, and it is guaranteed to not have any interior nul
567 /// use std::ffi::CString;
569 /// let c_string = CString::new("foo").expect("CString::new failed");
570 /// let bytes = c_string.into_bytes();
571 /// assert_eq!(bytes, vec![b'f', b'o', b'o']);
573 #[stable(feature = "cstring_into", since = "1.7.0")]
574 pub fn into_bytes(self) -> Vec<u8> {
575 let mut vec = self.into_inner().into_vec();
576 let _nul = vec.pop();
577 debug_assert_eq!(_nul, Some(0u8));
581 /// Equivalent to [`CString::into_bytes()`] except that the
582 /// returned vector includes the trailing nul terminator.
587 /// use std::ffi::CString;
589 /// let c_string = CString::new("foo").expect("CString::new failed");
590 /// let bytes = c_string.into_bytes_with_nul();
591 /// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
593 #[stable(feature = "cstring_into", since = "1.7.0")]
594 pub fn into_bytes_with_nul(self) -> Vec<u8> {
595 self.into_inner().into_vec()
598 /// Returns the contents of this `CString` as a slice of bytes.
600 /// The returned slice does **not** contain the trailing nul
601 /// terminator, and it is guaranteed to not have any interior nul
602 /// bytes. If you need the nul terminator, use
603 /// [`CString::as_bytes_with_nul`] instead.
608 /// use std::ffi::CString;
610 /// let c_string = CString::new("foo").expect("CString::new failed");
611 /// let bytes = c_string.as_bytes();
612 /// assert_eq!(bytes, &[b'f', b'o', b'o']);
615 #[stable(feature = "rust1", since = "1.0.0")]
616 pub fn as_bytes(&self) -> &[u8] {
617 // SAFETY: CString has a length at least 1
618 unsafe { self.inner.get_unchecked(..self.inner.len() - 1) }
621 /// Equivalent to [`CString::as_bytes()`] except that the
622 /// returned slice includes the trailing nul terminator.
627 /// use std::ffi::CString;
629 /// let c_string = CString::new("foo").expect("CString::new failed");
630 /// let bytes = c_string.as_bytes_with_nul();
631 /// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
634 #[stable(feature = "rust1", since = "1.0.0")]
635 pub fn as_bytes_with_nul(&self) -> &[u8] {
639 /// Extracts a [`CStr`] slice containing the entire string.
644 /// use std::ffi::{CString, CStr};
646 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
647 /// let cstr = c_string.as_c_str();
649 /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
652 #[stable(feature = "as_c_str", since = "1.20.0")]
653 pub fn as_c_str(&self) -> &CStr {
657 /// Converts this `CString` into a boxed [`CStr`].
662 /// use std::ffi::{CString, CStr};
664 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
665 /// let boxed = c_string.into_boxed_c_str();
666 /// assert_eq!(&*boxed,
667 /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
669 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
670 pub fn into_boxed_c_str(self) -> Box<CStr> {
671 unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) }
674 /// Bypass "move out of struct which implements [`Drop`] trait" restriction.
676 fn into_inner(self) -> Box<[u8]> {
677 // Rationale: `mem::forget(self)` invalidates the previous call to `ptr::read(&self.inner)`
678 // so we use `ManuallyDrop` to ensure `self` is not dropped.
679 // Then we can return the box directly without invalidating it.
680 // See https://github.com/rust-lang/rust/issues/62553.
681 let this = mem::ManuallyDrop::new(self);
682 unsafe { ptr::read(&this.inner) }
685 /// Converts a [`Vec`]`<u8>` to a [`CString`] without checking the
686 /// invariants on the given [`Vec`].
690 /// The given [`Vec`] **must** have one nul byte as its last element.
691 /// This means it cannot be empty nor have any other nul byte anywhere else.
696 /// #![feature(cstring_from_vec_with_nul)]
697 /// use std::ffi::CString;
699 /// unsafe { CString::from_vec_with_nul_unchecked(b"abc\0".to_vec()) },
700 /// unsafe { CString::from_vec_unchecked(b"abc".to_vec()) }
703 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
704 pub unsafe fn from_vec_with_nul_unchecked(v: Vec<u8>) -> Self {
705 Self { inner: v.into_boxed_slice() }
708 /// Attempts to converts a [`Vec`]`<u8>` to a [`CString`].
710 /// Runtime checks are present to ensure there is only one nul byte in the
711 /// [`Vec`], its last element.
715 /// If a nul byte is present and not the last element or no nul bytes
716 /// is present, an error will be returned.
720 /// A successful conversion will produce the same result as [`CString::new`]
721 /// when called without the ending nul byte.
724 /// #![feature(cstring_from_vec_with_nul)]
725 /// use std::ffi::CString;
727 /// CString::from_vec_with_nul(b"abc\0".to_vec())
728 /// .expect("CString::from_vec_with_nul failed"),
729 /// CString::new(b"abc".to_vec()).expect("CString::new failed")
733 /// An incorrectly formatted [`Vec`] will produce an error.
736 /// #![feature(cstring_from_vec_with_nul)]
737 /// use std::ffi::{CString, FromVecWithNulError};
738 /// // Interior nul byte
739 /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"a\0bc".to_vec()).unwrap_err();
741 /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"abc".to_vec()).unwrap_err();
743 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
744 pub fn from_vec_with_nul(v: Vec<u8>) -> Result<Self, FromVecWithNulError> {
745 let nul_pos = memchr::memchr(0, &v);
747 Some(nul_pos) if nul_pos + 1 == v.len() => {
748 // SAFETY: We know there is only one nul byte, at the end
750 Ok(unsafe { Self::from_vec_with_nul_unchecked(v) })
752 Some(nul_pos) => Err(FromVecWithNulError {
753 error_kind: FromBytesWithNulErrorKind::InteriorNul(nul_pos),
756 None => Err(FromVecWithNulError {
757 error_kind: FromBytesWithNulErrorKind::NotNulTerminated,
764 // Turns this `CString` into an empty string to prevent
765 // memory-unsafe code from working by accident. Inline
766 // to prevent LLVM from optimizing it away in debug builds.
767 #[stable(feature = "cstring_drop", since = "1.13.0")]
768 impl Drop for CString {
772 *self.inner.get_unchecked_mut(0) = 0;
777 #[stable(feature = "rust1", since = "1.0.0")]
778 impl ops::Deref for CString {
782 fn deref(&self) -> &CStr {
783 unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
787 #[stable(feature = "rust1", since = "1.0.0")]
788 impl fmt::Debug for CString {
789 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
790 fmt::Debug::fmt(&**self, f)
794 #[stable(feature = "cstring_into", since = "1.7.0")]
795 impl From<CString> for Vec<u8> {
796 /// Converts a [`CString`] into a [`Vec`]`<u8>`.
798 /// The conversion consumes the [`CString`], and removes the terminating NUL byte.
800 fn from(s: CString) -> Vec<u8> {
805 #[stable(feature = "cstr_debug", since = "1.3.0")]
806 impl fmt::Debug for CStr {
807 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
809 for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
810 f.write_char(byte as char)?;
816 #[stable(feature = "cstr_default", since = "1.10.0")]
817 impl Default for &CStr {
818 fn default() -> Self {
819 const SLICE: &[c_char] = &[0];
820 unsafe { CStr::from_ptr(SLICE.as_ptr()) }
824 #[stable(feature = "cstr_default", since = "1.10.0")]
825 impl Default for CString {
826 /// Creates an empty `CString`.
827 fn default() -> CString {
828 let a: &CStr = Default::default();
833 #[stable(feature = "cstr_borrow", since = "1.3.0")]
834 impl Borrow<CStr> for CString {
836 fn borrow(&self) -> &CStr {
841 #[stable(feature = "cstring_from_cow_cstr", since = "1.28.0")]
842 impl<'a> From<Cow<'a, CStr>> for CString {
844 fn from(s: Cow<'a, CStr>) -> Self {
849 #[stable(feature = "box_from_c_str", since = "1.17.0")]
850 impl From<&CStr> for Box<CStr> {
851 fn from(s: &CStr) -> Box<CStr> {
852 let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul());
853 unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
857 #[stable(feature = "box_from_cow", since = "1.45.0")]
858 impl From<Cow<'_, CStr>> for Box<CStr> {
860 fn from(cow: Cow<'_, CStr>) -> Box<CStr> {
862 Cow::Borrowed(s) => Box::from(s),
863 Cow::Owned(s) => Box::from(s),
868 #[stable(feature = "c_string_from_box", since = "1.18.0")]
869 impl From<Box<CStr>> for CString {
870 /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating.
872 fn from(s: Box<CStr>) -> CString {
877 #[stable(feature = "cstring_from_vec_of_nonzerou8", since = "1.43.0")]
878 impl From<Vec<NonZeroU8>> for CString {
879 /// Converts a [`Vec`]`<`[`NonZeroU8`]`>` into a [`CString`] without
880 /// copying nor checking for inner null bytes.
882 fn from(v: Vec<NonZeroU8>) -> CString {
884 // Transmute `Vec<NonZeroU8>` to `Vec<u8>`.
887 // - transmuting between `NonZeroU8` and `u8` is sound;
888 // - `alloc::Layout<NonZeroU8> == alloc::Layout<u8>`.
889 let (ptr, len, cap): (*mut NonZeroU8, _, _) = Vec::into_raw_parts(v);
890 Vec::from_raw_parts(ptr.cast::<u8>(), len, cap)
892 // SAFETY: `v` cannot contain null bytes, given the type-level
893 // invariant of `NonZeroU8`.
894 CString::from_vec_unchecked(v)
899 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
900 impl Clone for Box<CStr> {
902 fn clone(&self) -> Self {
907 #[stable(feature = "box_from_c_string", since = "1.20.0")]
908 impl From<CString> for Box<CStr> {
909 /// Converts a [`CString`] into a [`Box`]`<CStr>` without copying or allocating.
911 fn from(s: CString) -> Box<CStr> {
916 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
917 impl<'a> From<CString> for Cow<'a, CStr> {
918 /// Converts a [`CString`] into an owned [`Cow`] without copying or allocating.
920 fn from(s: CString) -> Cow<'a, CStr> {
925 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
926 impl<'a> From<&'a CStr> for Cow<'a, CStr> {
927 /// Converts a [`CStr`] into a borrowed [`Cow`] without copying or allocating.
929 fn from(s: &'a CStr) -> Cow<'a, CStr> {
934 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
935 impl<'a> From<&'a CString> for Cow<'a, CStr> {
936 /// Converts a `&`[`CString`] into a borrowed [`Cow`] without copying or allocating.
938 fn from(s: &'a CString) -> Cow<'a, CStr> {
939 Cow::Borrowed(s.as_c_str())
943 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
944 impl From<CString> for Arc<CStr> {
945 /// Converts a [`CString`] into an [`Arc`]`<CStr>` without copying or allocating.
947 fn from(s: CString) -> Arc<CStr> {
948 let arc: Arc<[u8]> = Arc::from(s.into_inner());
949 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
953 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
954 impl From<&CStr> for Arc<CStr> {
956 fn from(s: &CStr) -> Arc<CStr> {
957 let arc: Arc<[u8]> = Arc::from(s.to_bytes_with_nul());
958 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
962 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
963 impl From<CString> for Rc<CStr> {
964 /// Converts a [`CString`] into an [`Rc`]`<CStr>` without copying or allocating.
966 fn from(s: CString) -> Rc<CStr> {
967 let rc: Rc<[u8]> = Rc::from(s.into_inner());
968 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
972 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
973 impl From<&CStr> for Rc<CStr> {
975 fn from(s: &CStr) -> Rc<CStr> {
976 let rc: Rc<[u8]> = Rc::from(s.to_bytes_with_nul());
977 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
981 #[stable(feature = "default_box_extra", since = "1.17.0")]
982 impl Default for Box<CStr> {
983 fn default() -> Box<CStr> {
984 let boxed: Box<[u8]> = Box::from([0]);
985 unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
990 /// Returns the position of the nul byte in the slice that caused
991 /// [`CString::new`] to fail.
996 /// use std::ffi::CString;
998 /// let nul_error = CString::new("foo\0bar").unwrap_err();
999 /// assert_eq!(nul_error.nul_position(), 3);
1001 /// let nul_error = CString::new("foo bar\0").unwrap_err();
1002 /// assert_eq!(nul_error.nul_position(), 7);
1004 #[stable(feature = "rust1", since = "1.0.0")]
1005 pub fn nul_position(&self) -> usize {
1009 /// Consumes this error, returning the underlying vector of bytes which
1010 /// generated the error in the first place.
1015 /// use std::ffi::CString;
1017 /// let nul_error = CString::new("foo\0bar").unwrap_err();
1018 /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 pub fn into_vec(self) -> Vec<u8> {
1026 #[stable(feature = "rust1", since = "1.0.0")]
1027 impl Error for NulError {
1028 #[allow(deprecated)]
1029 fn description(&self) -> &str {
1030 "nul byte found in data"
1034 #[stable(feature = "rust1", since = "1.0.0")]
1035 impl fmt::Display for NulError {
1036 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1037 write!(f, "nul byte found in provided data at position: {}", self.0)
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 impl From<NulError> for io::Error {
1043 /// Converts a [`NulError`] into a [`io::Error`].
1044 fn from(_: NulError) -> io::Error {
1045 io::Error::new_const(io::ErrorKind::InvalidInput, &"data provided contains a nul byte")
1049 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
1050 impl Error for FromBytesWithNulError {
1051 #[allow(deprecated)]
1052 fn description(&self) -> &str {
1054 FromBytesWithNulErrorKind::InteriorNul(..) => {
1055 "data provided contains an interior nul byte"
1057 FromBytesWithNulErrorKind::NotNulTerminated => "data provided is not nul terminated",
1062 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
1063 impl fmt::Display for FromBytesWithNulError {
1064 #[allow(deprecated, deprecated_in_future)]
1065 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1066 f.write_str(self.description())?;
1067 if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind {
1068 write!(f, " at byte pos {}", pos)?;
1074 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
1075 impl Error for FromVecWithNulError {}
1077 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
1078 impl fmt::Display for FromVecWithNulError {
1079 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1080 match self.error_kind {
1081 FromBytesWithNulErrorKind::InteriorNul(pos) => {
1082 write!(f, "data provided contains an interior nul byte at pos {}", pos)
1084 FromBytesWithNulErrorKind::NotNulTerminated => {
1085 write!(f, "data provided is not nul terminated")
1091 impl IntoStringError {
1092 /// Consumes this error, returning original [`CString`] which generated the
1094 #[stable(feature = "cstring_into", since = "1.7.0")]
1095 pub fn into_cstring(self) -> CString {
1099 /// Access the underlying UTF-8 error that was the cause of this error.
1100 #[stable(feature = "cstring_into", since = "1.7.0")]
1101 pub fn utf8_error(&self) -> Utf8Error {
1106 #[stable(feature = "cstring_into", since = "1.7.0")]
1107 impl Error for IntoStringError {
1108 #[allow(deprecated)]
1109 fn description(&self) -> &str {
1110 "C string contained non-utf8 bytes"
1113 fn source(&self) -> Option<&(dyn Error + 'static)> {
1118 #[stable(feature = "cstring_into", since = "1.7.0")]
1119 impl fmt::Display for IntoStringError {
1120 #[allow(deprecated, deprecated_in_future)]
1121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1122 self.description().fmt(f)
1127 /// Wraps a raw C string with a safe C string wrapper.
1129 /// This function will wrap the provided `ptr` with a `CStr` wrapper, which
1130 /// allows inspection and interoperation of non-owned C strings. The total
1131 /// size of the raw C string must be smaller than `isize::MAX` **bytes**
1132 /// in memory due to calling the `slice::from_raw_parts` function.
1133 /// This method is unsafe for a number of reasons:
1135 /// * There is no guarantee to the validity of `ptr`.
1136 /// * The returned lifetime is not guaranteed to be the actual lifetime of
1138 /// * There is no guarantee that the memory pointed to by `ptr` contains a
1139 /// valid nul terminator byte at the end of the string.
1140 /// * It is not guaranteed that the memory pointed by `ptr` won't change
1141 /// before the `CStr` has been destroyed.
1143 /// > **Note**: This operation is intended to be a 0-cost cast but it is
1144 /// > currently implemented with an up-front calculation of the length of
1145 /// > the string. This is not guaranteed to always be the case.
1149 /// ```ignore (extern-declaration)
1151 /// use std::ffi::CStr;
1152 /// use std::os::raw::c_char;
1155 /// fn my_string() -> *const c_char;
1159 /// let slice = CStr::from_ptr(my_string());
1160 /// println!("string returned: {}", slice.to_str().unwrap());
1164 #[stable(feature = "rust1", since = "1.0.0")]
1165 pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
1166 // SAFETY: The caller has provided a pointer that points to a valid C
1167 // string with a NUL terminator of size less than `isize::MAX`, whose
1168 // content remain valid and doesn't change for the lifetime of the
1171 // Thus computing the length is fine (a NUL byte exists), the call to
1172 // from_raw_parts is safe because we know the length is at most `isize::MAX`, meaning
1173 // the call to `from_bytes_with_nul_unchecked` is correct.
1175 // The cast from c_char to u8 is ok because a c_char is always one byte.
1177 let len = sys::strlen(ptr);
1178 let ptr = ptr as *const u8;
1179 CStr::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr, len as usize + 1))
1183 /// Creates a C string wrapper from a byte slice.
1185 /// This function will cast the provided `bytes` to a `CStr`
1186 /// wrapper after ensuring that the byte slice is nul-terminated
1187 /// and does not contain any interior nul bytes.
1192 /// use std::ffi::CStr;
1194 /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
1195 /// assert!(cstr.is_ok());
1198 /// Creating a `CStr` without a trailing nul terminator is an error:
1201 /// use std::ffi::CStr;
1203 /// let cstr = CStr::from_bytes_with_nul(b"hello");
1204 /// assert!(cstr.is_err());
1207 /// Creating a `CStr` with an interior nul byte is an error:
1210 /// use std::ffi::CStr;
1212 /// let cstr = CStr::from_bytes_with_nul(b"he\0llo\0");
1213 /// assert!(cstr.is_err());
1215 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
1216 pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError> {
1217 let nul_pos = memchr::memchr(0, bytes);
1218 if let Some(nul_pos) = nul_pos {
1219 if nul_pos + 1 != bytes.len() {
1220 return Err(FromBytesWithNulError::interior_nul(nul_pos));
1222 Ok(unsafe { CStr::from_bytes_with_nul_unchecked(bytes) })
1224 Err(FromBytesWithNulError::not_nul_terminated())
1228 /// Unsafely creates a C string wrapper from a byte slice.
1230 /// This function will cast the provided `bytes` to a `CStr` wrapper without
1231 /// performing any sanity checks. The provided slice **must** be nul-terminated
1232 /// and not contain any interior nul bytes.
1237 /// use std::ffi::{CStr, CString};
1240 /// let cstring = CString::new("hello").expect("CString::new failed");
1241 /// let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
1242 /// assert_eq!(cstr, &*cstring);
1246 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
1247 #[rustc_const_unstable(feature = "const_cstr_unchecked", issue = "none")]
1248 pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
1249 // SAFETY: Casting to CStr is safe because its internal representation
1250 // is a [u8] too (safe only inside std).
1251 // Dereferencing the obtained pointer is safe because it comes from a
1252 // reference. Making a reference is then safe because its lifetime
1253 // is bound by the lifetime of the given `bytes`.
1254 unsafe { &*(bytes as *const [u8] as *const CStr) }
1257 /// Returns the inner pointer to this C string.
1259 /// The returned pointer will be valid for as long as `self` is, and points
1260 /// to a contiguous region of memory terminated with a 0 byte to represent
1261 /// the end of the string.
1265 /// The returned pointer is read-only; writing to it (including passing it
1266 /// to C code that writes to it) causes undefined behavior.
1268 /// It is your responsibility to make sure that the underlying memory is not
1269 /// freed too early. For example, the following code will cause undefined
1270 /// behavior when `ptr` is used inside the `unsafe` block:
1273 /// # #![allow(unused_must_use)] #![allow(temporary_cstring_as_ptr)]
1274 /// use std::ffi::CString;
1276 /// let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
1278 /// // `ptr` is dangling
1283 /// This happens because the pointer returned by `as_ptr` does not carry any
1284 /// lifetime information and the [`CString`] is deallocated immediately after
1285 /// the `CString::new("Hello").expect("CString::new failed").as_ptr()`
1286 /// expression is evaluated.
1287 /// To fix the problem, bind the `CString` to a local variable:
1290 /// # #![allow(unused_must_use)]
1291 /// use std::ffi::CString;
1293 /// let hello = CString::new("Hello").expect("CString::new failed");
1294 /// let ptr = hello.as_ptr();
1296 /// // `ptr` is valid because `hello` is in scope
1301 /// This way, the lifetime of the [`CString`] in `hello` encompasses
1302 /// the lifetime of `ptr` and the `unsafe` block.
1304 #[stable(feature = "rust1", since = "1.0.0")]
1305 #[rustc_const_stable(feature = "const_str_as_ptr", since = "1.32.0")]
1306 pub const fn as_ptr(&self) -> *const c_char {
1310 /// Converts this C string to a byte slice.
1312 /// The returned slice will **not** contain the trailing nul terminator that this C
1315 /// > **Note**: This method is currently implemented as a constant-time
1316 /// > cast, but it is planned to alter its definition in the future to
1317 /// > perform the length calculation whenever this method is called.
1322 /// use std::ffi::CStr;
1324 /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1325 /// assert_eq!(cstr.to_bytes(), b"foo");
1328 #[stable(feature = "rust1", since = "1.0.0")]
1329 pub fn to_bytes(&self) -> &[u8] {
1330 let bytes = self.to_bytes_with_nul();
1331 // SAFETY: to_bytes_with_nul returns slice with length at least 1
1332 unsafe { bytes.get_unchecked(..bytes.len() - 1) }
1335 /// Converts this C string to a byte slice containing the trailing 0 byte.
1337 /// This function is the equivalent of [`CStr::to_bytes`] except that it
1338 /// will retain the trailing nul terminator instead of chopping it off.
1340 /// > **Note**: This method is currently implemented as a 0-cost cast, but
1341 /// > it is planned to alter its definition in the future to perform the
1342 /// > length calculation whenever this method is called.
1347 /// use std::ffi::CStr;
1349 /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1350 /// assert_eq!(cstr.to_bytes_with_nul(), b"foo\0");
1353 #[stable(feature = "rust1", since = "1.0.0")]
1354 pub fn to_bytes_with_nul(&self) -> &[u8] {
1355 unsafe { &*(&self.inner as *const [c_char] as *const [u8]) }
1358 /// Yields a [`&str`] slice if the `CStr` contains valid UTF-8.
1360 /// If the contents of the `CStr` are valid UTF-8 data, this
1361 /// function will return the corresponding [`&str`] slice. Otherwise,
1362 /// it will return an error with details of where UTF-8 validation failed.
1364 /// [`&str`]: prim@str
1369 /// use std::ffi::CStr;
1371 /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1372 /// assert_eq!(cstr.to_str(), Ok("foo"));
1374 #[stable(feature = "cstr_to_str", since = "1.4.0")]
1375 pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
1376 // N.B., when `CStr` is changed to perform the length check in `.to_bytes()`
1377 // instead of in `from_ptr()`, it may be worth considering if this should
1378 // be rewritten to do the UTF-8 check inline with the length calculation
1379 // instead of doing it afterwards.
1380 str::from_utf8(self.to_bytes())
1383 /// Converts a `CStr` into a [`Cow`]`<`[`str`]`>`.
1385 /// If the contents of the `CStr` are valid UTF-8 data, this
1386 /// function will return a [`Cow`]`::`[`Borrowed`]`(`[`&str`]`)`
1387 /// with the corresponding [`&str`] slice. Otherwise, it will
1388 /// replace any invalid UTF-8 sequences with
1389 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD] and return a
1390 /// [`Cow`]`::`[`Owned`]`(`[`String`]`)` with the result.
1392 /// [`str`]: primitive@str
1393 /// [`&str`]: primitive@str
1394 /// [`Borrowed`]: Cow::Borrowed
1395 /// [`Owned`]: Cow::Owned
1396 /// [U+FFFD]: crate::char::REPLACEMENT_CHARACTER
1400 /// Calling `to_string_lossy` on a `CStr` containing valid UTF-8:
1403 /// use std::borrow::Cow;
1404 /// use std::ffi::CStr;
1406 /// let cstr = CStr::from_bytes_with_nul(b"Hello World\0")
1407 /// .expect("CStr::from_bytes_with_nul failed");
1408 /// assert_eq!(cstr.to_string_lossy(), Cow::Borrowed("Hello World"));
1411 /// Calling `to_string_lossy` on a `CStr` containing invalid UTF-8:
1414 /// use std::borrow::Cow;
1415 /// use std::ffi::CStr;
1417 /// let cstr = CStr::from_bytes_with_nul(b"Hello \xF0\x90\x80World\0")
1418 /// .expect("CStr::from_bytes_with_nul failed");
1420 /// cstr.to_string_lossy(),
1421 /// Cow::Owned(String::from("Hello �World")) as Cow<'_, str>
1424 #[stable(feature = "cstr_to_str", since = "1.4.0")]
1425 pub fn to_string_lossy(&self) -> Cow<'_, str> {
1426 String::from_utf8_lossy(self.to_bytes())
1429 /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating.
1434 /// use std::ffi::CString;
1436 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
1437 /// let boxed = c_string.into_boxed_c_str();
1438 /// assert_eq!(boxed.into_c_string(), CString::new("foo").expect("CString::new failed"));
1440 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
1441 pub fn into_c_string(self: Box<CStr>) -> CString {
1442 let raw = Box::into_raw(self) as *mut [u8];
1443 CString { inner: unsafe { Box::from_raw(raw) } }
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 impl PartialEq for CStr {
1449 fn eq(&self, other: &CStr) -> bool {
1450 self.to_bytes().eq(other.to_bytes())
1453 #[stable(feature = "rust1", since = "1.0.0")]
1455 #[stable(feature = "rust1", since = "1.0.0")]
1456 impl PartialOrd for CStr {
1457 fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
1458 self.to_bytes().partial_cmp(&other.to_bytes())
1461 #[stable(feature = "rust1", since = "1.0.0")]
1463 fn cmp(&self, other: &CStr) -> Ordering {
1464 self.to_bytes().cmp(&other.to_bytes())
1468 #[stable(feature = "cstr_borrow", since = "1.3.0")]
1469 impl ToOwned for CStr {
1470 type Owned = CString;
1472 fn to_owned(&self) -> CString {
1473 CString { inner: self.to_bytes_with_nul().into() }
1476 fn clone_into(&self, target: &mut CString) {
1477 let mut b = Vec::from(mem::take(&mut target.inner));
1478 self.to_bytes_with_nul().clone_into(&mut b);
1479 target.inner = b.into_boxed_slice();
1483 #[stable(feature = "cstring_asref", since = "1.7.0")]
1484 impl From<&CStr> for CString {
1485 fn from(s: &CStr) -> CString {
1490 #[stable(feature = "cstring_asref", since = "1.7.0")]
1491 impl ops::Index<ops::RangeFull> for CString {
1495 fn index(&self, _index: ops::RangeFull) -> &CStr {
1500 #[stable(feature = "cstr_range_from", since = "1.47.0")]
1501 impl ops::Index<ops::RangeFrom<usize>> for CStr {
1504 fn index(&self, index: ops::RangeFrom<usize>) -> &CStr {
1505 let bytes = self.to_bytes_with_nul();
1506 // we need to manually check the starting index to account for the null
1507 // byte, since otherwise we could get an empty string that doesn't end
1509 if index.start < bytes.len() {
1510 unsafe { CStr::from_bytes_with_nul_unchecked(&bytes[index.start..]) }
1513 "index out of bounds: the len is {} but the index is {}",
1521 #[stable(feature = "cstring_asref", since = "1.7.0")]
1522 impl AsRef<CStr> for CStr {
1524 fn as_ref(&self) -> &CStr {
1529 #[stable(feature = "cstring_asref", since = "1.7.0")]
1530 impl AsRef<CStr> for CString {
1532 fn as_ref(&self) -> &CStr {