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. After
34 /// being created, a `CString` predominately inherits all of its methods from
35 /// the `Deref` implementation to `[c_char]`. Note that the underlying array
36 /// is represented as an array of `c_char` as opposed to `u8`. A `u8` slice
37 /// can be obtained with the `as_bytes` method. Slices produced from a `CString`
38 /// do *not* contain the trailing nul terminator unless otherwise specified.
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.
91 /// Inspecting a foreign C string
94 /// use std::ffi::CStr;
95 /// use std::os::raw::c_char;
97 /// extern { fn my_string() -> *const c_char; }
100 /// let slice = CStr::from_ptr(my_string());
101 /// println!("string length: {}", slice.to_bytes().len());
105 /// Passing a Rust-originating C string
108 /// use std::ffi::{CString, CStr};
109 /// use std::os::raw::c_char;
111 /// fn work(data: &CStr) {
112 /// extern { fn work_with(data: *const c_char); }
114 /// unsafe { work_with(data.as_ptr()) }
117 /// let s = CString::new("data data data data").unwrap();
121 /// Converting a foreign C string into a Rust `String`
124 /// use std::ffi::CStr;
125 /// use std::os::raw::c_char;
127 /// extern { fn my_string() -> *const c_char; }
129 /// fn my_string_safe() -> String {
131 /// CStr::from_ptr(my_string()).to_string_lossy().into_owned()
135 /// println!("string: {}", my_string_safe());
138 #[stable(feature = "rust1", since = "1.0.0")]
140 // FIXME: this should not be represented with a DST slice but rather with
141 // just a raw `c_char` along with some form of marker to make
142 // this an unsized type. Essentially `sizeof(&CStr)` should be the
143 // same as `sizeof(&c_char)` but `CStr` should be an unsized type.
147 /// An error returned from `CString::new` to indicate that a nul byte was found
148 /// in the vector provided.
149 #[derive(Clone, PartialEq, Eq, Debug)]
150 #[stable(feature = "rust1", since = "1.0.0")]
151 pub struct NulError(usize, Vec<u8>);
153 /// An error returned from `CStr::from_bytes_with_nul` to indicate that a nul
154 /// byte was found too early in the slice provided or one wasn't found at all.
155 #[derive(Clone, PartialEq, Eq, Debug)]
156 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
157 pub struct FromBytesWithNulError { _a: () }
159 /// An error returned from `CString::into_string` to indicate that a UTF-8 error
160 /// was encountered during the conversion.
161 #[derive(Clone, PartialEq, Eq, Debug)]
162 #[stable(feature = "cstring_into", since = "1.7.0")]
163 pub struct IntoStringError {
169 /// Creates a new C-compatible string from a container of bytes.
171 /// This method will consume the provided data and use the underlying bytes
172 /// to construct a new string, ensuring that there is a trailing 0 byte.
177 /// use std::ffi::CString;
178 /// use std::os::raw::c_char;
180 /// extern { fn puts(s: *const c_char); }
182 /// let to_print = CString::new("Hello!").unwrap();
184 /// puts(to_print.as_ptr());
190 /// This function will return an error if the bytes yielded contain an
191 /// internal 0 byte. The error returned will contain the bytes as well as
192 /// the position of the nul byte.
193 #[stable(feature = "rust1", since = "1.0.0")]
194 pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
198 fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
199 match memchr::memchr(0, &bytes) {
200 Some(i) => Err(NulError(i, bytes)),
201 None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
205 /// Creates a C-compatible string from a byte vector without checking for
206 /// interior 0 bytes.
208 /// This method is equivalent to `new` except that no runtime assertion
209 /// is made that `v` contains no 0 bytes, and it requires an actual
210 /// byte vector, not anything that can be converted to one with Into.
215 /// use std::ffi::CString;
217 /// let raw = b"foo".to_vec();
219 /// let c_string = CString::from_vec_unchecked(raw);
222 #[stable(feature = "rust1", since = "1.0.0")]
223 pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
226 CString { inner: v.into_boxed_slice() }
229 /// Retakes ownership of a `CString` that was transferred to C.
231 /// Additionally, the length of the string will be recalculated from the pointer.
235 /// This should only ever be called with a pointer that was earlier
236 /// obtained by calling `into_raw` on a `CString`. Other usage (e.g. trying to take
237 /// ownership of a string that was allocated by foreign code) is likely to lead
238 /// to undefined behavior or allocator corruption.
239 #[stable(feature = "cstr_memory", since = "1.4.0")]
240 pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
241 let len = libc::strlen(ptr) + 1; // Including the NUL byte
242 let slice = slice::from_raw_parts(ptr, len as usize);
243 CString { inner: mem::transmute(slice) }
246 /// Transfers ownership of the string to a C caller.
248 /// The pointer must be returned to Rust and reconstituted using
249 /// `from_raw` to be properly deallocated. Specifically, one
250 /// should *not* use the standard C `free` function to deallocate
253 /// Failure to call `from_raw` will lead to a memory leak.
254 #[stable(feature = "cstr_memory", since = "1.4.0")]
255 pub fn into_raw(self) -> *mut c_char {
256 Box::into_raw(self.into_inner()) as *mut c_char
259 /// Converts the `CString` into a `String` if it contains valid Unicode data.
261 /// On failure, ownership of the original `CString` is returned.
262 #[stable(feature = "cstring_into", since = "1.7.0")]
263 pub fn into_string(self) -> Result<String, IntoStringError> {
264 String::from_utf8(self.into_bytes())
265 .map_err(|e| IntoStringError {
266 error: e.utf8_error(),
267 inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
271 /// Returns the underlying byte buffer.
273 /// The returned buffer does **not** contain the trailing nul separator and
274 /// it is guaranteed to not have any interior nul bytes.
275 #[stable(feature = "cstring_into", since = "1.7.0")]
276 pub fn into_bytes(self) -> Vec<u8> {
277 let mut vec = self.into_inner().into_vec();
278 let _nul = vec.pop();
279 debug_assert_eq!(_nul, Some(0u8));
283 /// Equivalent to the `into_bytes` function except that the returned vector
284 /// includes the trailing nul byte.
285 #[stable(feature = "cstring_into", since = "1.7.0")]
286 pub fn into_bytes_with_nul(self) -> Vec<u8> {
287 self.into_inner().into_vec()
290 /// Returns the contents of this `CString` as a slice of bytes.
292 /// The returned slice does **not** contain the trailing nul separator and
293 /// it is guaranteed to not have any interior nul bytes.
294 #[stable(feature = "rust1", since = "1.0.0")]
295 pub fn as_bytes(&self) -> &[u8] {
296 &self.inner[..self.inner.len() - 1]
299 /// Equivalent to the `as_bytes` function except that the returned slice
300 /// includes the trailing nul byte.
301 #[stable(feature = "rust1", since = "1.0.0")]
302 pub fn as_bytes_with_nul(&self) -> &[u8] {
306 /// Converts this `CString` into a boxed `CStr`.
307 #[unstable(feature = "into_boxed_c_str", issue = "0")]
308 pub fn into_boxed_c_str(self) -> Box<CStr> {
309 unsafe { mem::transmute(self.into_inner()) }
312 // Bypass "move out of struct which implements `Drop` trait" restriction.
313 fn into_inner(self) -> Box<[u8]> {
315 let result = ptr::read(&self.inner);
322 // Turns this `CString` into an empty string to prevent
323 // memory unsafe code from working by accident. Inline
324 // to prevent LLVM from optimizing it away in debug builds.
325 #[stable(feature = "cstring_drop", since = "1.13.0")]
326 impl Drop for CString {
329 unsafe { *self.inner.get_unchecked_mut(0) = 0; }
333 #[stable(feature = "rust1", since = "1.0.0")]
334 impl ops::Deref for CString {
337 fn deref(&self) -> &CStr {
338 unsafe { mem::transmute(self.as_bytes_with_nul()) }
342 #[stable(feature = "rust1", since = "1.0.0")]
343 impl fmt::Debug for CString {
344 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
345 fmt::Debug::fmt(&**self, f)
349 #[stable(feature = "cstring_into", since = "1.7.0")]
350 impl From<CString> for Vec<u8> {
351 fn from(s: CString) -> Vec<u8> {
356 #[stable(feature = "cstr_debug", since = "1.3.0")]
357 impl fmt::Debug for CStr {
358 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
360 for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
361 f.write_char(byte as char)?;
367 #[stable(feature = "cstr_default", since = "1.10.0")]
368 impl<'a> Default for &'a CStr {
369 fn default() -> &'a CStr {
370 static SLICE: &'static [c_char] = &[0];
371 unsafe { CStr::from_ptr(SLICE.as_ptr()) }
375 #[stable(feature = "cstr_default", since = "1.10.0")]
376 impl Default for CString {
377 /// Creates an empty `CString`.
378 fn default() -> CString {
379 let a: &CStr = Default::default();
384 #[stable(feature = "cstr_borrow", since = "1.3.0")]
385 impl Borrow<CStr> for CString {
386 fn borrow(&self) -> &CStr { self }
389 #[stable(feature = "box_from_c_str", since = "1.17.0")]
390 impl<'a> From<&'a CStr> for Box<CStr> {
391 fn from(s: &'a CStr) -> Box<CStr> {
392 let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul());
393 unsafe { mem::transmute(boxed) }
397 #[stable(feature = "default_box_extra", since = "1.17.0")]
398 impl Default for Box<CStr> {
399 fn default() -> Box<CStr> {
400 let boxed: Box<[u8]> = Box::from([0]);
401 unsafe { mem::transmute(boxed) }
406 /// Returns the position of the nul byte in the slice that was provided to
412 /// use std::ffi::CString;
414 /// let nul_error = CString::new("foo\0bar").unwrap_err();
415 /// assert_eq!(nul_error.nul_position(), 3);
417 /// let nul_error = CString::new("foo bar\0").unwrap_err();
418 /// assert_eq!(nul_error.nul_position(), 7);
420 #[stable(feature = "rust1", since = "1.0.0")]
421 pub fn nul_position(&self) -> usize { self.0 }
423 /// Consumes this error, returning the underlying vector of bytes which
424 /// generated the error in the first place.
429 /// use std::ffi::CString;
431 /// let nul_error = CString::new("foo\0bar").unwrap_err();
432 /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
434 #[stable(feature = "rust1", since = "1.0.0")]
435 pub fn into_vec(self) -> Vec<u8> { self.1 }
438 #[stable(feature = "rust1", since = "1.0.0")]
439 impl Error for NulError {
440 fn description(&self) -> &str { "nul byte found in data" }
443 #[stable(feature = "rust1", since = "1.0.0")]
444 impl fmt::Display for NulError {
445 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
446 write!(f, "nul byte found in provided data at position: {}", self.0)
450 #[stable(feature = "rust1", since = "1.0.0")]
451 impl From<NulError> for io::Error {
452 fn from(_: NulError) -> io::Error {
453 io::Error::new(io::ErrorKind::InvalidInput,
454 "data provided contains a nul byte")
458 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
459 impl Error for FromBytesWithNulError {
460 fn description(&self) -> &str {
461 "data provided is not null terminated or contains an interior nul byte"
465 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
466 impl fmt::Display for FromBytesWithNulError {
467 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
468 self.description().fmt(f)
472 impl IntoStringError {
473 /// Consumes this error, returning original `CString` which generated the
475 #[stable(feature = "cstring_into", since = "1.7.0")]
476 pub fn into_cstring(self) -> CString {
480 /// Access the underlying UTF-8 error that was the cause of this error.
481 #[stable(feature = "cstring_into", since = "1.7.0")]
482 pub fn utf8_error(&self) -> Utf8Error {
487 #[stable(feature = "cstring_into", since = "1.7.0")]
488 impl Error for IntoStringError {
489 fn description(&self) -> &str {
490 "C string contained non-utf8 bytes"
493 fn cause(&self) -> Option<&Error> {
498 #[stable(feature = "cstring_into", since = "1.7.0")]
499 impl fmt::Display for IntoStringError {
500 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
501 self.description().fmt(f)
506 /// Casts a raw C string to a safe C string wrapper.
508 /// This function will cast the provided `ptr` to the `CStr` wrapper which
509 /// allows inspection and interoperation of non-owned C strings. This method
510 /// is unsafe for a number of reasons:
512 /// * There is no guarantee to the validity of `ptr`
513 /// * The returned lifetime is not guaranteed to be the actual lifetime of
515 /// * There is no guarantee that the memory pointed to by `ptr` contains a
516 /// valid nul terminator byte at the end of the string.
518 /// > **Note**: This operation is intended to be a 0-cost cast but it is
519 /// > currently implemented with an up-front calculation of the length of
520 /// > the string. This is not guaranteed to always be the case.
526 /// use std::ffi::CStr;
527 /// use std::os::raw::c_char;
530 /// fn my_string() -> *const c_char;
534 /// let slice = CStr::from_ptr(my_string());
535 /// println!("string returned: {}", slice.to_str().unwrap());
539 #[stable(feature = "rust1", since = "1.0.0")]
540 pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
541 let len = libc::strlen(ptr);
542 mem::transmute(slice::from_raw_parts(ptr, len as usize + 1))
545 /// Creates a C string wrapper from a byte slice.
547 /// This function will cast the provided `bytes` to a `CStr` wrapper after
548 /// ensuring that it is null terminated and does not contain any interior
554 /// use std::ffi::CStr;
556 /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
557 /// assert!(cstr.is_ok());
559 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
560 pub fn from_bytes_with_nul(bytes: &[u8])
561 -> Result<&CStr, FromBytesWithNulError> {
562 if bytes.is_empty() || memchr::memchr(0, &bytes) != Some(bytes.len() - 1) {
563 Err(FromBytesWithNulError { _a: () })
565 Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) })
569 /// Unsafely creates a C string wrapper from a byte slice.
571 /// This function will cast the provided `bytes` to a `CStr` wrapper without
572 /// performing any sanity checks. The provided slice must be null terminated
573 /// and not contain any interior nul bytes.
578 /// use std::ffi::{CStr, CString};
581 /// let cstring = CString::new("hello").unwrap();
582 /// let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
583 /// assert_eq!(cstr, &*cstring);
586 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
587 pub unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
588 mem::transmute(bytes)
591 /// Returns the inner pointer to this C string.
593 /// The returned pointer will be valid for as long as `self` is and points
594 /// to a contiguous region of memory terminated with a 0 byte to represent
595 /// the end of the string.
599 /// It is your responsibility to make sure that the underlying memory is not
600 /// freed too early. For example, the following code will cause undefined
601 /// behaviour when `ptr` is used inside the `unsafe` block:
604 /// use std::ffi::{CString};
606 /// let ptr = CString::new("Hello").unwrap().as_ptr();
608 /// // `ptr` is dangling
613 /// This happens because the pointer returned by `as_ptr` does not carry any
614 /// lifetime information and the string is deallocated immediately after
615 /// the `CString::new("Hello").unwrap().as_ptr()` expression is evaluated.
616 /// To fix the problem, bind the string to a local variable:
619 /// use std::ffi::{CString};
621 /// let hello = CString::new("Hello").unwrap();
622 /// let ptr = hello.as_ptr();
624 /// // `ptr` is valid because `hello` is in scope
628 #[stable(feature = "rust1", since = "1.0.0")]
629 pub fn as_ptr(&self) -> *const c_char {
633 /// Converts this C string to a byte slice.
635 /// This function will calculate the length of this string (which normally
636 /// requires a linear amount of work to be done) and then return the
637 /// resulting slice of `u8` elements.
639 /// The returned slice will **not** contain the trailing nul that this C
642 /// > **Note**: This method is currently implemented as a 0-cost cast, but
643 /// > it is planned to alter its definition in the future to perform the
644 /// > length calculation whenever this method is called.
645 #[stable(feature = "rust1", since = "1.0.0")]
646 pub fn to_bytes(&self) -> &[u8] {
647 let bytes = self.to_bytes_with_nul();
648 &bytes[..bytes.len() - 1]
651 /// Converts this C string to a byte slice containing the trailing 0 byte.
653 /// This function is the equivalent of `to_bytes` except that it will retain
654 /// the trailing nul instead of chopping it off.
656 /// > **Note**: This method is currently implemented as a 0-cost cast, but
657 /// > it is planned to alter its definition in the future to perform the
658 /// > length calculation whenever this method is called.
659 #[stable(feature = "rust1", since = "1.0.0")]
660 pub fn to_bytes_with_nul(&self) -> &[u8] {
661 unsafe { mem::transmute(&self.inner) }
664 /// Yields a `&str` slice if the `CStr` contains valid UTF-8.
666 /// This function will calculate the length of this string and check for
667 /// UTF-8 validity, and then return the `&str` if it's valid.
669 /// > **Note**: This method is currently implemented to check for validity
670 /// > after a 0-cost cast, but it is planned to alter its definition in the
671 /// > future to perform the length calculation in addition to the UTF-8
672 /// > check whenever this method is called.
673 #[stable(feature = "cstr_to_str", since = "1.4.0")]
674 pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
675 // NB: When CStr is changed to perform the length check in .to_bytes()
676 // instead of in from_ptr(), it may be worth considering if this should
677 // be rewritten to do the UTF-8 check inline with the length calculation
678 // instead of doing it afterwards.
679 str::from_utf8(self.to_bytes())
682 /// Converts a `CStr` into a `Cow<str>`.
684 /// This function will calculate the length of this string (which normally
685 /// requires a linear amount of work to be done) and then return the
686 /// resulting slice as a `Cow<str>`, replacing any invalid UTF-8 sequences
687 /// with `U+FFFD REPLACEMENT CHARACTER`.
689 /// > **Note**: This method is currently implemented to check for validity
690 /// > after a 0-cost cast, but it is planned to alter its definition in the
691 /// > future to perform the length calculation in addition to the UTF-8
692 /// > check whenever this method is called.
693 #[stable(feature = "cstr_to_str", since = "1.4.0")]
694 pub fn to_string_lossy(&self) -> Cow<str> {
695 String::from_utf8_lossy(self.to_bytes())
699 #[stable(feature = "rust1", since = "1.0.0")]
700 impl PartialEq for CStr {
701 fn eq(&self, other: &CStr) -> bool {
702 self.to_bytes().eq(other.to_bytes())
705 #[stable(feature = "rust1", since = "1.0.0")]
707 #[stable(feature = "rust1", since = "1.0.0")]
708 impl PartialOrd for CStr {
709 fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
710 self.to_bytes().partial_cmp(&other.to_bytes())
713 #[stable(feature = "rust1", since = "1.0.0")]
715 fn cmp(&self, other: &CStr) -> Ordering {
716 self.to_bytes().cmp(&other.to_bytes())
720 #[stable(feature = "cstr_borrow", since = "1.3.0")]
721 impl ToOwned for CStr {
722 type Owned = CString;
724 fn to_owned(&self) -> CString {
725 CString { inner: self.to_bytes_with_nul().into() }
729 #[stable(feature = "cstring_asref", since = "1.7.0")]
730 impl<'a> From<&'a CStr> for CString {
731 fn from(s: &'a CStr) -> CString {
736 #[stable(feature = "cstring_asref", since = "1.7.0")]
737 impl ops::Index<ops::RangeFull> for CString {
741 fn index(&self, _index: ops::RangeFull) -> &CStr {
746 #[stable(feature = "cstring_asref", since = "1.7.0")]
747 impl AsRef<CStr> for CStr {
748 fn as_ref(&self) -> &CStr {
753 #[stable(feature = "cstring_asref", since = "1.7.0")]
754 impl AsRef<CStr> for CString {
755 fn as_ref(&self) -> &CStr {
764 use borrow::Cow::{Borrowed, Owned};
765 use hash::{Hash, Hasher};
766 use collections::hash_map::DefaultHasher;
771 let ptr = data.as_ptr() as *const c_char;
773 assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
774 assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
780 let s = CString::new("1234").unwrap();
781 assert_eq!(s.as_bytes(), b"1234");
782 assert_eq!(s.as_bytes_with_nul(), b"1234\0");
786 fn build_with_zero1() {
787 assert!(CString::new(&b"\0"[..]).is_err());
790 fn build_with_zero2() {
791 assert!(CString::new(vec![0]).is_err());
795 fn build_with_zero3() {
797 let s = CString::from_vec_unchecked(vec![0]);
798 assert_eq!(s.as_bytes(), b"\0");
804 let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
805 assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
811 let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
812 assert_eq!(s.to_bytes(), b"12");
813 assert_eq!(s.to_bytes_with_nul(), b"12\0");
819 let data = b"123\xE2\x80\xA6\0";
820 let ptr = data.as_ptr() as *const c_char;
822 assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
823 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
825 let data = b"123\xE2\0";
826 let ptr = data.as_ptr() as *const c_char;
828 assert!(CStr::from_ptr(ptr).to_str().is_err());
829 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
836 let ptr = data.as_ptr() as *const c_char;
838 let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
839 assert_eq!(owned.as_bytes_with_nul(), data);
844 let data = b"123\xE2\xFA\xA6\0";
845 let ptr = data.as_ptr() as *const c_char;
846 let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
848 let mut s = DefaultHasher::new();
850 let cstr_hash = s.finish();
851 let mut s = DefaultHasher::new();
852 CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
853 let cstring_hash = s.finish();
855 assert_eq!(cstr_hash, cstring_hash);
859 fn from_bytes_with_nul() {
861 let cstr = CStr::from_bytes_with_nul(data);
862 assert_eq!(cstr.map(CStr::to_bytes), Ok(&b"123"[..]));
863 let cstr = CStr::from_bytes_with_nul(data);
864 assert_eq!(cstr.map(CStr::to_bytes_with_nul), Ok(&b"123\0"[..]));
867 let cstr = CStr::from_bytes_with_nul(data);
868 let cstr_unchecked = CStr::from_bytes_with_nul_unchecked(data);
869 assert_eq!(cstr, Ok(cstr_unchecked));
874 fn from_bytes_with_nul_unterminated() {
876 let cstr = CStr::from_bytes_with_nul(data);
877 assert!(cstr.is_err());
881 fn from_bytes_with_nul_interior() {
882 let data = b"1\023\0";
883 let cstr = CStr::from_bytes_with_nul(data);
884 assert!(cstr.is_err());
889 let orig: &[u8] = b"Hello, world!\0";
890 let cstr = CStr::from_bytes_with_nul(orig).unwrap();
891 let cstring = cstr.to_owned();
892 let box1: Box<CStr> = Box::from(cstr);
893 let box2 = cstring.into_boxed_c_str();
894 assert_eq!(cstr, &*box1);
895 assert_eq!(box1, box2);
896 assert_eq!(&*box2, cstr);
901 let boxed = <Box<CStr>>::default();
902 assert_eq!(boxed.to_bytes_with_nul(), &[0]);