1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use borrow::{Cow, Borrow};
15 use fmt::{self, Write};
24 use str::{self, Utf8Error};
26 /// A type representing an owned C-compatible string.
28 /// This type serves the primary purpose of being able to safely generate a
29 /// C-compatible string from a Rust byte slice or vector. An instance of this
30 /// type is a static guarantee that the underlying bytes contain no interior 0
31 /// bytes and the final byte is 0.
33 /// A `CString` is created from either a byte slice or a byte vector. A [`u8`]
34 /// slice can be obtained with the `as_bytes` method. Slices produced from a
35 /// `CString` do *not* contain the trailing nul terminator unless otherwise
38 /// [`u8`]: ../primitive.u8.html
44 /// use std::ffi::CString;
45 /// use std::os::raw::c_char;
48 /// fn my_printer(s: *const c_char);
51 /// let c_to_print = CString::new("Hello, world!").unwrap();
53 /// my_printer(c_to_print.as_ptr());
60 /// `CString` is intended for working with traditional C-style strings
61 /// (a sequence of non-null bytes terminated by a single null byte); the
62 /// primary use case for these kinds of strings is interoperating with C-like
63 /// code. Often you will need to transfer ownership to/from that external
64 /// code. It is strongly recommended that you thoroughly read through the
65 /// documentation of `CString` before use, as improper ownership management
66 /// of `CString` instances can lead to invalid memory accesses, memory leaks,
67 /// and other memory errors.
69 #[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
70 #[stable(feature = "rust1", since = "1.0.0")]
72 // Invariant 1: the slice ends with a zero byte and has a length of at least one.
73 // Invariant 2: the slice contains only one zero byte.
74 // Improper usage of unsafe function can break Invariant 2, but not Invariant 1.
78 /// Representation of a borrowed C string.
80 /// This dynamically sized type is only safely constructed via a borrowed
81 /// version of an instance of `CString`. This type can be constructed from a raw
82 /// C string as well and represents a C string borrowed from another location.
84 /// Note that this structure is **not** `repr(C)` and is not recommended to be
85 /// placed in the signatures of FFI functions. Instead safe wrappers of FFI
86 /// functions may leverage the unsafe [`from_ptr`] constructor to provide a safe
87 /// interface to other consumers.
89 /// [`from_ptr`]: #method.from_ptr
93 /// Inspecting a foreign C string:
96 /// use std::ffi::CStr;
97 /// use std::os::raw::c_char;
99 /// extern { fn my_string() -> *const c_char; }
102 /// let slice = CStr::from_ptr(my_string());
103 /// println!("string length: {}", slice.to_bytes().len());
107 /// Passing a Rust-originating C string:
110 /// use std::ffi::{CString, CStr};
111 /// use std::os::raw::c_char;
113 /// fn work(data: &CStr) {
114 /// extern { fn work_with(data: *const c_char); }
116 /// unsafe { work_with(data.as_ptr()) }
119 /// let s = CString::new("data data data data").unwrap();
123 /// Converting a foreign C string into a Rust [`String`]:
125 /// [`String`]: ../string/struct.String.html
128 /// use std::ffi::CStr;
129 /// use std::os::raw::c_char;
131 /// extern { fn my_string() -> *const c_char; }
133 /// fn my_string_safe() -> String {
135 /// CStr::from_ptr(my_string()).to_string_lossy().into_owned()
139 /// println!("string: {}", my_string_safe());
142 #[stable(feature = "rust1", since = "1.0.0")]
144 // FIXME: this should not be represented with a DST slice but rather with
145 // just a raw `c_char` along with some form of marker to make
146 // this an unsized type. Essentially `sizeof(&CStr)` should be the
147 // same as `sizeof(&c_char)` but `CStr` should be an unsized type.
151 /// An error returned from [`CString::new`] to indicate that a nul byte was found
152 /// in the vector provided.
154 /// [`CString::new`]: struct.CString.html#method.new
155 #[derive(Clone, PartialEq, Eq, Debug)]
156 #[stable(feature = "rust1", since = "1.0.0")]
157 pub struct NulError(usize, Vec<u8>);
159 /// An error returned from [`CStr::from_bytes_with_nul`] to indicate that a nul
160 /// byte was found too early in the slice provided or one wasn't found at all.
162 /// [`CStr::from_bytes_with_nul`]: struct.CStr.html#method.from_bytes_with_nul
163 #[derive(Clone, PartialEq, Eq, Debug)]
164 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
165 pub struct FromBytesWithNulError {
166 kind: FromBytesWithNulErrorKind,
169 #[derive(Clone, PartialEq, Eq, Debug)]
170 enum FromBytesWithNulErrorKind {
175 impl FromBytesWithNulError {
176 fn interior_nul(pos: usize) -> FromBytesWithNulError {
177 FromBytesWithNulError {
178 kind: FromBytesWithNulErrorKind::InteriorNul(pos),
181 fn not_nul_terminated() -> FromBytesWithNulError {
182 FromBytesWithNulError {
183 kind: FromBytesWithNulErrorKind::NotNulTerminated,
188 /// An error returned from [`CString::into_string`] to indicate that a UTF-8 error
189 /// was encountered during the conversion.
191 /// [`CString::into_string`]: struct.CString.html#method.into_string
192 #[derive(Clone, PartialEq, Eq, Debug)]
193 #[stable(feature = "cstring_into", since = "1.7.0")]
194 pub struct IntoStringError {
200 /// Creates a new C-compatible string from a container of bytes.
202 /// This method will consume the provided data and use the underlying bytes
203 /// to construct a new string, ensuring that there is a trailing 0 byte.
208 /// use std::ffi::CString;
209 /// use std::os::raw::c_char;
211 /// extern { fn puts(s: *const c_char); }
213 /// let to_print = CString::new("Hello!").unwrap();
215 /// puts(to_print.as_ptr());
221 /// This function will return an error if the bytes yielded contain an
222 /// internal 0 byte. The error returned will contain the bytes as well as
223 /// the position of the nul byte.
224 #[stable(feature = "rust1", since = "1.0.0")]
225 pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
229 fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
230 match memchr::memchr(0, &bytes) {
231 Some(i) => Err(NulError(i, bytes)),
232 None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
236 /// Creates a C-compatible string from a byte vector without checking for
237 /// interior 0 bytes.
239 /// This method is equivalent to [`new`] except that no runtime assertion
240 /// is made that `v` contains no 0 bytes, and it requires an actual
241 /// byte vector, not anything that can be converted to one with Into.
243 /// [`new`]: #method.new
248 /// use std::ffi::CString;
250 /// let raw = b"foo".to_vec();
252 /// let c_string = CString::from_vec_unchecked(raw);
255 #[stable(feature = "rust1", since = "1.0.0")]
256 pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
259 CString { inner: v.into_boxed_slice() }
262 /// Retakes ownership of a `CString` that was transferred to C.
264 /// Additionally, the length of the string will be recalculated from the pointer.
268 /// This should only ever be called with a pointer that was earlier
269 /// obtained by calling [`into_raw`] on a `CString`. Other usage (e.g. trying to take
270 /// ownership of a string that was allocated by foreign code) is likely to lead
271 /// to undefined behavior or allocator corruption.
273 /// [`into_raw`]: #method.into_raw
274 #[stable(feature = "cstr_memory", since = "1.4.0")]
275 pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
276 let len = libc::strlen(ptr) + 1; // Including the NUL byte
277 let slice = slice::from_raw_parts(ptr, len as usize);
278 CString { inner: mem::transmute(slice) }
281 /// Transfers ownership of the string to a C caller.
283 /// The pointer must be returned to Rust and reconstituted using
284 /// [`from_raw`] to be properly deallocated. Specifically, one
285 /// should *not* use the standard C `free` function to deallocate
288 /// Failure to call [`from_raw`] will lead to a memory leak.
290 /// [`from_raw`]: #method.from_raw
295 /// use std::ffi::CString;
297 /// let c_string = CString::new("foo").unwrap();
299 /// let ptr = c_string.into_raw();
302 /// assert_eq!(b'f', *ptr as u8);
303 /// assert_eq!(b'o', *ptr.offset(1) as u8);
304 /// assert_eq!(b'o', *ptr.offset(2) as u8);
305 /// assert_eq!(b'\0', *ptr.offset(3) as u8);
307 /// // retake pointer to free memory
308 /// let _ = CString::from_raw(ptr);
311 #[stable(feature = "cstr_memory", since = "1.4.0")]
312 pub fn into_raw(self) -> *mut c_char {
313 Box::into_raw(self.into_inner()) as *mut c_char
316 /// Converts the `CString` into a [`String`] if it contains valid Unicode data.
318 /// On failure, ownership of the original `CString` is returned.
320 /// [`String`]: ../string/struct.String.html
321 #[stable(feature = "cstring_into", since = "1.7.0")]
322 pub fn into_string(self) -> Result<String, IntoStringError> {
323 String::from_utf8(self.into_bytes())
324 .map_err(|e| IntoStringError {
325 error: e.utf8_error(),
326 inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
330 /// Returns the underlying byte buffer.
332 /// The returned buffer does **not** contain the trailing nul separator and
333 /// it is guaranteed to not have any interior nul bytes.
338 /// use std::ffi::CString;
340 /// let c_string = CString::new("foo").unwrap();
341 /// let bytes = c_string.into_bytes();
342 /// assert_eq!(bytes, vec![b'f', b'o', b'o']);
344 #[stable(feature = "cstring_into", since = "1.7.0")]
345 pub fn into_bytes(self) -> Vec<u8> {
346 let mut vec = self.into_inner().into_vec();
347 let _nul = vec.pop();
348 debug_assert_eq!(_nul, Some(0u8));
352 /// Equivalent to the [`into_bytes`] function except that the returned vector
353 /// includes the trailing nul byte.
355 /// [`into_bytes`]: #method.into_bytes
360 /// use std::ffi::CString;
362 /// let c_string = CString::new("foo").unwrap();
363 /// let bytes = c_string.into_bytes_with_nul();
364 /// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
366 #[stable(feature = "cstring_into", since = "1.7.0")]
367 pub fn into_bytes_with_nul(self) -> Vec<u8> {
368 self.into_inner().into_vec()
371 /// Returns the contents of this `CString` as a slice of bytes.
373 /// The returned slice does **not** contain the trailing nul separator and
374 /// it is guaranteed to not have any interior nul bytes.
375 #[stable(feature = "rust1", since = "1.0.0")]
376 pub fn as_bytes(&self) -> &[u8] {
377 &self.inner[..self.inner.len() - 1]
380 /// Equivalent to the [`as_bytes`] function except that the returned slice
381 /// includes the trailing nul byte.
383 /// [`as_bytes`]: #method.as_bytes
388 /// use std::ffi::CString;
390 /// let c_string = CString::new("foo").unwrap();
391 /// let bytes = c_string.as_bytes_with_nul();
392 /// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
394 #[stable(feature = "rust1", since = "1.0.0")]
395 pub fn as_bytes_with_nul(&self) -> &[u8] {
399 /// Extracts a [`CStr`] slice containing the entire string.
401 /// [`CStr`]: struct.CStr.html
402 #[unstable(feature = "as_c_str", issue = "40380")]
403 pub fn as_c_str(&self) -> &CStr {
407 /// Converts this `CString` into a boxed [`CStr`].
409 /// [`CStr`]: struct.CStr.html
410 #[unstable(feature = "into_boxed_c_str", issue = "40380")]
411 pub fn into_boxed_c_str(self) -> Box<CStr> {
412 unsafe { mem::transmute(self.into_inner()) }
415 // Bypass "move out of struct which implements [`Drop`] trait" restriction.
417 /// [`Drop`]: ../ops/trait.Drop.html
418 fn into_inner(self) -> Box<[u8]> {
420 let result = ptr::read(&self.inner);
427 // Turns this `CString` into an empty string to prevent
428 // memory unsafe code from working by accident. Inline
429 // to prevent LLVM from optimizing it away in debug builds.
430 #[stable(feature = "cstring_drop", since = "1.13.0")]
431 impl Drop for CString {
434 unsafe { *self.inner.get_unchecked_mut(0) = 0; }
438 #[stable(feature = "rust1", since = "1.0.0")]
439 impl ops::Deref for CString {
442 fn deref(&self) -> &CStr {
443 unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
447 #[stable(feature = "rust1", since = "1.0.0")]
448 impl fmt::Debug for CString {
449 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
450 fmt::Debug::fmt(&**self, f)
454 #[stable(feature = "cstring_into", since = "1.7.0")]
455 impl From<CString> for Vec<u8> {
456 fn from(s: CString) -> Vec<u8> {
461 #[stable(feature = "cstr_debug", since = "1.3.0")]
462 impl fmt::Debug for CStr {
463 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
465 for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
466 f.write_char(byte as char)?;
472 #[stable(feature = "cstr_default", since = "1.10.0")]
473 impl<'a> Default for &'a CStr {
474 fn default() -> &'a CStr {
475 static SLICE: &'static [c_char] = &[0];
476 unsafe { CStr::from_ptr(SLICE.as_ptr()) }
480 #[stable(feature = "cstr_default", since = "1.10.0")]
481 impl Default for CString {
482 /// Creates an empty `CString`.
483 fn default() -> CString {
484 let a: &CStr = Default::default();
489 #[stable(feature = "cstr_borrow", since = "1.3.0")]
490 impl Borrow<CStr> for CString {
491 fn borrow(&self) -> &CStr { self }
494 #[stable(feature = "box_from_c_str", since = "1.17.0")]
495 impl<'a> From<&'a CStr> for Box<CStr> {
496 fn from(s: &'a CStr) -> Box<CStr> {
497 let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul());
498 unsafe { mem::transmute(boxed) }
502 #[stable(feature = "c_string_from_box", since = "1.18.0")]
503 impl From<Box<CStr>> for CString {
504 fn from(s: Box<CStr>) -> CString {
509 #[stable(feature = "box_from_c_string", since = "1.18.0")]
510 impl Into<Box<CStr>> for CString {
511 fn into(self) -> Box<CStr> {
512 self.into_boxed_c_str()
516 #[stable(feature = "default_box_extra", since = "1.17.0")]
517 impl Default for Box<CStr> {
518 fn default() -> Box<CStr> {
519 let boxed: Box<[u8]> = Box::from([0]);
520 unsafe { mem::transmute(boxed) }
525 /// Returns the position of the nul byte in the slice that was provided to
526 /// [`CString::new`].
528 /// [`CString::new`]: struct.CString.html#method.new
533 /// use std::ffi::CString;
535 /// let nul_error = CString::new("foo\0bar").unwrap_err();
536 /// assert_eq!(nul_error.nul_position(), 3);
538 /// let nul_error = CString::new("foo bar\0").unwrap_err();
539 /// assert_eq!(nul_error.nul_position(), 7);
541 #[stable(feature = "rust1", since = "1.0.0")]
542 pub fn nul_position(&self) -> usize { self.0 }
544 /// Consumes this error, returning the underlying vector of bytes which
545 /// generated the error in the first place.
550 /// use std::ffi::CString;
552 /// let nul_error = CString::new("foo\0bar").unwrap_err();
553 /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
555 #[stable(feature = "rust1", since = "1.0.0")]
556 pub fn into_vec(self) -> Vec<u8> { self.1 }
559 #[stable(feature = "rust1", since = "1.0.0")]
560 impl Error for NulError {
561 fn description(&self) -> &str { "nul byte found in data" }
564 #[stable(feature = "rust1", since = "1.0.0")]
565 impl fmt::Display for NulError {
566 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
567 write!(f, "nul byte found in provided data at position: {}", self.0)
571 #[stable(feature = "rust1", since = "1.0.0")]
572 impl From<NulError> for io::Error {
573 fn from(_: NulError) -> io::Error {
574 io::Error::new(io::ErrorKind::InvalidInput,
575 "data provided contains a nul byte")
579 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
580 impl Error for FromBytesWithNulError {
581 fn description(&self) -> &str {
583 FromBytesWithNulErrorKind::InteriorNul(..) =>
584 "data provided contains an interior nul byte",
585 FromBytesWithNulErrorKind::NotNulTerminated =>
586 "data provided is not nul terminated",
591 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
592 impl fmt::Display for FromBytesWithNulError {
593 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
594 f.write_str(self.description())?;
595 if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind {
596 write!(f, " at byte pos {}", pos)?;
602 impl IntoStringError {
603 /// Consumes this error, returning original [`CString`] which generated the
606 /// [`CString`]: struct.CString.html
607 #[stable(feature = "cstring_into", since = "1.7.0")]
608 pub fn into_cstring(self) -> CString {
612 /// Access the underlying UTF-8 error that was the cause of this error.
613 #[stable(feature = "cstring_into", since = "1.7.0")]
614 pub fn utf8_error(&self) -> Utf8Error {
619 #[stable(feature = "cstring_into", since = "1.7.0")]
620 impl Error for IntoStringError {
621 fn description(&self) -> &str {
622 "C string contained non-utf8 bytes"
625 fn cause(&self) -> Option<&Error> {
630 #[stable(feature = "cstring_into", since = "1.7.0")]
631 impl fmt::Display for IntoStringError {
632 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
633 self.description().fmt(f)
638 /// Casts a raw C string to a safe C string wrapper.
640 /// This function will cast the provided `ptr` to the `CStr` wrapper which
641 /// allows inspection and interoperation of non-owned C strings. This method
642 /// is unsafe for a number of reasons:
644 /// * There is no guarantee to the validity of `ptr`.
645 /// * The returned lifetime is not guaranteed to be the actual lifetime of
647 /// * There is no guarantee that the memory pointed to by `ptr` contains a
648 /// valid nul terminator byte at the end of the string.
650 /// > **Note**: This operation is intended to be a 0-cost cast but it is
651 /// > currently implemented with an up-front calculation of the length of
652 /// > the string. This is not guaranteed to always be the case.
658 /// use std::ffi::CStr;
659 /// use std::os::raw::c_char;
662 /// fn my_string() -> *const c_char;
666 /// let slice = CStr::from_ptr(my_string());
667 /// println!("string returned: {}", slice.to_str().unwrap());
671 #[stable(feature = "rust1", since = "1.0.0")]
672 pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
673 let len = libc::strlen(ptr);
674 let ptr = ptr as *const u8;
675 CStr::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr, len as usize + 1))
678 /// Creates a C string wrapper from a byte slice.
680 /// This function will cast the provided `bytes` to a `CStr` wrapper after
681 /// ensuring that it is null terminated and does not contain any interior
687 /// use std::ffi::CStr;
689 /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
690 /// assert!(cstr.is_ok());
692 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
693 pub fn from_bytes_with_nul(bytes: &[u8])
694 -> Result<&CStr, FromBytesWithNulError> {
695 let nul_pos = memchr::memchr(0, bytes);
696 if let Some(nul_pos) = nul_pos {
697 if nul_pos + 1 != bytes.len() {
698 return Err(FromBytesWithNulError::interior_nul(nul_pos));
700 Ok(unsafe { CStr::from_bytes_with_nul_unchecked(bytes) })
702 Err(FromBytesWithNulError::not_nul_terminated())
706 /// Unsafely creates a C string wrapper from a byte slice.
708 /// This function will cast the provided `bytes` to a `CStr` wrapper without
709 /// performing any sanity checks. The provided slice must be null terminated
710 /// and not contain any interior nul bytes.
715 /// use std::ffi::{CStr, CString};
718 /// let cstring = CString::new("hello").unwrap();
719 /// let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
720 /// assert_eq!(cstr, &*cstring);
723 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
724 pub unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
725 mem::transmute(bytes)
728 /// Returns the inner pointer to this C string.
730 /// The returned pointer will be valid for as long as `self` is and points
731 /// to a contiguous region of memory terminated with a 0 byte to represent
732 /// the end of the string.
736 /// It is your responsibility to make sure that the underlying memory is not
737 /// freed too early. For example, the following code will cause undefined
738 /// behaviour when `ptr` is used inside the `unsafe` block:
741 /// use std::ffi::{CString};
743 /// let ptr = CString::new("Hello").unwrap().as_ptr();
745 /// // `ptr` is dangling
750 /// This happens because the pointer returned by `as_ptr` does not carry any
751 /// lifetime information and the string is deallocated immediately after
752 /// the `CString::new("Hello").unwrap().as_ptr()` expression is evaluated.
753 /// To fix the problem, bind the string to a local variable:
756 /// use std::ffi::{CString};
758 /// let hello = CString::new("Hello").unwrap();
759 /// let ptr = hello.as_ptr();
761 /// // `ptr` is valid because `hello` is in scope
765 #[stable(feature = "rust1", since = "1.0.0")]
766 pub fn as_ptr(&self) -> *const c_char {
770 /// Converts this C string to a byte slice.
772 /// This function will calculate the length of this string (which normally
773 /// requires a linear amount of work to be done) and then return the
774 /// resulting slice of `u8` elements.
776 /// The returned slice will **not** contain the trailing nul that this C
779 /// > **Note**: This method is currently implemented as a 0-cost cast, but
780 /// > it is planned to alter its definition in the future to perform the
781 /// > length calculation whenever this method is called.
782 #[stable(feature = "rust1", since = "1.0.0")]
783 pub fn to_bytes(&self) -> &[u8] {
784 let bytes = self.to_bytes_with_nul();
785 &bytes[..bytes.len() - 1]
788 /// Converts this C string to a byte slice containing the trailing 0 byte.
790 /// This function is the equivalent of [`to_bytes`] except that it will retain
791 /// the trailing nul instead of chopping it off.
793 /// > **Note**: This method is currently implemented as a 0-cost cast, but
794 /// > it is planned to alter its definition in the future to perform the
795 /// > length calculation whenever this method is called.
797 /// [`to_bytes`]: #method.to_bytes
798 #[stable(feature = "rust1", since = "1.0.0")]
799 pub fn to_bytes_with_nul(&self) -> &[u8] {
800 unsafe { mem::transmute(&self.inner) }
803 /// Yields a [`&str`] slice if the `CStr` contains valid UTF-8.
805 /// This function will calculate the length of this string and check for
806 /// UTF-8 validity, and then return the [`&str`] if it's valid.
808 /// > **Note**: This method is currently implemented to check for validity
809 /// > after a 0-cost cast, but it is planned to alter its definition in the
810 /// > future to perform the length calculation in addition to the UTF-8
811 /// > check whenever this method is called.
813 /// [`&str`]: ../primitive.str.html
814 #[stable(feature = "cstr_to_str", since = "1.4.0")]
815 pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
816 // NB: When CStr is changed to perform the length check in .to_bytes()
817 // instead of in from_ptr(), it may be worth considering if this should
818 // be rewritten to do the UTF-8 check inline with the length calculation
819 // instead of doing it afterwards.
820 str::from_utf8(self.to_bytes())
823 /// Converts a `CStr` into a [`Cow`]`<`[`str`]`>`.
825 /// This function will calculate the length of this string (which normally
826 /// requires a linear amount of work to be done) and then return the
827 /// resulting slice as a [`Cow`]`<`[`str`]`>`, replacing any invalid UTF-8 sequences
828 /// with `U+FFFD REPLACEMENT CHARACTER`.
830 /// > **Note**: This method is currently implemented to check for validity
831 /// > after a 0-cost cast, but it is planned to alter its definition in the
832 /// > future to perform the length calculation in addition to the UTF-8
833 /// > check whenever this method is called.
835 /// [`Cow`]: ../borrow/enum.Cow.html
836 /// [`str`]: ../primitive.str.html
837 #[stable(feature = "cstr_to_str", since = "1.4.0")]
838 pub fn to_string_lossy(&self) -> Cow<str> {
839 String::from_utf8_lossy(self.to_bytes())
842 /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating.
844 /// [`Box`]: ../boxed/struct.Box.html
845 /// [`CString`]: struct.CString.html
846 #[unstable(feature = "into_boxed_c_str", issue = "40380")]
847 pub fn into_c_string(self: Box<CStr>) -> CString {
848 unsafe { mem::transmute(self) }
852 #[stable(feature = "rust1", since = "1.0.0")]
853 impl PartialEq for CStr {
854 fn eq(&self, other: &CStr) -> bool {
855 self.to_bytes().eq(other.to_bytes())
858 #[stable(feature = "rust1", since = "1.0.0")]
860 #[stable(feature = "rust1", since = "1.0.0")]
861 impl PartialOrd for CStr {
862 fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
863 self.to_bytes().partial_cmp(&other.to_bytes())
866 #[stable(feature = "rust1", since = "1.0.0")]
868 fn cmp(&self, other: &CStr) -> Ordering {
869 self.to_bytes().cmp(&other.to_bytes())
873 #[stable(feature = "cstr_borrow", since = "1.3.0")]
874 impl ToOwned for CStr {
875 type Owned = CString;
877 fn to_owned(&self) -> CString {
878 CString { inner: self.to_bytes_with_nul().into() }
882 #[stable(feature = "cstring_asref", since = "1.7.0")]
883 impl<'a> From<&'a CStr> for CString {
884 fn from(s: &'a CStr) -> CString {
889 #[stable(feature = "cstring_asref", since = "1.7.0")]
890 impl ops::Index<ops::RangeFull> for CString {
894 fn index(&self, _index: ops::RangeFull) -> &CStr {
899 #[stable(feature = "cstring_asref", since = "1.7.0")]
900 impl AsRef<CStr> for CStr {
901 fn as_ref(&self) -> &CStr {
906 #[stable(feature = "cstring_asref", since = "1.7.0")]
907 impl AsRef<CStr> for CString {
908 fn as_ref(&self) -> &CStr {
917 use borrow::Cow::{Borrowed, Owned};
918 use hash::{Hash, Hasher};
919 use collections::hash_map::DefaultHasher;
924 let ptr = data.as_ptr() as *const c_char;
926 assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
927 assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
933 let s = CString::new("1234").unwrap();
934 assert_eq!(s.as_bytes(), b"1234");
935 assert_eq!(s.as_bytes_with_nul(), b"1234\0");
939 fn build_with_zero1() {
940 assert!(CString::new(&b"\0"[..]).is_err());
943 fn build_with_zero2() {
944 assert!(CString::new(vec![0]).is_err());
948 fn build_with_zero3() {
950 let s = CString::from_vec_unchecked(vec![0]);
951 assert_eq!(s.as_bytes(), b"\0");
957 let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
958 assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
964 let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
965 assert_eq!(s.to_bytes(), b"12");
966 assert_eq!(s.to_bytes_with_nul(), b"12\0");
972 let data = b"123\xE2\x80\xA6\0";
973 let ptr = data.as_ptr() as *const c_char;
975 assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
976 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
978 let data = b"123\xE2\0";
979 let ptr = data.as_ptr() as *const c_char;
981 assert!(CStr::from_ptr(ptr).to_str().is_err());
982 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
989 let ptr = data.as_ptr() as *const c_char;
991 let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
992 assert_eq!(owned.as_bytes_with_nul(), data);
997 let data = b"123\xE2\xFA\xA6\0";
998 let ptr = data.as_ptr() as *const c_char;
999 let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
1001 let mut s = DefaultHasher::new();
1003 let cstr_hash = s.finish();
1004 let mut s = DefaultHasher::new();
1005 CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
1006 let cstring_hash = s.finish();
1008 assert_eq!(cstr_hash, cstring_hash);
1012 fn from_bytes_with_nul() {
1013 let data = b"123\0";
1014 let cstr = CStr::from_bytes_with_nul(data);
1015 assert_eq!(cstr.map(CStr::to_bytes), Ok(&b"123"[..]));
1016 let cstr = CStr::from_bytes_with_nul(data);
1017 assert_eq!(cstr.map(CStr::to_bytes_with_nul), Ok(&b"123\0"[..]));
1020 let cstr = CStr::from_bytes_with_nul(data);
1021 let cstr_unchecked = CStr::from_bytes_with_nul_unchecked(data);
1022 assert_eq!(cstr, Ok(cstr_unchecked));
1027 fn from_bytes_with_nul_unterminated() {
1029 let cstr = CStr::from_bytes_with_nul(data);
1030 assert!(cstr.is_err());
1034 fn from_bytes_with_nul_interior() {
1035 let data = b"1\023\0";
1036 let cstr = CStr::from_bytes_with_nul(data);
1037 assert!(cstr.is_err());
1042 let orig: &[u8] = b"Hello, world!\0";
1043 let cstr = CStr::from_bytes_with_nul(orig).unwrap();
1044 let boxed: Box<CStr> = Box::from(cstr);
1045 let cstring = cstr.to_owned().into_boxed_c_str().into_c_string();
1046 assert_eq!(cstr, &*boxed);
1047 assert_eq!(&*boxed, &*cstring);
1048 assert_eq!(&*cstring, cstr);
1052 fn boxed_default() {
1053 let boxed = <Box<CStr>>::default();
1054 assert_eq!(boxed.to_bytes_with_nul(), &[0]);