2 use borrow::{Cow, Borrow};
5 use fmt::{self, Write};
14 use str::{self, Utf8Error};
18 /// A type representing an owned, C-compatible, nul-terminated string with no nul bytes in the
21 /// This type serves the purpose of being able to safely generate a
22 /// C-compatible string from a Rust byte slice or vector. An instance of this
23 /// type is a static guarantee that the underlying bytes contain no interior 0
24 /// bytes ("nul characters") and that the final byte is 0 ("nul terminator").
26 /// `CString` is to [`&CStr`] as [`String`] is to [`&str`]: the former
27 /// in each pair are owned strings; the latter are borrowed
30 /// # Creating a `CString`
32 /// A `CString` is created from either a byte slice or a byte vector,
33 /// or anything that implements [`Into`]`<`[`Vec`]`<`[`u8`]`>>` (for
34 /// example, you can build a `CString` straight out of a [`String`] or
35 /// a [`&str`], since both implement that trait).
37 /// The [`new`] method will actually check that the provided `&[u8]`
38 /// does not have 0 bytes in the middle, and return an error if it
41 /// # Extracting a raw pointer to the whole C string
43 /// `CString` implements a [`as_ptr`] method through the [`Deref`]
44 /// trait. This method will give you a `*const c_char` which you can
45 /// feed directly to extern functions that expect a nul-terminated
46 /// string, like C's `strdup()`.
48 /// # Extracting a slice of the whole C string
50 /// Alternatively, you can obtain a `&[`[`u8`]`]` slice from a
51 /// `CString` with the [`as_bytes`] method. Slices produced in this
52 /// way do *not* contain the trailing nul terminator. This is useful
53 /// when you will be calling an extern function that takes a `*const
54 /// u8` argument which is not necessarily nul-terminated, plus another
55 /// argument with the length of the string — like C's `strndup()`.
56 /// You can of course get the slice's length with its
57 /// [`len`][slice.len] method.
59 /// If you need a `&[`[`u8`]`]` slice *with* the nul terminator, you
60 /// can use [`as_bytes_with_nul`] instead.
62 /// Once you have the kind of slice you need (with or without a nul
63 /// terminator), you can call the slice's own
64 /// [`as_ptr`][slice.as_ptr] method to get a raw pointer to pass to
65 /// extern functions. See the documentation for that function for a
66 /// discussion on ensuring the lifetime of the raw pointer.
68 /// [`Into`]: ../convert/trait.Into.html
69 /// [`Vec`]: ../vec/struct.Vec.html
70 /// [`String`]: ../string/struct.String.html
71 /// [`&str`]: ../primitive.str.html
72 /// [`u8`]: ../primitive.u8.html
73 /// [`new`]: #method.new
74 /// [`as_bytes`]: #method.as_bytes
75 /// [`as_bytes_with_nul`]: #method.as_bytes_with_nul
76 /// [`as_ptr`]: #method.as_ptr
77 /// [slice.as_ptr]: ../primitive.slice.html#method.as_ptr
78 /// [slice.len]: ../primitive.slice.html#method.len
79 /// [`Deref`]: ../ops/trait.Deref.html
80 /// [`CStr`]: struct.CStr.html
81 /// [`&CStr`]: struct.CStr.html
85 /// ```ignore (extern-declaration)
87 /// use std::ffi::CString;
88 /// use std::os::raw::c_char;
91 /// fn my_printer(s: *const c_char);
94 /// // We are certain that our string doesn't have 0 bytes in the middle,
95 /// // so we can .expect()
96 /// let c_to_print = CString::new("Hello, world!").expect("CString::new failed");
98 /// my_printer(c_to_print.as_ptr());
105 /// `CString` is intended for working with traditional C-style strings
106 /// (a sequence of non-nul bytes terminated by a single nul byte); the
107 /// primary use case for these kinds of strings is interoperating with C-like
108 /// code. Often you will need to transfer ownership to/from that external
109 /// code. It is strongly recommended that you thoroughly read through the
110 /// documentation of `CString` before use, as improper ownership management
111 /// of `CString` instances can lead to invalid memory accesses, memory leaks,
112 /// and other memory errors.
114 #[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
115 #[stable(feature = "rust1", since = "1.0.0")]
117 // Invariant 1: the slice ends with a zero byte and has a length of at least one.
118 // Invariant 2: the slice contains only one zero byte.
119 // Improper usage of unsafe function can break Invariant 2, but not Invariant 1.
123 /// Representation of a borrowed C string.
125 /// This type represents a borrowed reference to a nul-terminated
126 /// array of bytes. It can be constructed safely from a `&[`[`u8`]`]`
127 /// slice, or unsafely from a raw `*const c_char`. It can then be
128 /// converted to a Rust [`&str`] by performing UTF-8 validation, or
129 /// into an owned [`CString`].
131 /// `&CStr` is to [`CString`] as [`&str`] is to [`String`]: the former
132 /// in each pair are borrowed references; the latter are owned
135 /// Note that this structure is **not** `repr(C)` and is not recommended to be
136 /// placed in the signatures of FFI functions. Instead, safe wrappers of FFI
137 /// functions may leverage the unsafe [`from_ptr`] constructor to provide a safe
138 /// interface to other consumers.
142 /// Inspecting a foreign C string:
144 /// ```ignore (extern-declaration)
145 /// use std::ffi::CStr;
146 /// use std::os::raw::c_char;
148 /// extern { fn my_string() -> *const c_char; }
151 /// let slice = CStr::from_ptr(my_string());
152 /// println!("string buffer size without nul terminator: {}", slice.to_bytes().len());
156 /// Passing a Rust-originating C string:
158 /// ```ignore (extern-declaration)
159 /// use std::ffi::{CString, CStr};
160 /// use std::os::raw::c_char;
162 /// fn work(data: &CStr) {
163 /// extern { fn work_with(data: *const c_char); }
165 /// unsafe { work_with(data.as_ptr()) }
168 /// let s = CString::new("data data data data").expect("CString::new failed");
172 /// Converting a foreign C string into a Rust [`String`]:
174 /// ```ignore (extern-declaration)
175 /// use std::ffi::CStr;
176 /// use std::os::raw::c_char;
178 /// extern { fn my_string() -> *const c_char; }
180 /// fn my_string_safe() -> String {
182 /// CStr::from_ptr(my_string()).to_string_lossy().into_owned()
186 /// println!("string: {}", my_string_safe());
189 /// [`u8`]: ../primitive.u8.html
190 /// [`&str`]: ../primitive.str.html
191 /// [`String`]: ../string/struct.String.html
192 /// [`CString`]: struct.CString.html
193 /// [`from_ptr`]: #method.from_ptr
195 #[stable(feature = "rust1", since = "1.0.0")]
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.
212 /// [`CString`]: struct.CString.html
213 /// [`CString::new`]: struct.CString.html#method.new
218 /// use std::ffi::{CString, NulError};
220 /// let _: NulError = CString::new(b"f\0oo".to_vec()).unwrap_err();
222 #[derive(Clone, PartialEq, Eq, Debug)]
223 #[stable(feature = "rust1", since = "1.0.0")]
224 pub struct NulError(usize, Vec<u8>);
226 /// An error indicating that a nul byte was not in the expected position.
228 /// The slice used to create a [`CStr`] must have one and only one nul
229 /// byte at the end of the slice.
231 /// This error is created by the
232 /// [`from_bytes_with_nul`][`CStr::from_bytes_with_nul`] method on
233 /// [`CStr`]. See its documentation for more.
235 /// [`CStr`]: struct.CStr.html
236 /// [`CStr::from_bytes_with_nul`]: struct.CStr.html#method.from_bytes_with_nul
241 /// use std::ffi::{CStr, FromBytesWithNulError};
243 /// let _: FromBytesWithNulError = CStr::from_bytes_with_nul(b"f\0oo").unwrap_err();
245 #[derive(Clone, PartialEq, Eq, Debug)]
246 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
247 pub struct FromBytesWithNulError {
248 kind: FromBytesWithNulErrorKind,
251 #[derive(Clone, PartialEq, Eq, Debug)]
252 enum FromBytesWithNulErrorKind {
257 impl FromBytesWithNulError {
258 fn interior_nul(pos: usize) -> FromBytesWithNulError {
259 FromBytesWithNulError {
260 kind: FromBytesWithNulErrorKind::InteriorNul(pos),
263 fn not_nul_terminated() -> FromBytesWithNulError {
264 FromBytesWithNulError {
265 kind: FromBytesWithNulErrorKind::NotNulTerminated,
270 /// An error indicating invalid UTF-8 when converting a [`CString`] into a [`String`].
272 /// `CString` is just a wrapper over a buffer of bytes with a nul
273 /// terminator; [`into_string`][`CString::into_string`] performs UTF-8
274 /// validation on those bytes and may return this error.
276 /// This `struct` is created by the
277 /// [`into_string`][`CString::into_string`] method on [`CString`]. See
278 /// its documentation for more.
280 /// [`String`]: ../string/struct.String.html
281 /// [`CString`]: struct.CString.html
282 /// [`CString::into_string`]: struct.CString.html#method.into_string
283 #[derive(Clone, PartialEq, Eq, Debug)]
284 #[stable(feature = "cstring_into", since = "1.7.0")]
285 pub struct IntoStringError {
291 /// Creates a new C-compatible string from a container of bytes.
293 /// This function will consume the provided data and use the
294 /// underlying bytes to construct a new string, ensuring that
295 /// there is a trailing 0 byte. This trailing 0 byte will be
296 /// appended by this function; the provided data should *not*
297 /// contain any 0 bytes in it.
301 /// ```ignore (extern-declaration)
302 /// use std::ffi::CString;
303 /// use std::os::raw::c_char;
305 /// extern { fn puts(s: *const c_char); }
307 /// let to_print = CString::new("Hello!").expect("CString::new failed");
309 /// puts(to_print.as_ptr());
315 /// This function will return an error if the supplied bytes contain an
316 /// internal 0 byte. The [`NulError`] returned will contain the bytes as well as
317 /// the position of the nul byte.
319 /// [`NulError`]: struct.NulError.html
320 #[stable(feature = "rust1", since = "1.0.0")]
321 pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
325 fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
326 match memchr::memchr(0, &bytes) {
327 Some(i) => Err(NulError(i, bytes)),
328 None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
332 /// Creates a C-compatible string by consuming a byte vector,
333 /// without checking for interior 0 bytes.
335 /// This method is equivalent to [`new`] except that no runtime assertion
336 /// is made that `v` contains no 0 bytes, and it requires an actual
337 /// byte vector, not anything that can be converted to one with Into.
339 /// [`new`]: #method.new
344 /// use std::ffi::CString;
346 /// let raw = b"foo".to_vec();
348 /// let c_string = CString::from_vec_unchecked(raw);
351 #[stable(feature = "rust1", since = "1.0.0")]
352 pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
355 CString { inner: v.into_boxed_slice() }
358 /// Retakes ownership of a `CString` that was transferred to C via [`into_raw`].
360 /// Additionally, the length of the string will be recalculated from the pointer.
364 /// This should only ever be called with a pointer that was earlier
365 /// obtained by calling [`into_raw`] on a `CString`. Other usage (e.g., trying to take
366 /// ownership of a string that was allocated by foreign code) is likely to lead
367 /// to undefined behavior or allocator corruption.
369 /// > **Note:** If you need to borrow a string that was allocated by
370 /// > foreign code, use [`CStr`]. If you need to take ownership of
371 /// > a string that was allocated by foreign code, you will need to
372 /// > make your own provisions for freeing it appropriately, likely
373 /// > with the foreign code's API to do that.
375 /// [`into_raw`]: #method.into_raw
376 /// [`CStr`]: struct.CStr.html
380 /// Creates a `CString`, pass ownership to an `extern` function (via raw pointer), then retake
381 /// ownership with `from_raw`:
383 /// ```ignore (extern-declaration)
384 /// use std::ffi::CString;
385 /// use std::os::raw::c_char;
388 /// fn some_extern_function(s: *mut c_char);
391 /// let c_string = CString::new("Hello!").expect("CString::new failed");
392 /// let raw = c_string.into_raw();
394 /// some_extern_function(raw);
395 /// let c_string = CString::from_raw(raw);
398 #[stable(feature = "cstr_memory", since = "1.4.0")]
399 pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
400 let len = sys::strlen(ptr) + 1; // Including the NUL byte
401 let slice = slice::from_raw_parts_mut(ptr, len as usize);
402 CString { inner: Box::from_raw(slice as *mut [c_char] as *mut [u8]) }
405 /// Consumes the `CString` and transfers ownership of the string to a C caller.
407 /// The pointer which this function returns must be returned to Rust and reconstituted using
408 /// [`from_raw`] to be properly deallocated. Specifically, one
409 /// should *not* use the standard C `free()` function to deallocate
412 /// Failure to call [`from_raw`] will lead to a memory leak.
414 /// [`from_raw`]: #method.from_raw
419 /// use std::ffi::CString;
421 /// let c_string = CString::new("foo").expect("CString::new failed");
423 /// let ptr = c_string.into_raw();
426 /// assert_eq!(b'f', *ptr as u8);
427 /// assert_eq!(b'o', *ptr.offset(1) as u8);
428 /// assert_eq!(b'o', *ptr.offset(2) as u8);
429 /// assert_eq!(b'\0', *ptr.offset(3) as u8);
431 /// // retake pointer to free memory
432 /// let _ = CString::from_raw(ptr);
436 #[stable(feature = "cstr_memory", since = "1.4.0")]
437 pub fn into_raw(self) -> *mut c_char {
438 Box::into_raw(self.into_inner()) as *mut c_char
441 /// Converts the `CString` into a [`String`] if it contains valid UTF-8 data.
443 /// On failure, ownership of the original `CString` is returned.
445 /// [`String`]: ../string/struct.String.html
450 /// use std::ffi::CString;
452 /// let valid_utf8 = vec![b'f', b'o', b'o'];
453 /// let cstring = CString::new(valid_utf8).expect("CString::new failed");
454 /// assert_eq!(cstring.into_string().expect("into_string() call failed"), "foo");
456 /// let invalid_utf8 = vec![b'f', 0xff, b'o', b'o'];
457 /// let cstring = CString::new(invalid_utf8).expect("CString::new failed");
458 /// let err = cstring.into_string().err().expect("into_string().err() failed");
459 /// assert_eq!(err.utf8_error().valid_up_to(), 1);
462 #[stable(feature = "cstring_into", since = "1.7.0")]
463 pub fn into_string(self) -> Result<String, IntoStringError> {
464 String::from_utf8(self.into_bytes())
465 .map_err(|e| IntoStringError {
466 error: e.utf8_error(),
467 inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
471 /// Consumes the `CString` and returns the underlying byte buffer.
473 /// The returned buffer does **not** contain the trailing nul
474 /// terminator, and it is guaranteed to not have any interior nul
480 /// use std::ffi::CString;
482 /// let c_string = CString::new("foo").expect("CString::new failed");
483 /// let bytes = c_string.into_bytes();
484 /// assert_eq!(bytes, vec![b'f', b'o', b'o']);
486 #[stable(feature = "cstring_into", since = "1.7.0")]
487 pub fn into_bytes(self) -> Vec<u8> {
488 let mut vec = self.into_inner().into_vec();
489 let _nul = vec.pop();
490 debug_assert_eq!(_nul, Some(0u8));
494 /// Equivalent to the [`into_bytes`] function except that the returned vector
495 /// includes the trailing nul terminator.
497 /// [`into_bytes`]: #method.into_bytes
502 /// use std::ffi::CString;
504 /// let c_string = CString::new("foo").expect("CString::new failed");
505 /// let bytes = c_string.into_bytes_with_nul();
506 /// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
508 #[stable(feature = "cstring_into", since = "1.7.0")]
509 pub fn into_bytes_with_nul(self) -> Vec<u8> {
510 self.into_inner().into_vec()
513 /// Returns the contents of this `CString` as a slice of bytes.
515 /// The returned slice does **not** contain the trailing nul
516 /// terminator, and it is guaranteed to not have any interior nul
517 /// bytes. If you need the nul terminator, use
518 /// [`as_bytes_with_nul`] instead.
520 /// [`as_bytes_with_nul`]: #method.as_bytes_with_nul
525 /// use std::ffi::CString;
527 /// let c_string = CString::new("foo").expect("CString::new failed");
528 /// let bytes = c_string.as_bytes();
529 /// assert_eq!(bytes, &[b'f', b'o', b'o']);
532 #[stable(feature = "rust1", since = "1.0.0")]
533 pub fn as_bytes(&self) -> &[u8] {
534 &self.inner[..self.inner.len() - 1]
537 /// Equivalent to the [`as_bytes`] function except that the returned slice
538 /// includes the trailing nul terminator.
540 /// [`as_bytes`]: #method.as_bytes
545 /// use std::ffi::CString;
547 /// let c_string = CString::new("foo").expect("CString::new failed");
548 /// let bytes = c_string.as_bytes_with_nul();
549 /// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
552 #[stable(feature = "rust1", since = "1.0.0")]
553 pub fn as_bytes_with_nul(&self) -> &[u8] {
557 /// Extracts a [`CStr`] slice containing the entire string.
559 /// [`CStr`]: struct.CStr.html
564 /// use std::ffi::{CString, CStr};
566 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
567 /// let c_str = c_string.as_c_str();
568 /// assert_eq!(c_str,
569 /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
572 #[stable(feature = "as_c_str", since = "1.20.0")]
573 pub fn as_c_str(&self) -> &CStr {
577 /// Converts this `CString` into a boxed [`CStr`].
579 /// [`CStr`]: struct.CStr.html
584 /// use std::ffi::{CString, CStr};
586 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
587 /// let boxed = c_string.into_boxed_c_str();
588 /// assert_eq!(&*boxed,
589 /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
591 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
592 pub fn into_boxed_c_str(self) -> Box<CStr> {
593 unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) }
596 /// Bypass "move out of struct which implements [`Drop`] trait" restriction.
598 /// [`Drop`]: ../ops/trait.Drop.html
599 fn into_inner(self) -> Box<[u8]> {
601 let result = ptr::read(&self.inner);
608 // Turns this `CString` into an empty string to prevent
609 // memory unsafe code from working by accident. Inline
610 // to prevent LLVM from optimizing it away in debug builds.
611 #[stable(feature = "cstring_drop", since = "1.13.0")]
612 impl Drop for CString {
615 unsafe { *self.inner.get_unchecked_mut(0) = 0; }
619 #[stable(feature = "rust1", since = "1.0.0")]
620 impl ops::Deref for CString {
624 fn deref(&self) -> &CStr {
625 unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl fmt::Debug for CString {
631 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
632 fmt::Debug::fmt(&**self, f)
636 #[stable(feature = "cstring_into", since = "1.7.0")]
637 impl From<CString> for Vec<u8> {
638 /// Converts a [`CString`] into a [`Vec`]`<u8>`.
640 /// The conversion consumes the [`CString`], and removes the terminating NUL byte.
642 /// [`Vec`]: ../vec/struct.Vec.html
643 /// [`CString`]: ../ffi/struct.CString.html
645 fn from(s: CString) -> Vec<u8> {
650 #[stable(feature = "cstr_debug", since = "1.3.0")]
651 impl fmt::Debug for CStr {
652 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
654 for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
655 f.write_char(byte as char)?;
661 #[stable(feature = "cstr_default", since = "1.10.0")]
662 impl Default for &CStr {
663 fn default() -> Self {
664 const SLICE: &[c_char] = &[0];
665 unsafe { CStr::from_ptr(SLICE.as_ptr()) }
669 #[stable(feature = "cstr_default", since = "1.10.0")]
670 impl Default for CString {
671 /// Creates an empty `CString`.
672 fn default() -> CString {
673 let a: &CStr = Default::default();
678 #[stable(feature = "cstr_borrow", since = "1.3.0")]
679 impl Borrow<CStr> for CString {
681 fn borrow(&self) -> &CStr { self }
684 #[stable(feature = "cstring_from_cow_cstr", since = "1.28.0")]
685 impl<'a> From<Cow<'a, CStr>> for CString {
687 fn from(s: Cow<'a, CStr>) -> Self {
692 #[stable(feature = "box_from_c_str", since = "1.17.0")]
693 impl<'a> From<&'a CStr> for Box<CStr> {
694 fn from(s: &'a CStr) -> Box<CStr> {
695 let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul());
696 unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
700 #[stable(feature = "c_string_from_box", since = "1.18.0")]
701 impl From<Box<CStr>> for CString {
702 /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating.
704 /// [`Box`]: ../boxed/struct.Box.html
705 /// [`CString`]: ../ffi/struct.CString.html
707 fn from(s: Box<CStr>) -> CString {
712 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
713 impl Clone for Box<CStr> {
715 fn clone(&self) -> Self {
720 #[stable(feature = "box_from_c_string", since = "1.20.0")]
721 impl From<CString> for Box<CStr> {
722 /// Converts a [`CString`] into a [`Box`]`<CStr>` without copying or allocating.
724 /// [`CString`]: ../ffi/struct.CString.html
725 /// [`Box`]: ../boxed/struct.Box.html
727 fn from(s: CString) -> Box<CStr> {
732 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
733 impl<'a> From<CString> for Cow<'a, CStr> {
735 fn from(s: CString) -> Cow<'a, CStr> {
740 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
741 impl<'a> From<&'a CStr> for Cow<'a, CStr> {
743 fn from(s: &'a CStr) -> Cow<'a, CStr> {
748 #[stable(feature = "cow_from_cstr", since = "1.28.0")]
749 impl<'a> From<&'a CString> for Cow<'a, CStr> {
751 fn from(s: &'a CString) -> Cow<'a, CStr> {
752 Cow::Borrowed(s.as_c_str())
756 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
757 impl From<CString> for Arc<CStr> {
758 /// Converts a [`CString`] into a [`Arc`]`<CStr>` without copying or allocating.
760 /// [`CString`]: ../ffi/struct.CString.html
761 /// [`Arc`]: ../sync/struct.Arc.html
763 fn from(s: CString) -> Arc<CStr> {
764 let arc: Arc<[u8]> = Arc::from(s.into_inner());
765 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
769 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
770 impl<'a> From<&'a CStr> for Arc<CStr> {
772 fn from(s: &CStr) -> Arc<CStr> {
773 let arc: Arc<[u8]> = Arc::from(s.to_bytes_with_nul());
774 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
778 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
779 impl From<CString> for Rc<CStr> {
780 /// Converts a [`CString`] into a [`Rc`]`<CStr>` without copying or allocating.
782 /// [`CString`]: ../ffi/struct.CString.html
783 /// [`Rc`]: ../rc/struct.Rc.html
785 fn from(s: CString) -> Rc<CStr> {
786 let rc: Rc<[u8]> = Rc::from(s.into_inner());
787 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
791 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
792 impl<'a> From<&'a CStr> for Rc<CStr> {
794 fn from(s: &CStr) -> Rc<CStr> {
795 let rc: Rc<[u8]> = Rc::from(s.to_bytes_with_nul());
796 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
800 #[stable(feature = "default_box_extra", since = "1.17.0")]
801 impl Default for Box<CStr> {
802 fn default() -> Box<CStr> {
803 let boxed: Box<[u8]> = Box::from([0]);
804 unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
809 /// Returns the position of the nul byte in the slice that caused
810 /// [`CString::new`] to fail.
812 /// [`CString::new`]: struct.CString.html#method.new
817 /// use std::ffi::CString;
819 /// let nul_error = CString::new("foo\0bar").unwrap_err();
820 /// assert_eq!(nul_error.nul_position(), 3);
822 /// let nul_error = CString::new("foo bar\0").unwrap_err();
823 /// assert_eq!(nul_error.nul_position(), 7);
825 #[stable(feature = "rust1", since = "1.0.0")]
826 pub fn nul_position(&self) -> usize { self.0 }
828 /// Consumes this error, returning the underlying vector of bytes which
829 /// generated the error in the first place.
834 /// use std::ffi::CString;
836 /// let nul_error = CString::new("foo\0bar").unwrap_err();
837 /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
839 #[stable(feature = "rust1", since = "1.0.0")]
840 pub fn into_vec(self) -> Vec<u8> { self.1 }
843 #[stable(feature = "rust1", since = "1.0.0")]
844 impl Error for NulError {
845 fn description(&self) -> &str { "nul byte found in data" }
848 #[stable(feature = "rust1", since = "1.0.0")]
849 impl fmt::Display for NulError {
850 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
851 write!(f, "nul byte found in provided data at position: {}", self.0)
855 #[stable(feature = "rust1", since = "1.0.0")]
856 impl From<NulError> for io::Error {
857 /// Converts a [`NulError`] into a [`io::Error`].
859 /// [`NulError`]: ../ffi/struct.NulError.html
860 /// [`io::Error`]: ../io/struct.Error.html
861 fn from(_: NulError) -> io::Error {
862 io::Error::new(io::ErrorKind::InvalidInput,
863 "data provided contains a nul byte")
867 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
868 impl Error for FromBytesWithNulError {
869 fn description(&self) -> &str {
871 FromBytesWithNulErrorKind::InteriorNul(..) =>
872 "data provided contains an interior nul byte",
873 FromBytesWithNulErrorKind::NotNulTerminated =>
874 "data provided is not nul terminated",
879 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
880 impl fmt::Display for FromBytesWithNulError {
881 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
882 f.write_str(self.description())?;
883 if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind {
884 write!(f, " at byte pos {}", pos)?;
890 impl IntoStringError {
891 /// Consumes this error, returning original [`CString`] which generated the
894 /// [`CString`]: struct.CString.html
895 #[stable(feature = "cstring_into", since = "1.7.0")]
896 pub fn into_cstring(self) -> CString {
900 /// Access the underlying UTF-8 error that was the cause of this error.
901 #[stable(feature = "cstring_into", since = "1.7.0")]
902 pub fn utf8_error(&self) -> Utf8Error {
907 #[stable(feature = "cstring_into", since = "1.7.0")]
908 impl Error for IntoStringError {
909 fn description(&self) -> &str {
910 "C string contained non-utf8 bytes"
913 fn cause(&self) -> Option<&dyn Error> {
918 #[stable(feature = "cstring_into", since = "1.7.0")]
919 impl fmt::Display for IntoStringError {
920 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
921 self.description().fmt(f)
926 /// Wraps a raw C string with a safe C string wrapper.
928 /// This function will wrap the provided `ptr` with a `CStr` wrapper, which
929 /// allows inspection and interoperation of non-owned C strings. This method
930 /// is unsafe for a number of reasons:
932 /// * There is no guarantee to the validity of `ptr`.
933 /// * The returned lifetime is not guaranteed to be the actual lifetime of
935 /// * There is no guarantee that the memory pointed to by `ptr` contains a
936 /// valid nul terminator byte at the end of the string.
937 /// * It is not guaranteed that the memory pointed by `ptr` won't change
938 /// before the `CStr` has been destroyed.
940 /// > **Note**: This operation is intended to be a 0-cost cast but it is
941 /// > currently implemented with an up-front calculation of the length of
942 /// > the string. This is not guaranteed to always be the case.
946 /// ```ignore (extern-declaration)
948 /// use std::ffi::CStr;
949 /// use std::os::raw::c_char;
952 /// fn my_string() -> *const c_char;
956 /// let slice = CStr::from_ptr(my_string());
957 /// println!("string returned: {}", slice.to_str().unwrap());
961 #[stable(feature = "rust1", since = "1.0.0")]
962 pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
963 let len = sys::strlen(ptr);
964 let ptr = ptr as *const u8;
965 CStr::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr, len as usize + 1))
968 /// Creates a C string wrapper from a byte slice.
970 /// This function will cast the provided `bytes` to a `CStr`
971 /// wrapper after ensuring that the byte slice is nul-terminated
972 /// and does not contain any interior nul bytes.
977 /// use std::ffi::CStr;
979 /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
980 /// assert!(cstr.is_ok());
983 /// Creating a `CStr` without a trailing nul terminator is an error:
986 /// use std::ffi::CStr;
988 /// let c_str = CStr::from_bytes_with_nul(b"hello");
989 /// assert!(c_str.is_err());
992 /// Creating a `CStr` with an interior nul byte is an error:
995 /// use std::ffi::CStr;
997 /// let c_str = CStr::from_bytes_with_nul(b"he\0llo\0");
998 /// assert!(c_str.is_err());
1000 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
1001 pub fn from_bytes_with_nul(bytes: &[u8])
1002 -> Result<&CStr, FromBytesWithNulError> {
1003 let nul_pos = memchr::memchr(0, bytes);
1004 if let Some(nul_pos) = nul_pos {
1005 if nul_pos + 1 != bytes.len() {
1006 return Err(FromBytesWithNulError::interior_nul(nul_pos));
1008 Ok(unsafe { CStr::from_bytes_with_nul_unchecked(bytes) })
1010 Err(FromBytesWithNulError::not_nul_terminated())
1014 /// Unsafely creates a C string wrapper from a byte slice.
1016 /// This function will cast the provided `bytes` to a `CStr` wrapper without
1017 /// performing any sanity checks. The provided slice **must** be nul-terminated
1018 /// and not contain any interior nul bytes.
1023 /// use std::ffi::{CStr, CString};
1026 /// let cstring = CString::new("hello").expect("CString::new failed");
1027 /// let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
1028 /// assert_eq!(cstr, &*cstring);
1032 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
1033 #[rustc_const_unstable(feature = "const_cstr_unchecked")]
1034 pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
1035 &*(bytes as *const [u8] as *const CStr)
1038 /// Returns the inner pointer to this C string.
1040 /// The returned pointer will be valid for as long as `self` is, and points
1041 /// to a contiguous region of memory terminated with a 0 byte to represent
1042 /// the end of the string.
1046 /// It is your responsibility to make sure that the underlying memory is not
1047 /// freed too early. For example, the following code will cause undefined
1048 /// behavior when `ptr` is used inside the `unsafe` block:
1051 /// # #![allow(unused_must_use)]
1052 /// use std::ffi::{CString};
1054 /// let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
1056 /// // `ptr` is dangling
1061 /// This happens because the pointer returned by `as_ptr` does not carry any
1062 /// lifetime information and the [`CString`] is deallocated immediately after
1063 /// the `CString::new("Hello").expect("CString::new failed").as_ptr()` expression is evaluated.
1064 /// To fix the problem, bind the `CString` to a local variable:
1067 /// # #![allow(unused_must_use)]
1068 /// use std::ffi::{CString};
1070 /// let hello = CString::new("Hello").expect("CString::new failed");
1071 /// let ptr = hello.as_ptr();
1073 /// // `ptr` is valid because `hello` is in scope
1078 /// This way, the lifetime of the `CString` in `hello` encompasses
1079 /// the lifetime of `ptr` and the `unsafe` block.
1081 /// [`CString`]: struct.CString.html
1083 #[stable(feature = "rust1", since = "1.0.0")]
1084 pub const fn as_ptr(&self) -> *const c_char {
1088 /// Converts this C string to a byte slice.
1090 /// The returned slice will **not** contain the trailing nul terminator that this C
1093 /// > **Note**: This method is currently implemented as a constant-time
1094 /// > cast, but it is planned to alter its definition in the future to
1095 /// > perform the length calculation whenever this method is called.
1100 /// use std::ffi::CStr;
1102 /// let c_str = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1103 /// assert_eq!(c_str.to_bytes(), b"foo");
1106 #[stable(feature = "rust1", since = "1.0.0")]
1107 pub fn to_bytes(&self) -> &[u8] {
1108 let bytes = self.to_bytes_with_nul();
1109 &bytes[..bytes.len() - 1]
1112 /// Converts this C string to a byte slice containing the trailing 0 byte.
1114 /// This function is the equivalent of [`to_bytes`] except that it will retain
1115 /// the trailing nul terminator instead of chopping it off.
1117 /// > **Note**: This method is currently implemented as a 0-cost cast, but
1118 /// > it is planned to alter its definition in the future to perform the
1119 /// > length calculation whenever this method is called.
1121 /// [`to_bytes`]: #method.to_bytes
1126 /// use std::ffi::CStr;
1128 /// let c_str = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1129 /// assert_eq!(c_str.to_bytes_with_nul(), b"foo\0");
1132 #[stable(feature = "rust1", since = "1.0.0")]
1133 pub fn to_bytes_with_nul(&self) -> &[u8] {
1134 unsafe { &*(&self.inner as *const [c_char] as *const [u8]) }
1137 /// Yields a [`&str`] slice if the `CStr` contains valid UTF-8.
1139 /// If the contents of the `CStr` are valid UTF-8 data, this
1140 /// function will return the corresponding [`&str`] slice. Otherwise,
1141 /// it will return an error with details of where UTF-8 validation failed.
1143 /// > **Note**: This method is currently implemented to check for validity
1144 /// > after a constant-time cast, but it is planned to alter its definition
1145 /// > in the future to perform the length calculation in addition to the
1146 /// > UTF-8 check whenever this method is called.
1148 /// [`&str`]: ../primitive.str.html
1153 /// use std::ffi::CStr;
1155 /// let c_str = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1156 /// assert_eq!(c_str.to_str(), Ok("foo"));
1158 #[stable(feature = "cstr_to_str", since = "1.4.0")]
1159 pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
1160 // N.B., when `CStr` is changed to perform the length check in `.to_bytes()`
1161 // instead of in `from_ptr()`, it may be worth considering if this should
1162 // be rewritten to do the UTF-8 check inline with the length calculation
1163 // instead of doing it afterwards.
1164 str::from_utf8(self.to_bytes())
1167 /// Converts a `CStr` into a [`Cow`]`<`[`str`]`>`.
1169 /// If the contents of the `CStr` are valid UTF-8 data, this
1170 /// function will return a [`Cow`]`::`[`Borrowed`]`(`[`&str`]`)`
1171 /// with the corresponding [`&str`] slice. Otherwise, it will
1172 /// replace any invalid UTF-8 sequences with
1173 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD] and return a
1174 /// [`Cow`]`::`[`Owned`]`(`[`String`]`)` with the result.
1176 /// > **Note**: This method is currently implemented to check for validity
1177 /// > after a constant-time cast, but it is planned to alter its definition
1178 /// > in the future to perform the length calculation in addition to the
1179 /// > UTF-8 check whenever this method is called.
1181 /// [`Cow`]: ../borrow/enum.Cow.html
1182 /// [`Borrowed`]: ../borrow/enum.Cow.html#variant.Borrowed
1183 /// [`Owned`]: ../borrow/enum.Cow.html#variant.Owned
1184 /// [`str`]: ../primitive.str.html
1185 /// [`String`]: ../string/struct.String.html
1186 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
1190 /// Calling `to_string_lossy` on a `CStr` containing valid UTF-8:
1193 /// use std::borrow::Cow;
1194 /// use std::ffi::CStr;
1196 /// let c_str = CStr::from_bytes_with_nul(b"Hello World\0")
1197 /// .expect("CStr::from_bytes_with_nul failed");
1198 /// assert_eq!(c_str.to_string_lossy(), Cow::Borrowed("Hello World"));
1201 /// Calling `to_string_lossy` on a `CStr` containing invalid UTF-8:
1204 /// use std::borrow::Cow;
1205 /// use std::ffi::CStr;
1207 /// let c_str = CStr::from_bytes_with_nul(b"Hello \xF0\x90\x80World\0")
1208 /// .expect("CStr::from_bytes_with_nul failed");
1210 /// c_str.to_string_lossy(),
1211 /// Cow::Owned(String::from("Hello �World")) as Cow<str>
1214 #[stable(feature = "cstr_to_str", since = "1.4.0")]
1215 pub fn to_string_lossy(&self) -> Cow<str> {
1216 String::from_utf8_lossy(self.to_bytes())
1219 /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating.
1221 /// [`Box`]: ../boxed/struct.Box.html
1222 /// [`CString`]: struct.CString.html
1227 /// use std::ffi::CString;
1229 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
1230 /// let boxed = c_string.into_boxed_c_str();
1231 /// assert_eq!(boxed.into_c_string(), CString::new("foo").expect("CString::new failed"));
1233 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
1234 pub fn into_c_string(self: Box<CStr>) -> CString {
1235 let raw = Box::into_raw(self) as *mut [u8];
1236 CString { inner: unsafe { Box::from_raw(raw) } }
1240 #[stable(feature = "rust1", since = "1.0.0")]
1241 impl PartialEq for CStr {
1242 fn eq(&self, other: &CStr) -> bool {
1243 self.to_bytes().eq(other.to_bytes())
1246 #[stable(feature = "rust1", since = "1.0.0")]
1248 #[stable(feature = "rust1", since = "1.0.0")]
1249 impl PartialOrd for CStr {
1250 fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
1251 self.to_bytes().partial_cmp(&other.to_bytes())
1254 #[stable(feature = "rust1", since = "1.0.0")]
1256 fn cmp(&self, other: &CStr) -> Ordering {
1257 self.to_bytes().cmp(&other.to_bytes())
1261 #[stable(feature = "cstr_borrow", since = "1.3.0")]
1262 impl ToOwned for CStr {
1263 type Owned = CString;
1265 fn to_owned(&self) -> CString {
1266 CString { inner: self.to_bytes_with_nul().into() }
1270 #[stable(feature = "cstring_asref", since = "1.7.0")]
1271 impl<'a> From<&'a CStr> for CString {
1272 fn from(s: &'a CStr) -> CString {
1277 #[stable(feature = "cstring_asref", since = "1.7.0")]
1278 impl ops::Index<ops::RangeFull> for CString {
1282 fn index(&self, _index: ops::RangeFull) -> &CStr {
1287 #[stable(feature = "cstring_asref", since = "1.7.0")]
1288 impl AsRef<CStr> for CStr {
1290 fn as_ref(&self) -> &CStr {
1295 #[stable(feature = "cstring_asref", since = "1.7.0")]
1296 impl AsRef<CStr> for CString {
1298 fn as_ref(&self) -> &CStr {
1306 use os::raw::c_char;
1307 use borrow::Cow::{Borrowed, Owned};
1308 use hash::{Hash, Hasher};
1309 use collections::hash_map::DefaultHasher;
1315 let data = b"123\0";
1316 let ptr = data.as_ptr() as *const c_char;
1318 assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
1319 assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
1325 let s = CString::new("1234").unwrap();
1326 assert_eq!(s.as_bytes(), b"1234");
1327 assert_eq!(s.as_bytes_with_nul(), b"1234\0");
1331 fn build_with_zero1() {
1332 assert!(CString::new(&b"\0"[..]).is_err());
1335 fn build_with_zero2() {
1336 assert!(CString::new(vec![0]).is_err());
1340 fn build_with_zero3() {
1342 let s = CString::from_vec_unchecked(vec![0]);
1343 assert_eq!(s.as_bytes(), b"\0");
1349 let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
1350 assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
1356 let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
1357 assert_eq!(s.to_bytes(), b"12");
1358 assert_eq!(s.to_bytes_with_nul(), b"12\0");
1364 let data = b"123\xE2\x80\xA6\0";
1365 let ptr = data.as_ptr() as *const c_char;
1367 assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
1368 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
1370 let data = b"123\xE2\0";
1371 let ptr = data.as_ptr() as *const c_char;
1373 assert!(CStr::from_ptr(ptr).to_str().is_err());
1374 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
1380 let data = b"123\0";
1381 let ptr = data.as_ptr() as *const c_char;
1383 let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
1384 assert_eq!(owned.as_bytes_with_nul(), data);
1389 let data = b"123\xE2\xFA\xA6\0";
1390 let ptr = data.as_ptr() as *const c_char;
1391 let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
1393 let mut s = DefaultHasher::new();
1395 let cstr_hash = s.finish();
1396 let mut s = DefaultHasher::new();
1397 CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
1398 let cstring_hash = s.finish();
1400 assert_eq!(cstr_hash, cstring_hash);
1404 fn from_bytes_with_nul() {
1405 let data = b"123\0";
1406 let cstr = CStr::from_bytes_with_nul(data);
1407 assert_eq!(cstr.map(CStr::to_bytes), Ok(&b"123"[..]));
1408 let cstr = CStr::from_bytes_with_nul(data);
1409 assert_eq!(cstr.map(CStr::to_bytes_with_nul), Ok(&b"123\0"[..]));
1412 let cstr = CStr::from_bytes_with_nul(data);
1413 let cstr_unchecked = CStr::from_bytes_with_nul_unchecked(data);
1414 assert_eq!(cstr, Ok(cstr_unchecked));
1419 fn from_bytes_with_nul_unterminated() {
1421 let cstr = CStr::from_bytes_with_nul(data);
1422 assert!(cstr.is_err());
1426 fn from_bytes_with_nul_interior() {
1427 let data = b"1\023\0";
1428 let cstr = CStr::from_bytes_with_nul(data);
1429 assert!(cstr.is_err());
1434 let orig: &[u8] = b"Hello, world!\0";
1435 let cstr = CStr::from_bytes_with_nul(orig).unwrap();
1436 let boxed: Box<CStr> = Box::from(cstr);
1437 let cstring = cstr.to_owned().into_boxed_c_str().into_c_string();
1438 assert_eq!(cstr, &*boxed);
1439 assert_eq!(&*boxed, &*cstring);
1440 assert_eq!(&*cstring, cstr);
1444 fn boxed_default() {
1445 let boxed = <Box<CStr>>::default();
1446 assert_eq!(boxed.to_bytes_with_nul(), &[0]);
1451 let orig: &[u8] = b"Hello, world!\0";
1452 let cstr = CStr::from_bytes_with_nul(orig).unwrap();
1453 let rc: Rc<CStr> = Rc::from(cstr);
1454 let arc: Arc<CStr> = Arc::from(cstr);
1456 assert_eq!(&*rc, cstr);
1457 assert_eq!(&*arc, cstr);
1459 let rc2: Rc<CStr> = Rc::from(cstr.to_owned());
1460 let arc2: Arc<CStr> = Arc::from(cstr.to_owned());
1462 assert_eq!(&*rc2, cstr);
1463 assert_eq!(&*arc2, cstr);
1467 fn cstr_const_constructor() {
1468 const CSTR: &CStr = unsafe {
1469 CStr::from_bytes_with_nul_unchecked(b"Hello, world!\0")
1472 assert_eq!(CSTR.to_str().unwrap(), "Hello, world!");