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 {
158 kind: FromBytesWithNulErrorKind,
161 #[derive(Clone, PartialEq, Eq, Debug)]
162 enum FromBytesWithNulErrorKind {
167 impl FromBytesWithNulError {
168 fn interior_nul(pos: usize) -> FromBytesWithNulError {
169 FromBytesWithNulError {
170 kind: FromBytesWithNulErrorKind::InteriorNul(pos),
173 fn not_nul_terminated() -> FromBytesWithNulError {
174 FromBytesWithNulError {
175 kind: FromBytesWithNulErrorKind::NotNulTerminated,
180 /// An error returned from `CString::into_string` to indicate that a UTF-8 error
181 /// was encountered during the conversion.
182 #[derive(Clone, PartialEq, Eq, Debug)]
183 #[stable(feature = "cstring_into", since = "1.7.0")]
184 pub struct IntoStringError {
190 /// Creates a new C-compatible string from a container of bytes.
192 /// This method will consume the provided data and use the underlying bytes
193 /// to construct a new string, ensuring that there is a trailing 0 byte.
198 /// use std::ffi::CString;
199 /// use std::os::raw::c_char;
201 /// extern { fn puts(s: *const c_char); }
203 /// let to_print = CString::new("Hello!").unwrap();
205 /// puts(to_print.as_ptr());
211 /// This function will return an error if the bytes yielded contain an
212 /// internal 0 byte. The error returned will contain the bytes as well as
213 /// the position of the nul byte.
214 #[stable(feature = "rust1", since = "1.0.0")]
215 pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
219 fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
220 match memchr::memchr(0, &bytes) {
221 Some(i) => Err(NulError(i, bytes)),
222 None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
226 /// Creates a C-compatible string from a byte vector without checking for
227 /// interior 0 bytes.
229 /// This method is equivalent to `new` except that no runtime assertion
230 /// is made that `v` contains no 0 bytes, and it requires an actual
231 /// byte vector, not anything that can be converted to one with Into.
236 /// use std::ffi::CString;
238 /// let raw = b"foo".to_vec();
240 /// let c_string = CString::from_vec_unchecked(raw);
243 #[stable(feature = "rust1", since = "1.0.0")]
244 pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
247 CString { inner: v.into_boxed_slice() }
250 /// Retakes ownership of a `CString` that was transferred to C.
252 /// Additionally, the length of the string will be recalculated from the pointer.
256 /// This should only ever be called with a pointer that was earlier
257 /// obtained by calling `into_raw` on a `CString`. Other usage (e.g. trying to take
258 /// ownership of a string that was allocated by foreign code) is likely to lead
259 /// to undefined behavior or allocator corruption.
260 #[stable(feature = "cstr_memory", since = "1.4.0")]
261 pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
262 let len = libc::strlen(ptr) + 1; // Including the NUL byte
263 let slice = slice::from_raw_parts(ptr, len as usize);
264 CString { inner: mem::transmute(slice) }
267 /// Transfers ownership of the string to a C caller.
269 /// The pointer must be returned to Rust and reconstituted using
270 /// `from_raw` to be properly deallocated. Specifically, one
271 /// should *not* use the standard C `free` function to deallocate
274 /// Failure to call `from_raw` will lead to a memory leak.
275 #[stable(feature = "cstr_memory", since = "1.4.0")]
276 pub fn into_raw(self) -> *mut c_char {
277 Box::into_raw(self.into_inner()) as *mut c_char
280 /// Converts the `CString` into a `String` if it contains valid Unicode data.
282 /// On failure, ownership of the original `CString` is returned.
283 #[stable(feature = "cstring_into", since = "1.7.0")]
284 pub fn into_string(self) -> Result<String, IntoStringError> {
285 String::from_utf8(self.into_bytes())
286 .map_err(|e| IntoStringError {
287 error: e.utf8_error(),
288 inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
292 /// Returns the underlying byte buffer.
294 /// The returned buffer does **not** contain the trailing nul separator and
295 /// it is guaranteed to not have any interior nul bytes.
296 #[stable(feature = "cstring_into", since = "1.7.0")]
297 pub fn into_bytes(self) -> Vec<u8> {
298 let mut vec = self.into_inner().into_vec();
299 let _nul = vec.pop();
300 debug_assert_eq!(_nul, Some(0u8));
304 /// Equivalent to the `into_bytes` function except that the returned vector
305 /// includes the trailing nul byte.
306 #[stable(feature = "cstring_into", since = "1.7.0")]
307 pub fn into_bytes_with_nul(self) -> Vec<u8> {
308 self.into_inner().into_vec()
311 /// Returns the contents of this `CString` as a slice of bytes.
313 /// The returned slice does **not** contain the trailing nul separator and
314 /// it is guaranteed to not have any interior nul bytes.
315 #[stable(feature = "rust1", since = "1.0.0")]
316 pub fn as_bytes(&self) -> &[u8] {
317 &self.inner[..self.inner.len() - 1]
320 /// Equivalent to the `as_bytes` function except that the returned slice
321 /// includes the trailing nul byte.
322 #[stable(feature = "rust1", since = "1.0.0")]
323 pub fn as_bytes_with_nul(&self) -> &[u8] {
327 /// Extracts a `CStr` slice containing the entire string.
328 #[unstable(feature = "as_c_str", issue = "40380")]
329 pub fn as_c_str(&self) -> &CStr {
333 /// Converts this `CString` into a boxed `CStr`.
334 #[unstable(feature = "into_boxed_c_str", issue = "40380")]
335 pub fn into_boxed_c_str(self) -> Box<CStr> {
336 unsafe { mem::transmute(self.into_inner()) }
339 // Bypass "move out of struct which implements `Drop` trait" restriction.
340 fn into_inner(self) -> Box<[u8]> {
342 let result = ptr::read(&self.inner);
349 // Turns this `CString` into an empty string to prevent
350 // memory unsafe code from working by accident. Inline
351 // to prevent LLVM from optimizing it away in debug builds.
352 #[stable(feature = "cstring_drop", since = "1.13.0")]
353 impl Drop for CString {
356 unsafe { *self.inner.get_unchecked_mut(0) = 0; }
360 #[stable(feature = "rust1", since = "1.0.0")]
361 impl ops::Deref for CString {
364 fn deref(&self) -> &CStr {
365 unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
369 #[stable(feature = "rust1", since = "1.0.0")]
370 impl fmt::Debug for CString {
371 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
372 fmt::Debug::fmt(&**self, f)
376 #[stable(feature = "cstring_into", since = "1.7.0")]
377 impl From<CString> for Vec<u8> {
378 fn from(s: CString) -> Vec<u8> {
383 #[stable(feature = "cstr_debug", since = "1.3.0")]
384 impl fmt::Debug for CStr {
385 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
387 for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
388 f.write_char(byte as char)?;
394 #[stable(feature = "cstr_default", since = "1.10.0")]
395 impl<'a> Default for &'a CStr {
396 fn default() -> &'a CStr {
397 static SLICE: &'static [c_char] = &[0];
398 unsafe { CStr::from_ptr(SLICE.as_ptr()) }
402 #[stable(feature = "cstr_default", since = "1.10.0")]
403 impl Default for CString {
404 /// Creates an empty `CString`.
405 fn default() -> CString {
406 let a: &CStr = Default::default();
411 #[stable(feature = "cstr_borrow", since = "1.3.0")]
412 impl Borrow<CStr> for CString {
413 fn borrow(&self) -> &CStr { self }
416 #[stable(feature = "box_from_c_str", since = "1.17.0")]
417 impl<'a> From<&'a CStr> for Box<CStr> {
418 fn from(s: &'a CStr) -> Box<CStr> {
419 let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul());
420 unsafe { mem::transmute(boxed) }
424 #[stable(feature = "c_string_from_box", since = "1.17.0")]
425 impl From<Box<CStr>> for CString {
426 fn from(s: Box<CStr>) -> CString {
431 #[stable(feature = "box_from_c_string", since = "1.17.0")]
432 impl Into<Box<CStr>> for CString {
433 fn into(self) -> Box<CStr> {
434 self.into_boxed_c_str()
438 #[stable(feature = "default_box_extra", since = "1.17.0")]
439 impl Default for Box<CStr> {
440 fn default() -> Box<CStr> {
441 let boxed: Box<[u8]> = Box::from([0]);
442 unsafe { mem::transmute(boxed) }
447 /// Returns the position of the nul byte in the slice that was provided to
453 /// use std::ffi::CString;
455 /// let nul_error = CString::new("foo\0bar").unwrap_err();
456 /// assert_eq!(nul_error.nul_position(), 3);
458 /// let nul_error = CString::new("foo bar\0").unwrap_err();
459 /// assert_eq!(nul_error.nul_position(), 7);
461 #[stable(feature = "rust1", since = "1.0.0")]
462 pub fn nul_position(&self) -> usize { self.0 }
464 /// Consumes this error, returning the underlying vector of bytes which
465 /// generated the error in the first place.
470 /// use std::ffi::CString;
472 /// let nul_error = CString::new("foo\0bar").unwrap_err();
473 /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
475 #[stable(feature = "rust1", since = "1.0.0")]
476 pub fn into_vec(self) -> Vec<u8> { self.1 }
479 #[stable(feature = "rust1", since = "1.0.0")]
480 impl Error for NulError {
481 fn description(&self) -> &str { "nul byte found in data" }
484 #[stable(feature = "rust1", since = "1.0.0")]
485 impl fmt::Display for NulError {
486 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
487 write!(f, "nul byte found in provided data at position: {}", self.0)
491 #[stable(feature = "rust1", since = "1.0.0")]
492 impl From<NulError> for io::Error {
493 fn from(_: NulError) -> io::Error {
494 io::Error::new(io::ErrorKind::InvalidInput,
495 "data provided contains a nul byte")
499 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
500 impl Error for FromBytesWithNulError {
501 fn description(&self) -> &str {
503 FromBytesWithNulErrorKind::InteriorNul(..) =>
504 "data provided contains an interior nul byte",
505 FromBytesWithNulErrorKind::NotNulTerminated =>
506 "data provided is not nul terminated",
511 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
512 impl fmt::Display for FromBytesWithNulError {
513 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
514 f.write_str(self.description())?;
515 if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind {
516 write!(f, " at byte pos {}", pos)?;
522 impl IntoStringError {
523 /// Consumes this error, returning original `CString` which generated the
525 #[stable(feature = "cstring_into", since = "1.7.0")]
526 pub fn into_cstring(self) -> CString {
530 /// Access the underlying UTF-8 error that was the cause of this error.
531 #[stable(feature = "cstring_into", since = "1.7.0")]
532 pub fn utf8_error(&self) -> Utf8Error {
537 #[stable(feature = "cstring_into", since = "1.7.0")]
538 impl Error for IntoStringError {
539 fn description(&self) -> &str {
540 "C string contained non-utf8 bytes"
543 fn cause(&self) -> Option<&Error> {
548 #[stable(feature = "cstring_into", since = "1.7.0")]
549 impl fmt::Display for IntoStringError {
550 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
551 self.description().fmt(f)
556 /// Casts a raw C string to a safe C string wrapper.
558 /// This function will cast the provided `ptr` to the `CStr` wrapper which
559 /// allows inspection and interoperation of non-owned C strings. This method
560 /// is unsafe for a number of reasons:
562 /// * There is no guarantee to the validity of `ptr`
563 /// * The returned lifetime is not guaranteed to be the actual lifetime of
565 /// * There is no guarantee that the memory pointed to by `ptr` contains a
566 /// valid nul terminator byte at the end of the string.
568 /// > **Note**: This operation is intended to be a 0-cost cast but it is
569 /// > currently implemented with an up-front calculation of the length of
570 /// > the string. This is not guaranteed to always be the case.
576 /// use std::ffi::CStr;
577 /// use std::os::raw::c_char;
580 /// fn my_string() -> *const c_char;
584 /// let slice = CStr::from_ptr(my_string());
585 /// println!("string returned: {}", slice.to_str().unwrap());
589 #[stable(feature = "rust1", since = "1.0.0")]
590 pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
591 let len = libc::strlen(ptr);
592 let ptr = ptr as *const u8;
593 CStr::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr, len as usize + 1))
596 /// Creates a C string wrapper from a byte slice.
598 /// This function will cast the provided `bytes` to a `CStr` wrapper after
599 /// ensuring that it is null terminated and does not contain any interior
605 /// use std::ffi::CStr;
607 /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
608 /// assert!(cstr.is_ok());
610 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
611 pub fn from_bytes_with_nul(bytes: &[u8])
612 -> Result<&CStr, FromBytesWithNulError> {
613 let nul_pos = memchr::memchr(0, bytes);
614 if let Some(nul_pos) = nul_pos {
615 if nul_pos + 1 != bytes.len() {
616 return Err(FromBytesWithNulError::interior_nul(nul_pos));
618 Ok(unsafe { CStr::from_bytes_with_nul_unchecked(bytes) })
620 Err(FromBytesWithNulError::not_nul_terminated())
624 /// Unsafely creates a C string wrapper from a byte slice.
626 /// This function will cast the provided `bytes` to a `CStr` wrapper without
627 /// performing any sanity checks. The provided slice must be null terminated
628 /// and not contain any interior nul bytes.
633 /// use std::ffi::{CStr, CString};
636 /// let cstring = CString::new("hello").unwrap();
637 /// let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
638 /// assert_eq!(cstr, &*cstring);
641 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
642 pub unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
643 mem::transmute(bytes)
646 /// Returns the inner pointer to this C string.
648 /// The returned pointer will be valid for as long as `self` is and points
649 /// to a contiguous region of memory terminated with a 0 byte to represent
650 /// the end of the string.
654 /// It is your responsibility to make sure that the underlying memory is not
655 /// freed too early. For example, the following code will cause undefined
656 /// behaviour when `ptr` is used inside the `unsafe` block:
659 /// use std::ffi::{CString};
661 /// let ptr = CString::new("Hello").unwrap().as_ptr();
663 /// // `ptr` is dangling
668 /// This happens because the pointer returned by `as_ptr` does not carry any
669 /// lifetime information and the string is deallocated immediately after
670 /// the `CString::new("Hello").unwrap().as_ptr()` expression is evaluated.
671 /// To fix the problem, bind the string to a local variable:
674 /// use std::ffi::{CString};
676 /// let hello = CString::new("Hello").unwrap();
677 /// let ptr = hello.as_ptr();
679 /// // `ptr` is valid because `hello` is in scope
683 #[stable(feature = "rust1", since = "1.0.0")]
684 pub fn as_ptr(&self) -> *const c_char {
688 /// Converts this C string to a byte slice.
690 /// This function will calculate the length of this string (which normally
691 /// requires a linear amount of work to be done) and then return the
692 /// resulting slice of `u8` elements.
694 /// The returned slice will **not** contain the trailing nul that this C
697 /// > **Note**: This method is currently implemented as a 0-cost cast, but
698 /// > it is planned to alter its definition in the future to perform the
699 /// > length calculation whenever this method is called.
700 #[stable(feature = "rust1", since = "1.0.0")]
701 pub fn to_bytes(&self) -> &[u8] {
702 let bytes = self.to_bytes_with_nul();
703 &bytes[..bytes.len() - 1]
706 /// Converts this C string to a byte slice containing the trailing 0 byte.
708 /// This function is the equivalent of `to_bytes` except that it will retain
709 /// the trailing nul instead of chopping it off.
711 /// > **Note**: This method is currently implemented as a 0-cost cast, but
712 /// > it is planned to alter its definition in the future to perform the
713 /// > length calculation whenever this method is called.
714 #[stable(feature = "rust1", since = "1.0.0")]
715 pub fn to_bytes_with_nul(&self) -> &[u8] {
716 unsafe { mem::transmute(&self.inner) }
719 /// Yields a `&str` slice if the `CStr` contains valid UTF-8.
721 /// This function will calculate the length of this string and check for
722 /// UTF-8 validity, and then return the `&str` if it's valid.
724 /// > **Note**: This method is currently implemented to check for validity
725 /// > after a 0-cost cast, but it is planned to alter its definition in the
726 /// > future to perform the length calculation in addition to the UTF-8
727 /// > check whenever this method is called.
728 #[stable(feature = "cstr_to_str", since = "1.4.0")]
729 pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
730 // NB: When CStr is changed to perform the length check in .to_bytes()
731 // instead of in from_ptr(), it may be worth considering if this should
732 // be rewritten to do the UTF-8 check inline with the length calculation
733 // instead of doing it afterwards.
734 str::from_utf8(self.to_bytes())
737 /// Converts a `CStr` into a `Cow<str>`.
739 /// This function will calculate the length of this string (which normally
740 /// requires a linear amount of work to be done) and then return the
741 /// resulting slice as a `Cow<str>`, replacing any invalid UTF-8 sequences
742 /// with `U+FFFD REPLACEMENT CHARACTER`.
744 /// > **Note**: This method is currently implemented to check for validity
745 /// > after a 0-cost cast, but it is planned to alter its definition in the
746 /// > future to perform the length calculation in addition to the UTF-8
747 /// > check whenever this method is called.
748 #[stable(feature = "cstr_to_str", since = "1.4.0")]
749 pub fn to_string_lossy(&self) -> Cow<str> {
750 String::from_utf8_lossy(self.to_bytes())
753 /// Converts a `Box<CStr>` into a `CString` without copying or allocating.
754 #[unstable(feature = "into_boxed_c_str", issue = "40380")]
755 pub fn into_c_string(self: Box<CStr>) -> CString {
756 unsafe { mem::transmute(self) }
760 #[stable(feature = "rust1", since = "1.0.0")]
761 impl PartialEq for CStr {
762 fn eq(&self, other: &CStr) -> bool {
763 self.to_bytes().eq(other.to_bytes())
766 #[stable(feature = "rust1", since = "1.0.0")]
768 #[stable(feature = "rust1", since = "1.0.0")]
769 impl PartialOrd for CStr {
770 fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
771 self.to_bytes().partial_cmp(&other.to_bytes())
774 #[stable(feature = "rust1", since = "1.0.0")]
776 fn cmp(&self, other: &CStr) -> Ordering {
777 self.to_bytes().cmp(&other.to_bytes())
781 #[stable(feature = "cstr_borrow", since = "1.3.0")]
782 impl ToOwned for CStr {
783 type Owned = CString;
785 fn to_owned(&self) -> CString {
786 CString { inner: self.to_bytes_with_nul().into() }
790 #[stable(feature = "cstring_asref", since = "1.7.0")]
791 impl<'a> From<&'a CStr> for CString {
792 fn from(s: &'a CStr) -> CString {
797 #[stable(feature = "cstring_asref", since = "1.7.0")]
798 impl ops::Index<ops::RangeFull> for CString {
802 fn index(&self, _index: ops::RangeFull) -> &CStr {
807 #[stable(feature = "cstring_asref", since = "1.7.0")]
808 impl AsRef<CStr> for CStr {
809 fn as_ref(&self) -> &CStr {
814 #[stable(feature = "cstring_asref", since = "1.7.0")]
815 impl AsRef<CStr> for CString {
816 fn as_ref(&self) -> &CStr {
825 use borrow::Cow::{Borrowed, Owned};
826 use hash::{Hash, Hasher};
827 use collections::hash_map::DefaultHasher;
832 let ptr = data.as_ptr() as *const c_char;
834 assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
835 assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
841 let s = CString::new("1234").unwrap();
842 assert_eq!(s.as_bytes(), b"1234");
843 assert_eq!(s.as_bytes_with_nul(), b"1234\0");
847 fn build_with_zero1() {
848 assert!(CString::new(&b"\0"[..]).is_err());
851 fn build_with_zero2() {
852 assert!(CString::new(vec![0]).is_err());
856 fn build_with_zero3() {
858 let s = CString::from_vec_unchecked(vec![0]);
859 assert_eq!(s.as_bytes(), b"\0");
865 let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
866 assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
872 let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
873 assert_eq!(s.to_bytes(), b"12");
874 assert_eq!(s.to_bytes_with_nul(), b"12\0");
880 let data = b"123\xE2\x80\xA6\0";
881 let ptr = data.as_ptr() as *const c_char;
883 assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
884 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
886 let data = b"123\xE2\0";
887 let ptr = data.as_ptr() as *const c_char;
889 assert!(CStr::from_ptr(ptr).to_str().is_err());
890 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
897 let ptr = data.as_ptr() as *const c_char;
899 let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
900 assert_eq!(owned.as_bytes_with_nul(), data);
905 let data = b"123\xE2\xFA\xA6\0";
906 let ptr = data.as_ptr() as *const c_char;
907 let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
909 let mut s = DefaultHasher::new();
911 let cstr_hash = s.finish();
912 let mut s = DefaultHasher::new();
913 CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
914 let cstring_hash = s.finish();
916 assert_eq!(cstr_hash, cstring_hash);
920 fn from_bytes_with_nul() {
922 let cstr = CStr::from_bytes_with_nul(data);
923 assert_eq!(cstr.map(CStr::to_bytes), Ok(&b"123"[..]));
924 let cstr = CStr::from_bytes_with_nul(data);
925 assert_eq!(cstr.map(CStr::to_bytes_with_nul), Ok(&b"123\0"[..]));
928 let cstr = CStr::from_bytes_with_nul(data);
929 let cstr_unchecked = CStr::from_bytes_with_nul_unchecked(data);
930 assert_eq!(cstr, Ok(cstr_unchecked));
935 fn from_bytes_with_nul_unterminated() {
937 let cstr = CStr::from_bytes_with_nul(data);
938 assert!(cstr.is_err());
942 fn from_bytes_with_nul_interior() {
943 let data = b"1\023\0";
944 let cstr = CStr::from_bytes_with_nul(data);
945 assert!(cstr.is_err());
950 let orig: &[u8] = b"Hello, world!\0";
951 let cstr = CStr::from_bytes_with_nul(orig).unwrap();
952 let boxed: Box<CStr> = Box::from(cstr);
953 let cstring = cstr.to_owned().into_boxed_c_str().into_c_string();
954 assert_eq!(cstr, &*boxed);
955 assert_eq!(&*boxed, &*cstring);
956 assert_eq!(&*cstring, cstr);
961 let boxed = <Box<CStr>>::default();
962 assert_eq!(boxed.to_bytes_with_nul(), &[0]);