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 <code>&[CStr]</code> as [`String`] is to <code>&[str]</code>: 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 <code>[Into]<[Vec]<[u8]>></code> (for
40 /// example, you can build a `CString` straight out of a [`String`] or
41 /// a <code>&[str]</code>, since both implement that trait).
43 /// The [`CString::new`] method will actually check that the provided <code>&[[u8]]</code>
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 <code>&[[u8]]</code> 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 <code>&[[u8]]</code> 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 "str"
77 /// [`Deref`]: ops::Deref
81 /// ```ignore (extern-declaration)
83 /// use std::ffi::CString;
84 /// use std::os::raw::c_char;
87 /// fn my_printer(s: *const c_char);
90 /// // We are certain that our string doesn't have 0 bytes in the middle,
91 /// // so we can .expect()
92 /// let c_to_print = CString::new("Hello, world!").expect("CString::new failed");
94 /// my_printer(c_to_print.as_ptr());
101 /// `CString` is intended for working with traditional C-style strings
102 /// (a sequence of non-nul bytes terminated by a single nul byte); the
103 /// primary use case for these kinds of strings is interoperating with C-like
104 /// code. Often you will need to transfer ownership to/from that external
105 /// code. It is strongly recommended that you thoroughly read through the
106 /// documentation of `CString` before use, as improper ownership management
107 /// of `CString` instances can lead to invalid memory accesses, memory leaks,
108 /// and other memory errors.
109 #[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
110 #[cfg_attr(not(test), rustc_diagnostic_item = "cstring_type")]
111 #[stable(feature = "rust1", since = "1.0.0")]
113 // Invariant 1: the slice ends with a zero byte and has a length of at least one.
114 // Invariant 2: the slice contains only one zero byte.
115 // Improper usage of unsafe function can break Invariant 2, but not Invariant 1.
119 /// Representation of a borrowed C string.
121 /// This type represents a borrowed reference to a nul-terminated
122 /// array of bytes. It can be constructed safely from a <code>&[[u8]]</code>
123 /// slice, or unsafely from a raw `*const c_char`. It can then be
124 /// converted to a Rust <code>&[str]</code> by performing UTF-8 validation, or
125 /// into an owned [`CString`].
127 /// `&CStr` is to [`CString`] as <code>&[str]</code> is to [`String`]: the former
128 /// in each pair are borrowed references; the latter are owned
131 /// Note that this structure is **not** `repr(C)` and is not recommended to be
132 /// placed in the signatures of FFI functions. Instead, safe wrappers of FFI
133 /// functions may leverage the unsafe [`CStr::from_ptr`] constructor to provide
134 /// a safe interface to other consumers.
138 /// Inspecting a foreign C string:
140 /// ```ignore (extern-declaration)
141 /// use std::ffi::CStr;
142 /// use std::os::raw::c_char;
144 /// extern "C" { fn my_string() -> *const c_char; }
147 /// let slice = CStr::from_ptr(my_string());
148 /// println!("string buffer size without nul terminator: {}", slice.to_bytes().len());
152 /// Passing a Rust-originating C string:
154 /// ```ignore (extern-declaration)
155 /// use std::ffi::{CString, CStr};
156 /// use std::os::raw::c_char;
158 /// fn work(data: &CStr) {
159 /// extern "C" { fn work_with(data: *const c_char); }
161 /// unsafe { work_with(data.as_ptr()) }
164 /// let s = CString::new("data data data data").expect("CString::new failed");
168 /// Converting a foreign C string into a Rust [`String`]:
170 /// ```ignore (extern-declaration)
171 /// use std::ffi::CStr;
172 /// use std::os::raw::c_char;
174 /// extern "C" { fn my_string() -> *const c_char; }
176 /// fn my_string_safe() -> String {
178 /// CStr::from_ptr(my_string()).to_string_lossy().into_owned()
182 /// println!("string: {}", my_string_safe());
185 /// [str]: prim@str "str"
187 #[cfg_attr(not(test), rustc_diagnostic_item = "CStr")]
188 #[stable(feature = "rust1", since = "1.0.0")]
190 // `fn from` in `impl From<&CStr> for Box<CStr>` current implementation relies
191 // on `CStr` being layout-compatible with `[u8]`.
192 // When attribute privacy is implemented, `CStr` should be annotated as `#[repr(transparent)]`.
193 // Anyway, `CStr` representation and layout are considered implementation detail, are
194 // not documented and must not be relied upon.
196 // FIXME: this should not be represented with a DST slice but rather with
197 // just a raw `c_char` along with some form of marker to make
198 // this an unsized type. Essentially `sizeof(&CStr)` should be the
199 // same as `sizeof(&c_char)` but `CStr` should be an unsized type.
203 /// An error indicating that an interior nul byte was found.
205 /// While Rust strings may contain nul bytes in the middle, C strings
206 /// can't, as that byte would effectively truncate the string.
208 /// This error is created by the [`new`][`CString::new`] method on
209 /// [`CString`]. See its documentation for more.
214 /// use std::ffi::{CString, NulError};
216 /// let _: NulError = CString::new(b"f\0oo".to_vec()).unwrap_err();
218 #[derive(Clone, PartialEq, Eq, Debug)]
219 #[stable(feature = "rust1", since = "1.0.0")]
220 pub struct NulError(usize, Vec<u8>);
222 /// An error indicating that a nul byte was not in the expected position.
224 /// The slice used to create a [`CStr`] must have one and only one nul byte,
225 /// positioned at the end.
227 /// This error is created by the [`CStr::from_bytes_with_nul`] method.
228 /// See its documentation for more.
233 /// use std::ffi::{CStr, FromBytesWithNulError};
235 /// let _: FromBytesWithNulError = CStr::from_bytes_with_nul(b"f\0oo").unwrap_err();
237 #[derive(Clone, PartialEq, Eq, Debug)]
238 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
239 pub struct FromBytesWithNulError {
240 kind: FromBytesWithNulErrorKind,
243 /// An error indicating that a nul byte was not in the expected position.
245 /// The vector used to create a [`CString`] must have one and only one nul byte,
246 /// positioned at the end.
248 /// This error is created by the [`CString::from_vec_with_nul`] method.
249 /// See its documentation for more.
254 /// #![feature(cstring_from_vec_with_nul)]
255 /// use std::ffi::{CString, FromVecWithNulError};
257 /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"f\0oo".to_vec()).unwrap_err();
259 #[derive(Clone, PartialEq, Eq, Debug)]
260 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
261 pub struct FromVecWithNulError {
262 error_kind: FromBytesWithNulErrorKind,
266 #[derive(Clone, PartialEq, Eq, Debug)]
267 enum FromBytesWithNulErrorKind {
272 impl FromBytesWithNulError {
273 fn interior_nul(pos: usize) -> FromBytesWithNulError {
274 FromBytesWithNulError { kind: FromBytesWithNulErrorKind::InteriorNul(pos) }
276 fn not_nul_terminated() -> FromBytesWithNulError {
277 FromBytesWithNulError { kind: FromBytesWithNulErrorKind::NotNulTerminated }
281 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
282 impl FromVecWithNulError {
283 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a [`CString`].
290 /// #![feature(cstring_from_vec_with_nul)]
291 /// use std::ffi::CString;
293 /// // Some invalid bytes in a vector
294 /// let bytes = b"f\0oo".to_vec();
296 /// let value = CString::from_vec_with_nul(bytes.clone());
298 /// 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 #[must_use = "`self` will be dropped if the result is not used"]
327 pub fn into_bytes(self) -> Vec<u8> {
332 /// An error indicating invalid UTF-8 when converting a [`CString`] into a [`String`].
334 /// `CString` is just a wrapper over a buffer of bytes with a nul terminator;
335 /// [`CString::into_string`] performs UTF-8 validation on those bytes and may
336 /// return this error.
338 /// This `struct` is created by [`CString::into_string()`]. See
339 /// its documentation for more.
340 #[derive(Clone, PartialEq, Eq, Debug)]
341 #[stable(feature = "cstring_into", since = "1.7.0")]
342 pub struct IntoStringError {
348 /// Creates a new C-compatible string from a container of bytes.
350 /// This function will consume the provided data and use the
351 /// underlying bytes to construct a new string, ensuring that
352 /// there is a trailing 0 byte. This trailing 0 byte will be
353 /// appended by this function; the provided data should *not*
354 /// contain any 0 bytes in it.
358 /// ```ignore (extern-declaration)
359 /// use std::ffi::CString;
360 /// use std::os::raw::c_char;
362 /// extern "C" { fn puts(s: *const c_char); }
364 /// let to_print = CString::new("Hello!").expect("CString::new failed");
366 /// puts(to_print.as_ptr());
372 /// This function will return an error if the supplied bytes contain an
373 /// internal 0 byte. The [`NulError`] returned will contain the bytes as well as
374 /// the position of the nul byte.
375 #[stable(feature = "rust1", since = "1.0.0")]
376 pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
378 fn into_vec(self) -> Vec<u8>;
380 impl<T: Into<Vec<u8>>> SpecIntoVec for T {
381 default fn into_vec(self) -> Vec<u8> {
385 // Specialization for avoiding reallocation.
386 impl SpecIntoVec for &'_ [u8] {
387 fn into_vec(self) -> Vec<u8> {
388 let mut v = Vec::with_capacity(self.len() + 1);
393 impl SpecIntoVec for &'_ str {
394 fn into_vec(self) -> Vec<u8> {
395 let mut v = Vec::with_capacity(self.len() + 1);
396 v.extend(self.as_bytes());
401 Self::_new(SpecIntoVec::into_vec(t))
404 fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
405 match memchr::memchr(0, &bytes) {
406 Some(i) => Err(NulError(i, bytes)),
407 None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
411 /// Creates a C-compatible string by consuming a byte vector,
412 /// without checking for interior 0 bytes.
414 /// Trailing 0 byte will be appended by this function.
416 /// This method is equivalent to [`CString::new`] except that no runtime
417 /// assertion is made that `v` contains no 0 bytes, and it requires an
418 /// actual byte vector, not anything that can be converted to one with Into.
423 /// use std::ffi::CString;
425 /// let raw = b"foo".to_vec();
427 /// let c_string = CString::from_vec_unchecked(raw);
431 #[stable(feature = "rust1", since = "1.0.0")]
432 pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
435 CString { inner: v.into_boxed_slice() }
438 /// Retakes ownership of a `CString` that was transferred to C via
439 /// [`CString::into_raw`].
441 /// Additionally, the length of the string will be recalculated from the pointer.
445 /// This should only ever be called with a pointer that was earlier
446 /// obtained by calling [`CString::into_raw`]. Other usage (e.g., trying to take
447 /// ownership of a string that was allocated by foreign code) is likely to lead
448 /// to undefined behavior or allocator corruption.
450 /// It should be noted that the length isn't just "recomputed," but that
451 /// the recomputed length must match the original length from the
452 /// [`CString::into_raw`] call. This means the [`CString::into_raw`]/`from_raw`
453 /// methods should not be used when passing the string to C functions that can
454 /// modify the string's length.
456 /// > **Note:** If you need to borrow a string that was allocated by
457 /// > foreign code, use [`CStr`]. If you need to take ownership of
458 /// > a string that was allocated by foreign code, you will need to
459 /// > make your own provisions for freeing it appropriately, likely
460 /// > with the foreign code's API to do that.
464 /// Creates a `CString`, pass ownership to an `extern` function (via raw pointer), then retake
465 /// ownership with `from_raw`:
467 /// ```ignore (extern-declaration)
468 /// use std::ffi::CString;
469 /// use std::os::raw::c_char;
472 /// fn some_extern_function(s: *mut c_char);
475 /// let c_string = CString::new("Hello!").expect("CString::new failed");
476 /// let raw = c_string.into_raw();
478 /// some_extern_function(raw);
479 /// let c_string = CString::from_raw(raw);
482 #[must_use = "call `drop(from_raw(ptr))` if you intend to drop the `CString`"]
483 #[stable(feature = "cstr_memory", since = "1.4.0")]
484 pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
485 // SAFETY: This is called with a pointer that was obtained from a call
486 // to `CString::into_raw` and the length has not been modified. As such,
487 // we know there is a NUL byte (and only one) at the end and that the
488 // information about the size of the allocation is correct on Rust's
491 let len = sys::strlen(ptr) + 1; // Including the NUL byte
492 let slice = slice::from_raw_parts_mut(ptr, len as usize);
493 CString { inner: Box::from_raw(slice as *mut [c_char] as *mut [u8]) }
497 /// Consumes the `CString` and transfers ownership of the string to a C caller.
499 /// The pointer which this function returns must be returned to Rust and reconstituted using
500 /// [`CString::from_raw`] to be properly deallocated. Specifically, one
501 /// should *not* use the standard C `free()` function to deallocate
504 /// Failure to call [`CString::from_raw`] will lead to a memory leak.
506 /// The C side must **not** modify the length of the string (by writing a
507 /// `null` somewhere inside the string or removing the final one) before
508 /// it makes it back into Rust using [`CString::from_raw`]. See the safety section
509 /// in [`CString::from_raw`].
514 /// use std::ffi::CString;
516 /// let c_string = CString::new("foo").expect("CString::new failed");
518 /// let ptr = c_string.into_raw();
521 /// assert_eq!(b'f', *ptr as u8);
522 /// assert_eq!(b'o', *ptr.offset(1) as u8);
523 /// assert_eq!(b'o', *ptr.offset(2) as u8);
524 /// assert_eq!(b'\0', *ptr.offset(3) as u8);
526 /// // retake pointer to free memory
527 /// let _ = CString::from_raw(ptr);
531 #[must_use = "`self` will be dropped if the result is not used"]
532 #[stable(feature = "cstr_memory", since = "1.4.0")]
533 pub fn into_raw(self) -> *mut c_char {
534 Box::into_raw(self.into_inner()) as *mut c_char
537 /// Converts the `CString` into a [`String`] if it contains valid UTF-8 data.
539 /// On failure, ownership of the original `CString` is returned.
544 /// use std::ffi::CString;
546 /// let valid_utf8 = vec![b'f', b'o', b'o'];
547 /// let cstring = CString::new(valid_utf8).expect("CString::new failed");
548 /// assert_eq!(cstring.into_string().expect("into_string() call failed"), "foo");
550 /// let invalid_utf8 = vec![b'f', 0xff, b'o', b'o'];
551 /// let cstring = CString::new(invalid_utf8).expect("CString::new failed");
552 /// let err = cstring.into_string().err().expect("into_string().err() failed");
553 /// assert_eq!(err.utf8_error().valid_up_to(), 1);
555 #[stable(feature = "cstring_into", since = "1.7.0")]
556 pub fn into_string(self) -> Result<String, IntoStringError> {
557 String::from_utf8(self.into_bytes()).map_err(|e| IntoStringError {
558 error: e.utf8_error(),
559 inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
563 /// Consumes the `CString` and returns the underlying byte buffer.
565 /// The returned buffer does **not** contain the trailing nul
566 /// terminator, and it is guaranteed to not have any interior nul
572 /// use std::ffi::CString;
574 /// let c_string = CString::new("foo").expect("CString::new failed");
575 /// let bytes = c_string.into_bytes();
576 /// assert_eq!(bytes, vec![b'f', b'o', b'o']);
578 #[must_use = "`self` will be dropped if the result is not used"]
579 #[stable(feature = "cstring_into", since = "1.7.0")]
580 pub fn into_bytes(self) -> Vec<u8> {
581 let mut vec = self.into_inner().into_vec();
582 let _nul = vec.pop();
583 debug_assert_eq!(_nul, Some(0u8));
587 /// Equivalent to [`CString::into_bytes()`] except that the
588 /// returned vector includes the trailing nul terminator.
593 /// use std::ffi::CString;
595 /// let c_string = CString::new("foo").expect("CString::new failed");
596 /// let bytes = c_string.into_bytes_with_nul();
597 /// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
599 #[must_use = "`self` will be dropped if the result is not used"]
600 #[stable(feature = "cstring_into", since = "1.7.0")]
601 pub fn into_bytes_with_nul(self) -> Vec<u8> {
602 self.into_inner().into_vec()
605 /// Returns the contents of this `CString` as a slice of bytes.
607 /// The returned slice does **not** contain the trailing nul
608 /// terminator, and it is guaranteed to not have any interior nul
609 /// bytes. If you need the nul terminator, use
610 /// [`CString::as_bytes_with_nul`] instead.
615 /// use std::ffi::CString;
617 /// let c_string = CString::new("foo").expect("CString::new failed");
618 /// let bytes = c_string.as_bytes();
619 /// assert_eq!(bytes, &[b'f', b'o', b'o']);
623 #[stable(feature = "rust1", since = "1.0.0")]
624 pub fn as_bytes(&self) -> &[u8] {
625 // SAFETY: CString has a length at least 1
626 unsafe { self.inner.get_unchecked(..self.inner.len() - 1) }
629 /// Equivalent to [`CString::as_bytes()`] except that the
630 /// returned slice includes the trailing nul terminator.
635 /// use std::ffi::CString;
637 /// let c_string = CString::new("foo").expect("CString::new failed");
638 /// let bytes = c_string.as_bytes_with_nul();
639 /// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
643 #[stable(feature = "rust1", since = "1.0.0")]
644 pub fn as_bytes_with_nul(&self) -> &[u8] {
648 /// Extracts a [`CStr`] slice containing the entire string.
653 /// use std::ffi::{CString, CStr};
655 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
656 /// let cstr = c_string.as_c_str();
658 /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
662 #[stable(feature = "as_c_str", since = "1.20.0")]
663 pub fn as_c_str(&self) -> &CStr {
667 /// Converts this `CString` into a boxed [`CStr`].
672 /// use std::ffi::{CString, CStr};
674 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
675 /// let boxed = c_string.into_boxed_c_str();
676 /// assert_eq!(&*boxed,
677 /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
679 #[must_use = "`self` will be dropped if the result is not used"]
680 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
681 pub fn into_boxed_c_str(self) -> Box<CStr> {
682 unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) }
685 /// Bypass "move out of struct which implements [`Drop`] trait" restriction.
687 fn into_inner(self) -> Box<[u8]> {
688 // Rationale: `mem::forget(self)` invalidates the previous call to `ptr::read(&self.inner)`
689 // so we use `ManuallyDrop` to ensure `self` is not dropped.
690 // Then we can return the box directly without invalidating it.
691 // See https://github.com/rust-lang/rust/issues/62553.
692 let this = mem::ManuallyDrop::new(self);
693 unsafe { ptr::read(&this.inner) }
696 /// Converts a <code>[Vec]<[u8]></code> to a [`CString`] without checking the
697 /// invariants on the given [`Vec`].
701 /// The given [`Vec`] **must** have one nul byte as its last element.
702 /// This means it cannot be empty nor have any other nul byte anywhere else.
707 /// #![feature(cstring_from_vec_with_nul)]
708 /// use std::ffi::CString;
710 /// unsafe { CString::from_vec_with_nul_unchecked(b"abc\0".to_vec()) },
711 /// unsafe { CString::from_vec_unchecked(b"abc".to_vec()) }
715 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
716 pub unsafe fn from_vec_with_nul_unchecked(v: Vec<u8>) -> Self {
717 Self { inner: v.into_boxed_slice() }
720 /// Attempts to converts a <code>[Vec]<[u8]></code> to a [`CString`].
722 /// Runtime checks are present to ensure there is only one nul byte in the
723 /// [`Vec`], its last element.
727 /// If a nul byte is present and not the last element or no nul bytes
728 /// is present, an error will be returned.
732 /// A successful conversion will produce the same result as [`CString::new`]
733 /// when called without the ending nul byte.
736 /// #![feature(cstring_from_vec_with_nul)]
737 /// use std::ffi::CString;
739 /// CString::from_vec_with_nul(b"abc\0".to_vec())
740 /// .expect("CString::from_vec_with_nul failed"),
741 /// CString::new(b"abc".to_vec()).expect("CString::new failed")
745 /// An incorrectly formatted [`Vec`] will produce an error.
748 /// #![feature(cstring_from_vec_with_nul)]
749 /// use std::ffi::{CString, FromVecWithNulError};
750 /// // Interior nul byte
751 /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"a\0bc".to_vec()).unwrap_err();
753 /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"abc".to_vec()).unwrap_err();
755 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
756 pub fn from_vec_with_nul(v: Vec<u8>) -> Result<Self, FromVecWithNulError> {
757 let nul_pos = memchr::memchr(0, &v);
759 Some(nul_pos) if nul_pos + 1 == v.len() => {
760 // SAFETY: We know there is only one nul byte, at the end
762 Ok(unsafe { Self::from_vec_with_nul_unchecked(v) })
764 Some(nul_pos) => Err(FromVecWithNulError {
765 error_kind: FromBytesWithNulErrorKind::InteriorNul(nul_pos),
768 None => Err(FromVecWithNulError {
769 error_kind: FromBytesWithNulErrorKind::NotNulTerminated,
776 // Turns this `CString` into an empty string to prevent
777 // memory-unsafe code from working by accident. Inline
778 // to prevent LLVM from optimizing it away in debug builds.
779 #[stable(feature = "cstring_drop", since = "1.13.0")]
780 impl Drop for CString {
784 *self.inner.get_unchecked_mut(0) = 0;
789 #[stable(feature = "rust1", since = "1.0.0")]
790 impl ops::Deref for CString {
794 fn deref(&self) -> &CStr {
795 unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
799 #[stable(feature = "rust1", since = "1.0.0")]
800 impl fmt::Debug for CString {
801 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
802 fmt::Debug::fmt(&**self, f)
806 #[stable(feature = "cstring_into", since = "1.7.0")]
807 impl From<CString> for Vec<u8> {
808 /// Converts a [`CString`] into a <code>[Vec]<[u8]></code>.
810 /// The conversion consumes the [`CString`], and removes the terminating NUL byte.
812 fn from(s: CString) -> Vec<u8> {
817 #[stable(feature = "cstr_debug", since = "1.3.0")]
818 impl fmt::Debug for CStr {
819 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
821 for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
822 f.write_char(byte as char)?;
828 #[stable(feature = "cstr_default", since = "1.10.0")]
829 impl Default for &CStr {
830 fn default() -> Self {
831 const SLICE: &[c_char] = &[0];
832 unsafe { CStr::from_ptr(SLICE.as_ptr()) }
836 #[stable(feature = "cstr_default", since = "1.10.0")]
837 impl Default for CString {
838 /// Creates an empty `CString`.
839 fn default() -> CString {
840 let a: &CStr = Default::default();
845 #[stable(feature = "cstr_borrow", since = "1.3.0")]
846 impl Borrow<CStr> for CString {
848 fn borrow(&self) -> &CStr {
853 #[stable(feature = "cstring_from_cow_cstr", since = "1.28.0")]
854 impl<'a> From<Cow<'a, CStr>> for CString {
856 fn from(s: Cow<'a, CStr>) -> Self {
861 #[stable(feature = "box_from_c_str", since = "1.17.0")]
862 impl From<&CStr> for Box<CStr> {
863 fn from(s: &CStr) -> Box<CStr> {
864 let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul());
865 unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
869 #[stable(feature = "box_from_cow", since = "1.45.0")]
870 impl From<Cow<'_, CStr>> for Box<CStr> {
872 fn from(cow: Cow<'_, CStr>) -> Box<CStr> {
874 Cow::Borrowed(s) => Box::from(s),
875 Cow::Owned(s) => Box::from(s),
880 #[stable(feature = "c_string_from_box", since = "1.18.0")]
881 impl From<Box<CStr>> for CString {
882 /// Converts a <code>[Box]<[CStr]></code> into a [`CString`] without copying or allocating.
884 fn from(s: Box<CStr>) -> CString {
889 #[stable(feature = "cstring_from_vec_of_nonzerou8", since = "1.43.0")]
890 impl From<Vec<NonZeroU8>> for CString {
891 /// Converts a <code>[Vec]<[NonZeroU8]></code> into a [`CString`] without
892 /// copying nor checking for inner null bytes.
894 fn from(v: Vec<NonZeroU8>) -> CString {
896 // Transmute `Vec<NonZeroU8>` to `Vec<u8>`.
899 // - transmuting between `NonZeroU8` and `u8` is sound;
900 // - `alloc::Layout<NonZeroU8> == alloc::Layout<u8>`.
901 let (ptr, len, cap): (*mut NonZeroU8, _, _) = Vec::into_raw_parts(v);
902 Vec::from_raw_parts(ptr.cast::<u8>(), len, cap)
904 // SAFETY: `v` cannot contain null bytes, given the type-level
905 // invariant of `NonZeroU8`.
906 CString::from_vec_unchecked(v)
911 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
912 impl Clone for Box<CStr> {
914 fn clone(&self) -> Self {
919 #[stable(feature = "box_from_c_string", since = "1.20.0")]
920 impl From<CString> for Box<CStr> {
921 /// Converts a [`CString`] into a <code>[Box]<[CStr]></code> without copying or allocating.
923 fn from(s: CString) -> Box<CStr> {
928 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
929 impl<'a> From<CString> for Cow<'a, CStr> {
930 /// Converts a [`CString`] into an owned [`Cow`] without copying or allocating.
932 fn from(s: CString) -> Cow<'a, CStr> {
937 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
938 impl<'a> From<&'a CStr> for Cow<'a, CStr> {
939 /// Converts a [`CStr`] into a borrowed [`Cow`] without copying or allocating.
941 fn from(s: &'a CStr) -> Cow<'a, CStr> {
946 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
947 impl<'a> From<&'a CString> for Cow<'a, CStr> {
948 /// Converts a `&`[`CString`] into a borrowed [`Cow`] without copying or allocating.
950 fn from(s: &'a CString) -> Cow<'a, CStr> {
951 Cow::Borrowed(s.as_c_str())
955 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
956 impl From<CString> for Arc<CStr> {
957 /// Converts a [`CString`] into an <code>[Arc]<[CStr]></code> without copying or allocating.
959 fn from(s: CString) -> Arc<CStr> {
960 let arc: Arc<[u8]> = Arc::from(s.into_inner());
961 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
965 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
966 impl From<&CStr> for Arc<CStr> {
968 fn from(s: &CStr) -> Arc<CStr> {
969 let arc: Arc<[u8]> = Arc::from(s.to_bytes_with_nul());
970 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
974 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
975 impl From<CString> for Rc<CStr> {
976 /// Converts a [`CString`] into an <code>[Rc]<[CStr]></code> without copying or allocating.
978 fn from(s: CString) -> Rc<CStr> {
979 let rc: Rc<[u8]> = Rc::from(s.into_inner());
980 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
984 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
985 impl From<&CStr> for Rc<CStr> {
987 fn from(s: &CStr) -> Rc<CStr> {
988 let rc: Rc<[u8]> = Rc::from(s.to_bytes_with_nul());
989 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
993 #[stable(feature = "default_box_extra", since = "1.17.0")]
994 impl Default for Box<CStr> {
995 fn default() -> Box<CStr> {
996 let boxed: Box<[u8]> = Box::from([0]);
997 unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
1002 /// Returns the position of the nul byte in the slice that caused
1003 /// [`CString::new`] to fail.
1008 /// use std::ffi::CString;
1010 /// let nul_error = CString::new("foo\0bar").unwrap_err();
1011 /// assert_eq!(nul_error.nul_position(), 3);
1013 /// let nul_error = CString::new("foo bar\0").unwrap_err();
1014 /// assert_eq!(nul_error.nul_position(), 7);
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 pub fn nul_position(&self) -> usize {
1021 /// Consumes this error, returning the underlying vector of bytes which
1022 /// generated the error in the first place.
1027 /// use std::ffi::CString;
1029 /// let nul_error = CString::new("foo\0bar").unwrap_err();
1030 /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
1032 #[must_use = "`self` will be dropped if the result is not used"]
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 pub fn into_vec(self) -> Vec<u8> {
1039 #[stable(feature = "rust1", since = "1.0.0")]
1040 impl Error for NulError {
1041 #[allow(deprecated)]
1042 fn description(&self) -> &str {
1043 "nul byte found in data"
1047 #[stable(feature = "rust1", since = "1.0.0")]
1048 impl fmt::Display for NulError {
1049 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1050 write!(f, "nul byte found in provided data at position: {}", self.0)
1054 #[stable(feature = "rust1", since = "1.0.0")]
1055 impl From<NulError> for io::Error {
1056 /// Converts a [`NulError`] into a [`io::Error`].
1057 fn from(_: NulError) -> io::Error {
1058 io::Error::new_const(io::ErrorKind::InvalidInput, &"data provided contains a nul byte")
1062 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
1063 impl Error for FromBytesWithNulError {
1064 #[allow(deprecated)]
1065 fn description(&self) -> &str {
1067 FromBytesWithNulErrorKind::InteriorNul(..) => {
1068 "data provided contains an interior nul byte"
1070 FromBytesWithNulErrorKind::NotNulTerminated => "data provided is not nul terminated",
1075 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
1076 impl fmt::Display for FromBytesWithNulError {
1077 #[allow(deprecated, deprecated_in_future)]
1078 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1079 f.write_str(self.description())?;
1080 if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind {
1081 write!(f, " at byte pos {}", pos)?;
1087 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
1088 impl Error for FromVecWithNulError {}
1090 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
1091 impl fmt::Display for FromVecWithNulError {
1092 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1093 match self.error_kind {
1094 FromBytesWithNulErrorKind::InteriorNul(pos) => {
1095 write!(f, "data provided contains an interior nul byte at pos {}", pos)
1097 FromBytesWithNulErrorKind::NotNulTerminated => {
1098 write!(f, "data provided is not nul terminated")
1104 impl IntoStringError {
1105 /// Consumes this error, returning original [`CString`] which generated the
1107 #[must_use = "`self` will be dropped if the result is not used"]
1108 #[stable(feature = "cstring_into", since = "1.7.0")]
1109 pub fn into_cstring(self) -> CString {
1113 /// Access the underlying UTF-8 error that was the cause of this error.
1114 #[stable(feature = "cstring_into", since = "1.7.0")]
1115 pub fn utf8_error(&self) -> Utf8Error {
1120 #[stable(feature = "cstring_into", since = "1.7.0")]
1121 impl Error for IntoStringError {
1122 #[allow(deprecated)]
1123 fn description(&self) -> &str {
1124 "C string contained non-utf8 bytes"
1127 fn source(&self) -> Option<&(dyn Error + 'static)> {
1132 #[stable(feature = "cstring_into", since = "1.7.0")]
1133 impl fmt::Display for IntoStringError {
1134 #[allow(deprecated, deprecated_in_future)]
1135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1136 self.description().fmt(f)
1141 /// Wraps a raw C string with a safe C string wrapper.
1143 /// This function will wrap the provided `ptr` with a `CStr` wrapper, which
1144 /// allows inspection and interoperation of non-owned C strings. The total
1145 /// size of the raw C string must be smaller than `isize::MAX` **bytes**
1146 /// in memory due to calling the `slice::from_raw_parts` function.
1147 /// This method is unsafe for a number of reasons:
1149 /// * There is no guarantee to the validity of `ptr`.
1150 /// * The returned lifetime is not guaranteed to be the actual lifetime of
1152 /// * There is no guarantee that the memory pointed to by `ptr` contains a
1153 /// valid nul terminator byte at the end of the string.
1154 /// * It is not guaranteed that the memory pointed by `ptr` won't change
1155 /// before the `CStr` has been destroyed.
1157 /// > **Note**: This operation is intended to be a 0-cost cast but it is
1158 /// > currently implemented with an up-front calculation of the length of
1159 /// > the string. This is not guaranteed to always be the case.
1163 /// ```ignore (extern-declaration)
1165 /// use std::ffi::CStr;
1166 /// use std::os::raw::c_char;
1169 /// fn my_string() -> *const c_char;
1173 /// let slice = CStr::from_ptr(my_string());
1174 /// println!("string returned: {}", slice.to_str().unwrap());
1179 #[stable(feature = "rust1", since = "1.0.0")]
1180 pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
1181 // SAFETY: The caller has provided a pointer that points to a valid C
1182 // string with a NUL terminator of size less than `isize::MAX`, whose
1183 // content remain valid and doesn't change for the lifetime of the
1186 // Thus computing the length is fine (a NUL byte exists), the call to
1187 // from_raw_parts is safe because we know the length is at most `isize::MAX`, meaning
1188 // the call to `from_bytes_with_nul_unchecked` is correct.
1190 // The cast from c_char to u8 is ok because a c_char is always one byte.
1192 let len = sys::strlen(ptr);
1193 let ptr = ptr as *const u8;
1194 CStr::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr, len as usize + 1))
1198 /// Creates a C string wrapper from a byte slice.
1200 /// This function will cast the provided `bytes` to a `CStr`
1201 /// wrapper after ensuring that the byte slice is nul-terminated
1202 /// and does not contain any interior nul bytes.
1207 /// use std::ffi::CStr;
1209 /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
1210 /// assert!(cstr.is_ok());
1213 /// Creating a `CStr` without a trailing nul terminator is an error:
1216 /// use std::ffi::CStr;
1218 /// let cstr = CStr::from_bytes_with_nul(b"hello");
1219 /// assert!(cstr.is_err());
1222 /// Creating a `CStr` with an interior nul byte is an error:
1225 /// use std::ffi::CStr;
1227 /// let cstr = CStr::from_bytes_with_nul(b"he\0llo\0");
1228 /// assert!(cstr.is_err());
1230 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
1231 pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError> {
1232 let nul_pos = memchr::memchr(0, bytes);
1233 if let Some(nul_pos) = nul_pos {
1234 if nul_pos + 1 != bytes.len() {
1235 return Err(FromBytesWithNulError::interior_nul(nul_pos));
1237 Ok(unsafe { CStr::from_bytes_with_nul_unchecked(bytes) })
1239 Err(FromBytesWithNulError::not_nul_terminated())
1243 /// Unsafely creates a C string wrapper from a byte slice.
1245 /// This function will cast the provided `bytes` to a `CStr` wrapper without
1246 /// performing any sanity checks. The provided slice **must** be nul-terminated
1247 /// and not contain any interior nul bytes.
1252 /// use std::ffi::{CStr, CString};
1255 /// let cstring = CString::new("hello").expect("CString::new failed");
1256 /// let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
1257 /// assert_eq!(cstr, &*cstring);
1262 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
1263 #[rustc_const_unstable(feature = "const_cstr_unchecked", issue = "none")]
1264 pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
1265 // SAFETY: Casting to CStr is safe because its internal representation
1266 // is a [u8] too (safe only inside std).
1267 // Dereferencing the obtained pointer is safe because it comes from a
1268 // reference. Making a reference is then safe because its lifetime
1269 // is bound by the lifetime of the given `bytes`.
1270 unsafe { &*(bytes as *const [u8] as *const CStr) }
1273 /// Returns the inner pointer to this C string.
1275 /// The returned pointer will be valid for as long as `self` is, and points
1276 /// to a contiguous region of memory terminated with a 0 byte to represent
1277 /// the end of the string.
1281 /// The returned pointer is read-only; writing to it (including passing it
1282 /// to C code that writes to it) causes undefined behavior.
1284 /// It is your responsibility to make sure that the underlying memory is not
1285 /// freed too early. For example, the following code will cause undefined
1286 /// behavior when `ptr` is used inside the `unsafe` block:
1289 /// # #![allow(unused_must_use)] #![allow(temporary_cstring_as_ptr)]
1290 /// use std::ffi::CString;
1292 /// let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
1294 /// // `ptr` is dangling
1299 /// This happens because the pointer returned by `as_ptr` does not carry any
1300 /// lifetime information and the [`CString`] is deallocated immediately after
1301 /// the `CString::new("Hello").expect("CString::new failed").as_ptr()`
1302 /// expression is evaluated.
1303 /// To fix the problem, bind the `CString` to a local variable:
1306 /// # #![allow(unused_must_use)]
1307 /// use std::ffi::CString;
1309 /// let hello = CString::new("Hello").expect("CString::new failed");
1310 /// let ptr = hello.as_ptr();
1312 /// // `ptr` is valid because `hello` is in scope
1317 /// This way, the lifetime of the [`CString`] in `hello` encompasses
1318 /// the lifetime of `ptr` and the `unsafe` block.
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 #[rustc_const_stable(feature = "const_str_as_ptr", since = "1.32.0")]
1323 pub const fn as_ptr(&self) -> *const c_char {
1327 /// Converts this C string to a byte slice.
1329 /// The returned slice will **not** contain the trailing nul terminator that this C
1332 /// > **Note**: This method is currently implemented as a constant-time
1333 /// > cast, but it is planned to alter its definition in the future to
1334 /// > perform the length calculation whenever this method is called.
1339 /// use std::ffi::CStr;
1341 /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1342 /// assert_eq!(cstr.to_bytes(), b"foo");
1345 #[must_use = "this returns the result of the operation, \
1346 without modifying the original"]
1347 #[stable(feature = "rust1", since = "1.0.0")]
1348 pub fn to_bytes(&self) -> &[u8] {
1349 let bytes = self.to_bytes_with_nul();
1350 // SAFETY: to_bytes_with_nul returns slice with length at least 1
1351 unsafe { bytes.get_unchecked(..bytes.len() - 1) }
1354 /// Converts this C string to a byte slice containing the trailing 0 byte.
1356 /// This function is the equivalent of [`CStr::to_bytes`] except that it
1357 /// will retain the trailing nul terminator instead of chopping it off.
1359 /// > **Note**: This method is currently implemented as a 0-cost cast, but
1360 /// > it is planned to alter its definition in the future to perform the
1361 /// > length calculation whenever this method is called.
1366 /// use std::ffi::CStr;
1368 /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1369 /// assert_eq!(cstr.to_bytes_with_nul(), b"foo\0");
1372 #[must_use = "this returns the result of the operation, \
1373 without modifying the original"]
1374 #[stable(feature = "rust1", since = "1.0.0")]
1375 pub fn to_bytes_with_nul(&self) -> &[u8] {
1376 unsafe { &*(&self.inner as *const [c_char] as *const [u8]) }
1379 /// Yields a <code>&[str]</code> slice if the `CStr` contains valid UTF-8.
1381 /// If the contents of the `CStr` are valid UTF-8 data, this
1382 /// function will return the corresponding <code>&[str]</code> slice. Otherwise,
1383 /// it will return an error with details of where UTF-8 validation failed.
1385 /// [str]: prim@str "str"
1390 /// use std::ffi::CStr;
1392 /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1393 /// assert_eq!(cstr.to_str(), Ok("foo"));
1395 #[stable(feature = "cstr_to_str", since = "1.4.0")]
1396 pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
1397 // N.B., when `CStr` is changed to perform the length check in `.to_bytes()`
1398 // instead of in `from_ptr()`, it may be worth considering if this should
1399 // be rewritten to do the UTF-8 check inline with the length calculation
1400 // instead of doing it afterwards.
1401 str::from_utf8(self.to_bytes())
1404 /// Converts a `CStr` into a <code>[Cow]<[str]></code>.
1406 /// If the contents of the `CStr` are valid UTF-8 data, this
1407 /// function will return a <code>[Cow]::[Borrowed]\(&[str])</code>
1408 /// with the corresponding <code>&[str]</code> slice. Otherwise, it will
1409 /// replace any invalid UTF-8 sequences with
1410 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD] and return a
1411 /// <code>[Cow]::[Owned]\(&[str])</code> with the result.
1413 /// [str]: prim@str "str"
1414 /// [Borrowed]: Cow::Borrowed
1415 /// [Owned]: Cow::Owned
1416 /// [U+FFFD]: crate::char::REPLACEMENT_CHARACTER "std::char::REPLACEMENT_CHARACTER"
1420 /// Calling `to_string_lossy` on a `CStr` containing valid UTF-8:
1423 /// use std::borrow::Cow;
1424 /// use std::ffi::CStr;
1426 /// let cstr = CStr::from_bytes_with_nul(b"Hello World\0")
1427 /// .expect("CStr::from_bytes_with_nul failed");
1428 /// assert_eq!(cstr.to_string_lossy(), Cow::Borrowed("Hello World"));
1431 /// Calling `to_string_lossy` on a `CStr` containing invalid UTF-8:
1434 /// use std::borrow::Cow;
1435 /// use std::ffi::CStr;
1437 /// let cstr = CStr::from_bytes_with_nul(b"Hello \xF0\x90\x80World\0")
1438 /// .expect("CStr::from_bytes_with_nul failed");
1440 /// cstr.to_string_lossy(),
1441 /// Cow::Owned(String::from("Hello �World")) as Cow<'_, str>
1444 #[must_use = "this returns the result of the operation, \
1445 without modifying the original"]
1446 #[stable(feature = "cstr_to_str", since = "1.4.0")]
1447 pub fn to_string_lossy(&self) -> Cow<'_, str> {
1448 String::from_utf8_lossy(self.to_bytes())
1451 /// Converts a <code>[Box]<[CStr]></code> into a [`CString`] without copying or allocating.
1456 /// use std::ffi::CString;
1458 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
1459 /// let boxed = c_string.into_boxed_c_str();
1460 /// assert_eq!(boxed.into_c_string(), CString::new("foo").expect("CString::new failed"));
1462 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
1463 pub fn into_c_string(self: Box<CStr>) -> CString {
1464 let raw = Box::into_raw(self) as *mut [u8];
1465 CString { inner: unsafe { Box::from_raw(raw) } }
1469 #[stable(feature = "rust1", since = "1.0.0")]
1470 impl PartialEq for CStr {
1471 fn eq(&self, other: &CStr) -> bool {
1472 self.to_bytes().eq(other.to_bytes())
1475 #[stable(feature = "rust1", since = "1.0.0")]
1477 #[stable(feature = "rust1", since = "1.0.0")]
1478 impl PartialOrd for CStr {
1479 fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
1480 self.to_bytes().partial_cmp(&other.to_bytes())
1483 #[stable(feature = "rust1", since = "1.0.0")]
1485 fn cmp(&self, other: &CStr) -> Ordering {
1486 self.to_bytes().cmp(&other.to_bytes())
1490 #[stable(feature = "cstr_borrow", since = "1.3.0")]
1491 impl ToOwned for CStr {
1492 type Owned = CString;
1494 fn to_owned(&self) -> CString {
1495 CString { inner: self.to_bytes_with_nul().into() }
1498 fn clone_into(&self, target: &mut CString) {
1499 let mut b = Vec::from(mem::take(&mut target.inner));
1500 self.to_bytes_with_nul().clone_into(&mut b);
1501 target.inner = b.into_boxed_slice();
1505 #[stable(feature = "cstring_asref", since = "1.7.0")]
1506 impl From<&CStr> for CString {
1507 fn from(s: &CStr) -> CString {
1512 #[stable(feature = "cstring_asref", since = "1.7.0")]
1513 impl ops::Index<ops::RangeFull> for CString {
1517 fn index(&self, _index: ops::RangeFull) -> &CStr {
1522 #[stable(feature = "cstr_range_from", since = "1.47.0")]
1523 impl ops::Index<ops::RangeFrom<usize>> for CStr {
1526 fn index(&self, index: ops::RangeFrom<usize>) -> &CStr {
1527 let bytes = self.to_bytes_with_nul();
1528 // we need to manually check the starting index to account for the null
1529 // byte, since otherwise we could get an empty string that doesn't end
1531 if index.start < bytes.len() {
1532 unsafe { CStr::from_bytes_with_nul_unchecked(&bytes[index.start..]) }
1535 "index out of bounds: the len is {} but the index is {}",
1543 #[stable(feature = "cstring_asref", since = "1.7.0")]
1544 impl AsRef<CStr> for CStr {
1546 fn as_ref(&self) -> &CStr {
1551 #[stable(feature = "cstring_asref", since = "1.7.0")]
1552 impl AsRef<CStr> for CString {
1554 fn as_ref(&self) -> &CStr {