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, ToOwned, Borrow};
14 use convert::{Into, From};
15 use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
17 use fmt::{self, Write};
24 use option::Option::{self, Some, None};
26 use result::Result::{self, Ok, Err};
28 use str::{self, Utf8Error};
32 /// A type representing an owned C-compatible string
34 /// This type serves the primary purpose of being able to safely generate a
35 /// C-compatible string from a Rust byte slice or vector. An instance of this
36 /// type is a static guarantee that the underlying bytes contain no interior 0
37 /// bytes and the final byte is 0.
39 /// A `CString` is created from either a byte slice or a byte vector. After
40 /// being created, a `CString` predominately inherits all of its methods from
41 /// the `Deref` implementation to `[c_char]`. Note that the underlying array
42 /// is represented as an array of `c_char` as opposed to `u8`. A `u8` slice
43 /// can be obtained with the `as_bytes` method. Slices produced from a `CString`
44 /// do *not* contain the trailing nul terminator unless otherwise specified.
50 /// use std::ffi::CString;
51 /// use std::os::raw::c_char;
54 /// fn my_printer(s: *const c_char);
57 /// let c_to_print = CString::new("Hello, world!").unwrap();
59 /// my_printer(c_to_print.as_ptr());
66 /// `CString` is intended for working with traditional C-style strings
67 /// (a sequence of non-null bytes terminated by a single null byte); the
68 /// primary use case for these kinds of strings is interoperating with C-like
69 /// code. Often you will need to transfer ownership to/from that external
70 /// code. It is strongly recommended that you thoroughly read through the
71 /// documentation of `CString` before use, as improper ownership management
72 /// of `CString` instances can lead to invalid memory accesses, memory leaks,
73 /// and other memory errors.
75 #[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
76 #[stable(feature = "rust1", since = "1.0.0")]
81 /// Representation of a borrowed C string.
83 /// This dynamically sized type is only safely constructed via a borrowed
84 /// version of an instance of `CString`. This type can be constructed from a raw
85 /// C string as well and represents a C string borrowed from another location.
87 /// Note that this structure is **not** `repr(C)` and is not recommended to be
88 /// placed in the signatures of FFI functions. Instead safe wrappers of FFI
89 /// functions may leverage the unsafe `from_ptr` constructor to provide a safe
90 /// interface to other consumers.
94 /// Inspecting a foreign C string
97 /// use std::ffi::CStr;
98 /// use std::os::raw::c_char;
100 /// extern { fn my_string() -> *const c_char; }
103 /// let slice = CStr::from_ptr(my_string());
104 /// println!("string length: {}", slice.to_bytes().len());
108 /// Passing a Rust-originating C string
111 /// use std::ffi::{CString, CStr};
112 /// use std::os::raw::c_char;
114 /// fn work(data: &CStr) {
115 /// extern { fn work_with(data: *const c_char); }
117 /// unsafe { work_with(data.as_ptr()) }
120 /// let s = CString::new("data data data data").unwrap();
124 /// Converting a foreign C string into a Rust `String`
127 /// use std::ffi::CStr;
128 /// use std::os::raw::c_char;
130 /// extern { fn my_string() -> *const c_char; }
132 /// fn my_string_safe() -> String {
134 /// CStr::from_ptr(my_string()).to_string_lossy().into_owned()
138 /// println!("string: {}", my_string_safe());
141 #[stable(feature = "rust1", since = "1.0.0")]
143 // FIXME: this should not be represented with a DST slice but rather with
144 // just a raw `c_char` along with some form of marker to make
145 // this an unsized type. Essentially `sizeof(&CStr)` should be the
146 // same as `sizeof(&c_char)` but `CStr` should be an unsized type.
150 /// An error returned from `CString::new` to indicate that a nul byte was found
151 /// in the vector provided.
152 #[derive(Clone, PartialEq, Debug)]
153 #[stable(feature = "rust1", since = "1.0.0")]
154 pub struct NulError(usize, Vec<u8>);
156 /// An error returned from `CStr::from_bytes_with_nul` to indicate that a nul
157 /// byte was found too early in the slice provided or one wasn't found at all.
158 #[derive(Clone, PartialEq, Debug)]
159 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
160 pub struct FromBytesWithNulError { _a: () }
162 /// An error returned from `CString::into_string` to indicate that a UTF-8 error
163 /// was encountered during the conversion.
164 #[derive(Clone, PartialEq, Debug)]
165 #[stable(feature = "cstring_into", since = "1.7.0")]
166 pub struct IntoStringError {
172 /// Creates a new C-compatible string from a container of bytes.
174 /// This method will consume the provided data and use the underlying bytes
175 /// to construct a new string, ensuring that there is a trailing 0 byte.
180 /// use std::ffi::CString;
181 /// use std::os::raw::c_char;
183 /// extern { fn puts(s: *const c_char); }
185 /// let to_print = CString::new("Hello!").unwrap();
187 /// puts(to_print.as_ptr());
193 /// This function will return an error if the bytes yielded contain an
194 /// internal 0 byte. The error returned will contain the bytes as well as
195 /// the position of the nul byte.
196 #[stable(feature = "rust1", since = "1.0.0")]
197 pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
201 fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
202 match memchr::memchr(0, &bytes) {
203 Some(i) => Err(NulError(i, bytes)),
204 None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
208 /// Creates a C-compatible string from a byte vector without checking for
209 /// interior 0 bytes.
211 /// This method is equivalent to `new` except that no runtime assertion
212 /// is made that `v` contains no 0 bytes, and it requires an actual
213 /// byte vector, not anything that can be converted to one with Into.
214 #[stable(feature = "rust1", since = "1.0.0")]
215 pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
218 CString { inner: v.into_boxed_slice() }
221 /// Retakes ownership of a `CString` that was transferred to C.
223 /// This should only ever be called with a pointer that was earlier
224 /// obtained by calling `into_raw` on a `CString`. Additionally, the length
225 /// of the string will be recalculated from the pointer.
226 #[stable(feature = "cstr_memory", since = "1.4.0")]
227 pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
228 let len = libc::strlen(ptr) + 1; // Including the NUL byte
229 let slice = slice::from_raw_parts(ptr, len as usize);
230 CString { inner: mem::transmute(slice) }
233 /// Transfers ownership of the string to a C caller.
235 /// The pointer must be returned to Rust and reconstituted using
236 /// `from_raw` to be properly deallocated. Specifically, one
237 /// should *not* use the standard C `free` function to deallocate
240 /// Failure to call `from_raw` will lead to a memory leak.
241 #[stable(feature = "cstr_memory", since = "1.4.0")]
242 pub fn into_raw(self) -> *mut c_char {
243 Box::into_raw(self.inner) as *mut c_char
246 /// Converts the `CString` into a `String` if it contains valid Unicode data.
248 /// On failure, ownership of the original `CString` is returned.
249 #[stable(feature = "cstring_into", since = "1.7.0")]
250 pub fn into_string(self) -> Result<String, IntoStringError> {
251 String::from_utf8(self.into_bytes())
252 .map_err(|e| IntoStringError {
253 error: e.utf8_error(),
254 inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
258 /// Returns the underlying byte buffer.
260 /// The returned buffer does **not** contain the trailing nul separator and
261 /// it is guaranteed to not have any interior nul bytes.
262 #[stable(feature = "cstring_into", since = "1.7.0")]
263 pub fn into_bytes(self) -> Vec<u8> {
264 let mut vec = self.inner.into_vec();
265 let _nul = vec.pop();
266 debug_assert_eq!(_nul, Some(0u8));
270 /// Equivalent to the `into_bytes` function except that the returned vector
271 /// includes the trailing nul byte.
272 #[stable(feature = "cstring_into", since = "1.7.0")]
273 pub fn into_bytes_with_nul(self) -> Vec<u8> {
274 self.inner.into_vec()
277 /// Returns the contents of this `CString` as a slice of bytes.
279 /// The returned slice does **not** contain the trailing nul separator and
280 /// it is guaranteed to not have any interior nul bytes.
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub fn as_bytes(&self) -> &[u8] {
283 &self.inner[..self.inner.len() - 1]
286 /// Equivalent to the `as_bytes` function except that the returned slice
287 /// includes the trailing nul byte.
288 #[stable(feature = "rust1", since = "1.0.0")]
289 pub fn as_bytes_with_nul(&self) -> &[u8] {
294 #[stable(feature = "rust1", since = "1.0.0")]
295 impl ops::Deref for CString {
298 fn deref(&self) -> &CStr {
299 unsafe { mem::transmute(self.as_bytes_with_nul()) }
303 #[stable(feature = "rust1", since = "1.0.0")]
304 impl fmt::Debug for CString {
305 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
306 fmt::Debug::fmt(&**self, f)
310 #[stable(feature = "cstring_into", since = "1.7.0")]
311 impl From<CString> for Vec<u8> {
312 fn from(s: CString) -> Vec<u8> {
317 #[stable(feature = "cstr_debug", since = "1.3.0")]
318 impl fmt::Debug for CStr {
319 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
321 for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
322 f.write_char(byte as char)?;
328 #[stable(feature = "cstr_default", since = "1.10.0")]
329 impl<'a> Default for &'a CStr {
330 fn default() -> &'a CStr {
331 static SLICE: &'static [c_char] = &[0];
332 unsafe { CStr::from_ptr(SLICE.as_ptr()) }
336 #[stable(feature = "cstr_default", since = "1.10.0")]
337 impl Default for CString {
338 fn default() -> CString {
339 let a: &CStr = Default::default();
344 #[stable(feature = "cstr_borrow", since = "1.3.0")]
345 impl Borrow<CStr> for CString {
346 fn borrow(&self) -> &CStr { self }
350 /// Returns the position of the nul byte in the slice that was provided to
356 /// use std::ffi::CString;
358 /// let nul_error = CString::new("foo\0bar").unwrap_err();
359 /// assert_eq!(nul_error.nul_position(), 3);
361 /// let nul_error = CString::new("foo bar\0").unwrap_err();
362 /// assert_eq!(nul_error.nul_position(), 7);
364 #[stable(feature = "rust1", since = "1.0.0")]
365 pub fn nul_position(&self) -> usize { self.0 }
367 /// Consumes this error, returning the underlying vector of bytes which
368 /// generated the error in the first place.
373 /// use std::ffi::CString;
375 /// let nul_error = CString::new("foo\0bar").unwrap_err();
376 /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
378 #[stable(feature = "rust1", since = "1.0.0")]
379 pub fn into_vec(self) -> Vec<u8> { self.1 }
382 #[stable(feature = "rust1", since = "1.0.0")]
383 impl Error for NulError {
384 fn description(&self) -> &str { "nul byte found in data" }
387 #[stable(feature = "rust1", since = "1.0.0")]
388 impl fmt::Display for NulError {
389 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
390 write!(f, "nul byte found in provided data at position: {}", self.0)
394 #[stable(feature = "rust1", since = "1.0.0")]
395 impl From<NulError> for io::Error {
396 fn from(_: NulError) -> io::Error {
397 io::Error::new(io::ErrorKind::InvalidInput,
398 "data provided contains a nul byte")
402 impl IntoStringError {
403 /// Consumes this error, returning original `CString` which generated the
405 #[stable(feature = "cstring_into", since = "1.7.0")]
406 pub fn into_cstring(self) -> CString {
410 /// Access the underlying UTF-8 error that was the cause of this error.
411 #[stable(feature = "cstring_into", since = "1.7.0")]
412 pub fn utf8_error(&self) -> Utf8Error {
417 #[stable(feature = "cstring_into", since = "1.7.0")]
418 impl Error for IntoStringError {
419 fn description(&self) -> &str {
420 "C string contained non-utf8 bytes"
423 fn cause(&self) -> Option<&Error> {
428 #[stable(feature = "cstring_into", since = "1.7.0")]
429 impl fmt::Display for IntoStringError {
430 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
431 self.description().fmt(f)
436 /// Casts a raw C string to a safe C string wrapper.
438 /// This function will cast the provided `ptr` to the `CStr` wrapper which
439 /// allows inspection and interoperation of non-owned C strings. This method
440 /// is unsafe for a number of reasons:
442 /// * There is no guarantee to the validity of `ptr`
443 /// * The returned lifetime is not guaranteed to be the actual lifetime of
445 /// * There is no guarantee that the memory pointed to by `ptr` contains a
446 /// valid nul terminator byte at the end of the string.
448 /// > **Note**: This operation is intended to be a 0-cost cast but it is
449 /// > currently implemented with an up-front calculation of the length of
450 /// > the string. This is not guaranteed to always be the case.
456 /// use std::ffi::CStr;
457 /// use std::os::raw::c_char;
460 /// fn my_string() -> *const c_char;
464 /// let slice = CStr::from_ptr(my_string());
465 /// println!("string returned: {}", slice.to_str().unwrap());
469 #[stable(feature = "rust1", since = "1.0.0")]
470 pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
471 let len = libc::strlen(ptr);
472 mem::transmute(slice::from_raw_parts(ptr, len as usize + 1))
475 /// Creates a C string wrapper from a byte slice.
477 /// This function will cast the provided `bytes` to a `CStr` wrapper after
478 /// ensuring that it is null terminated and does not contain any interior
484 /// use std::ffi::CStr;
486 /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
487 /// assert!(cstr.is_ok());
489 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
490 pub fn from_bytes_with_nul(bytes: &[u8])
491 -> Result<&CStr, FromBytesWithNulError> {
492 if bytes.is_empty() || memchr::memchr(0, &bytes) != Some(bytes.len() - 1) {
493 Err(FromBytesWithNulError { _a: () })
495 Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) })
499 /// Unsafely creates a C string wrapper from a byte slice.
501 /// This function will cast the provided `bytes` to a `CStr` wrapper without
502 /// performing any sanity checks. The provided slice must be null terminated
503 /// and not contain any interior nul bytes.
508 /// use std::ffi::{CStr, CString};
511 /// let cstring = CString::new("hello").unwrap();
512 /// let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
513 /// assert_eq!(cstr, &*cstring);
516 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
517 pub unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
518 mem::transmute(bytes)
521 /// Returns the inner pointer to this C string.
523 /// The returned pointer will be valid for as long as `self` is and points
524 /// to a contiguous region of memory terminated with a 0 byte to represent
525 /// the end of the string.
529 /// It is your responsibility to make sure that the underlying memory is not
530 /// freed too early. For example, the following code will cause undefined
531 /// behaviour when `ptr` is used inside the `unsafe` block:
534 /// use std::ffi::{CString};
536 /// let ptr = CString::new("Hello").unwrap().as_ptr();
538 /// // `ptr` is dangling
543 /// This happens because the pointer returned by `as_ptr` does not carry any
544 /// lifetime information and the string is deallocated immediately after
545 /// the `CString::new("Hello").unwrap().as_ptr()` expression is evaluated.
546 /// To fix the problem, bind the string to a local variable:
549 /// use std::ffi::{CString};
551 /// let hello = CString::new("Hello").unwrap();
552 /// let ptr = hello.as_ptr();
554 /// // `ptr` is valid because `hello` is in scope
558 #[stable(feature = "rust1", since = "1.0.0")]
559 pub fn as_ptr(&self) -> *const c_char {
563 /// Converts this C string to a byte slice.
565 /// This function will calculate the length of this string (which normally
566 /// requires a linear amount of work to be done) and then return the
567 /// resulting slice of `u8` elements.
569 /// The returned slice will **not** contain the trailing nul that this C
572 /// > **Note**: This method is currently implemented as a 0-cost cast, but
573 /// > it is planned to alter its definition in the future to perform the
574 /// > length calculation whenever this method is called.
575 #[stable(feature = "rust1", since = "1.0.0")]
576 pub fn to_bytes(&self) -> &[u8] {
577 let bytes = self.to_bytes_with_nul();
578 &bytes[..bytes.len() - 1]
581 /// Converts this C string to a byte slice containing the trailing 0 byte.
583 /// This function is the equivalent of `to_bytes` except that it will retain
584 /// the trailing nul instead of chopping it off.
586 /// > **Note**: This method is currently implemented as a 0-cost cast, but
587 /// > it is planned to alter its definition in the future to perform the
588 /// > length calculation whenever this method is called.
589 #[stable(feature = "rust1", since = "1.0.0")]
590 pub fn to_bytes_with_nul(&self) -> &[u8] {
591 unsafe { mem::transmute(&self.inner) }
594 /// Yields a `&str` slice if the `CStr` contains valid UTF-8.
596 /// This function will calculate the length of this string and check for
597 /// UTF-8 validity, and then return the `&str` if it's valid.
599 /// > **Note**: This method is currently implemented to check for validity
600 /// > after a 0-cost cast, but it is planned to alter its definition in the
601 /// > future to perform the length calculation in addition to the UTF-8
602 /// > check whenever this method is called.
603 #[stable(feature = "cstr_to_str", since = "1.4.0")]
604 pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
605 // NB: When CStr is changed to perform the length check in .to_bytes()
606 // instead of in from_ptr(), it may be worth considering if this should
607 // be rewritten to do the UTF-8 check inline with the length calculation
608 // instead of doing it afterwards.
609 str::from_utf8(self.to_bytes())
612 /// Converts a `CStr` into a `Cow<str>`.
614 /// This function will calculate the length of this string (which normally
615 /// requires a linear amount of work to be done) and then return the
616 /// resulting slice as a `Cow<str>`, replacing any invalid UTF-8 sequences
617 /// with `U+FFFD REPLACEMENT CHARACTER`.
619 /// > **Note**: This method is currently implemented to check for validity
620 /// > after a 0-cost cast, but it is planned to alter its definition in the
621 /// > future to perform the length calculation in addition to the UTF-8
622 /// > check whenever this method is called.
623 #[stable(feature = "cstr_to_str", since = "1.4.0")]
624 pub fn to_string_lossy(&self) -> Cow<str> {
625 String::from_utf8_lossy(self.to_bytes())
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl PartialEq for CStr {
631 fn eq(&self, other: &CStr) -> bool {
632 self.to_bytes().eq(other.to_bytes())
635 #[stable(feature = "rust1", since = "1.0.0")]
637 #[stable(feature = "rust1", since = "1.0.0")]
638 impl PartialOrd for CStr {
639 fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
640 self.to_bytes().partial_cmp(&other.to_bytes())
643 #[stable(feature = "rust1", since = "1.0.0")]
645 fn cmp(&self, other: &CStr) -> Ordering {
646 self.to_bytes().cmp(&other.to_bytes())
650 #[stable(feature = "cstr_borrow", since = "1.3.0")]
651 impl ToOwned for CStr {
652 type Owned = CString;
654 fn to_owned(&self) -> CString {
655 unsafe { CString::from_vec_unchecked(self.to_bytes().to_vec()) }
659 #[stable(feature = "cstring_asref", since = "1.7.0")]
660 impl<'a> From<&'a CStr> for CString {
661 fn from(s: &'a CStr) -> CString {
666 #[stable(feature = "cstring_asref", since = "1.7.0")]
667 impl ops::Index<ops::RangeFull> for CString {
671 fn index(&self, _index: ops::RangeFull) -> &CStr {
676 #[stable(feature = "cstring_asref", since = "1.7.0")]
677 impl AsRef<CStr> for CStr {
678 fn as_ref(&self) -> &CStr {
683 #[stable(feature = "cstring_asref", since = "1.7.0")]
684 impl AsRef<CStr> for CString {
685 fn as_ref(&self) -> &CStr {
695 use borrow::Cow::{Borrowed, Owned};
696 use hash::{SipHasher, Hash, Hasher};
701 let ptr = data.as_ptr() as *const c_char;
703 assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
704 assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
710 let s = CString::new("1234").unwrap();
711 assert_eq!(s.as_bytes(), b"1234");
712 assert_eq!(s.as_bytes_with_nul(), b"1234\0");
716 fn build_with_zero1() {
717 assert!(CString::new(&b"\0"[..]).is_err());
720 fn build_with_zero2() {
721 assert!(CString::new(vec![0]).is_err());
725 fn build_with_zero3() {
727 let s = CString::from_vec_unchecked(vec![0]);
728 assert_eq!(s.as_bytes(), b"\0");
734 let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
735 assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
741 let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
742 assert_eq!(s.to_bytes(), b"12");
743 assert_eq!(s.to_bytes_with_nul(), b"12\0");
749 let data = b"123\xE2\x80\xA6\0";
750 let ptr = data.as_ptr() as *const c_char;
752 assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
753 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
755 let data = b"123\xE2\0";
756 let ptr = data.as_ptr() as *const c_char;
758 assert!(CStr::from_ptr(ptr).to_str().is_err());
759 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
766 let ptr = data.as_ptr() as *const c_char;
768 let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
769 assert_eq!(owned.as_bytes_with_nul(), data);
774 let data = b"123\xE2\xFA\xA6\0";
775 let ptr = data.as_ptr() as *const c_char;
776 let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
778 let mut s = SipHasher::new_with_keys(0, 0);
780 let cstr_hash = s.finish();
781 let mut s = SipHasher::new_with_keys(0, 0);
782 CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
783 let cstring_hash = s.finish();
785 assert_eq!(cstr_hash, cstring_hash);
789 fn from_bytes_with_nul() {
791 let cstr = CStr::from_bytes_with_nul(data);
792 assert_eq!(cstr.map(CStr::to_bytes), Ok(&b"123"[..]));
793 let cstr = CStr::from_bytes_with_nul(data);
794 assert_eq!(cstr.map(CStr::to_bytes_with_nul), Ok(&b"123\0"[..]));
797 let cstr = CStr::from_bytes_with_nul(data);
798 let cstr_unchecked = CStr::from_bytes_with_nul_unchecked(data);
799 assert_eq!(cstr, Ok(cstr_unchecked));
804 fn from_bytes_with_nul_unterminated() {
806 let cstr = CStr::from_bytes_with_nul(data);
807 assert!(cstr.is_err());
811 fn from_bytes_with_nul_interior() {
812 let data = b"1\023\0";
813 let cstr = CStr::from_bytes_with_nul(data);
814 assert!(cstr.is_err());