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());
63 #[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
64 #[stable(feature = "rust1", since = "1.0.0")]
69 /// Representation of a borrowed C string.
71 /// This dynamically sized type is only safely constructed via a borrowed
72 /// version of an instance of `CString`. This type can be constructed from a raw
73 /// C string as well and represents a C string borrowed from another location.
75 /// Note that this structure is **not** `repr(C)` and is not recommended to be
76 /// placed in the signatures of FFI functions. Instead safe wrappers of FFI
77 /// functions may leverage the unsafe `from_ptr` constructor to provide a safe
78 /// interface to other consumers.
82 /// Inspecting a foreign C string
85 /// use std::ffi::CStr;
86 /// use std::os::raw::c_char;
88 /// extern { fn my_string() -> *const c_char; }
92 /// let slice = CStr::from_ptr(my_string());
93 /// println!("string length: {}", slice.to_bytes().len());
98 /// Passing a Rust-originating C string
101 /// use std::ffi::{CString, CStr};
102 /// use std::os::raw::c_char;
104 /// fn work(data: &CStr) {
105 /// extern { fn work_with(data: *const c_char); }
107 /// unsafe { work_with(data.as_ptr()) }
111 /// let s = CString::new("data data data data").unwrap();
116 /// Converting a foreign C string into a Rust `String`
119 /// use std::ffi::CStr;
120 /// use std::os::raw::c_char;
122 /// extern { fn my_string() -> *const c_char; }
124 /// fn my_string_safe() -> String {
126 /// CStr::from_ptr(my_string()).to_string_lossy().into_owned()
131 /// println!("string: {}", my_string_safe());
135 #[stable(feature = "rust1", since = "1.0.0")]
137 // FIXME: this should not be represented with a DST slice but rather with
138 // just a raw `c_char` along with some form of marker to make
139 // this an unsized type. Essentially `sizeof(&CStr)` should be the
140 // same as `sizeof(&c_char)` but `CStr` should be an unsized type.
144 /// An error returned from `CString::new` to indicate that a nul byte was found
145 /// in the vector provided.
146 #[derive(Clone, PartialEq, Debug)]
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub struct NulError(usize, Vec<u8>);
150 /// An error returned from `CString::into_string` to indicate that a UTF-8 error
151 /// was encountered during the conversion.
152 #[derive(Clone, PartialEq, Debug)]
153 #[stable(feature = "cstring_into", since = "1.7.0")]
154 pub struct IntoStringError {
160 /// Creates a new C-compatible string from a container of bytes.
162 /// This method will consume the provided data and use the underlying bytes
163 /// to construct a new string, ensuring that there is a trailing 0 byte.
168 /// use std::ffi::CString;
169 /// use std::os::raw::c_char;
171 /// extern { fn puts(s: *const c_char); }
174 /// let to_print = CString::new("Hello!").unwrap();
176 /// puts(to_print.as_ptr());
183 /// This function will return an error if the bytes yielded contain an
184 /// internal 0 byte. The error returned will contain the bytes as well as
185 /// the position of the nul byte.
186 #[stable(feature = "rust1", since = "1.0.0")]
187 pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
191 fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
192 match memchr::memchr(0, &bytes) {
193 Some(i) => Err(NulError(i, bytes)),
194 None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
198 /// Creates a C-compatible string from a byte vector without checking for
199 /// interior 0 bytes.
201 /// This method is equivalent to `new` except that no runtime assertion
202 /// is made that `v` contains no 0 bytes, and it requires an actual
203 /// byte vector, not anything that can be converted to one with Into.
204 #[stable(feature = "rust1", since = "1.0.0")]
205 pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
207 CString { inner: v.into_boxed_slice() }
210 /// Retakes ownership of a CString that was transferred to C.
212 /// The only appropriate argument is a pointer obtained by calling
213 /// `into_raw`. The length of the string will be recalculated
214 /// using the pointer.
215 #[stable(feature = "cstr_memory", since = "1.4.0")]
216 pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
217 let len = libc::strlen(ptr) + 1; // Including the NUL byte
218 let slice = slice::from_raw_parts(ptr, len as usize);
219 CString { inner: mem::transmute(slice) }
222 /// Transfers ownership of the string to a C caller.
224 /// The pointer must be returned to Rust and reconstituted using
225 /// `from_raw` to be properly deallocated. Specifically, one
226 /// should *not* use the standard C `free` function to deallocate
229 /// Failure to call `from_raw` will lead to a memory leak.
230 #[stable(feature = "cstr_memory", since = "1.4.0")]
231 pub fn into_raw(self) -> *mut c_char {
232 Box::into_raw(self.inner) as *mut c_char
235 /// Converts the `CString` into a `String` if it contains valid Unicode data.
237 /// On failure, ownership of the original `CString` is returned.
238 #[stable(feature = "cstring_into", since = "1.7.0")]
239 pub fn into_string(self) -> Result<String, IntoStringError> {
240 String::from_utf8(self.into_bytes())
241 .map_err(|e| IntoStringError {
242 error: e.utf8_error(),
243 inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
247 /// Returns the underlying byte buffer.
249 /// The returned buffer does **not** contain the trailing nul separator and
250 /// it is guaranteed to not have any interior nul bytes.
251 #[stable(feature = "cstring_into", since = "1.7.0")]
252 pub fn into_bytes(self) -> Vec<u8> {
253 let mut vec = self.inner.into_vec();
254 let _nul = vec.pop();
255 debug_assert_eq!(_nul, Some(0u8));
259 /// Equivalent to the `into_bytes` function except that the returned vector
260 /// includes the trailing nul byte.
261 #[stable(feature = "cstring_into", since = "1.7.0")]
262 pub fn into_bytes_with_nul(self) -> Vec<u8> {
263 self.inner.into_vec()
266 /// Returns the contents of this `CString` as a slice of bytes.
268 /// The returned slice does **not** contain the trailing nul separator and
269 /// it is guaranteed to not have any interior nul bytes.
270 #[stable(feature = "rust1", since = "1.0.0")]
271 pub fn as_bytes(&self) -> &[u8] {
272 &self.inner[..self.inner.len() - 1]
275 /// Equivalent to the `as_bytes` function except that the returned slice
276 /// includes the trailing nul byte.
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub fn as_bytes_with_nul(&self) -> &[u8] {
283 #[stable(feature = "rust1", since = "1.0.0")]
284 impl ops::Deref for CString {
287 fn deref(&self) -> &CStr {
288 unsafe { mem::transmute(self.as_bytes_with_nul()) }
292 #[stable(feature = "rust1", since = "1.0.0")]
293 impl fmt::Debug for CString {
294 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
295 fmt::Debug::fmt(&**self, f)
299 #[stable(feature = "cstring_into", since = "1.7.0")]
300 impl From<CString> for Vec<u8> {
301 fn from(s: CString) -> Vec<u8> {
306 #[stable(feature = "cstr_debug", since = "1.3.0")]
307 impl fmt::Debug for CStr {
308 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
309 try!(write!(f, "\""));
310 for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
311 try!(f.write_char(byte as char));
317 #[stable(feature = "cstr_borrow", since = "1.3.0")]
318 impl Borrow<CStr> for CString {
319 fn borrow(&self) -> &CStr { self }
323 /// Returns the position of the nul byte in the slice that was provided to
325 #[stable(feature = "rust1", since = "1.0.0")]
326 pub fn nul_position(&self) -> usize { self.0 }
328 /// Consumes this error, returning the underlying vector of bytes which
329 /// generated the error in the first place.
330 #[stable(feature = "rust1", since = "1.0.0")]
331 pub fn into_vec(self) -> Vec<u8> { self.1 }
334 #[stable(feature = "rust1", since = "1.0.0")]
335 impl Error for NulError {
336 fn description(&self) -> &str { "nul byte found in data" }
339 #[stable(feature = "rust1", since = "1.0.0")]
340 impl fmt::Display for NulError {
341 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
342 write!(f, "nul byte found in provided data at position: {}", self.0)
346 #[stable(feature = "rust1", since = "1.0.0")]
347 impl From<NulError> for io::Error {
348 fn from(_: NulError) -> io::Error {
349 io::Error::new(io::ErrorKind::InvalidInput,
350 "data provided contains a nul byte")
354 impl IntoStringError {
355 /// Consumes this error, returning original `CString` which generated the
357 #[stable(feature = "cstring_into", since = "1.7.0")]
358 pub fn into_cstring(self) -> CString {
362 /// Access the underlying UTF-8 error that was the cause of this error.
363 #[stable(feature = "cstring_into", since = "1.7.0")]
364 pub fn utf8_error(&self) -> Utf8Error {
369 #[stable(feature = "cstring_into", since = "1.7.0")]
370 impl Error for IntoStringError {
371 fn description(&self) -> &str {
372 "C string contained non-utf8 bytes"
375 fn cause(&self) -> Option<&Error> {
380 #[stable(feature = "cstring_into", since = "1.7.0")]
381 impl fmt::Display for IntoStringError {
382 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
383 self.description().fmt(f)
388 /// Casts a raw C string to a safe C string wrapper.
390 /// This function will cast the provided `ptr` to the `CStr` wrapper which
391 /// allows inspection and interoperation of non-owned C strings. This method
392 /// is unsafe for a number of reasons:
394 /// * There is no guarantee to the validity of `ptr`
395 /// * The returned lifetime is not guaranteed to be the actual lifetime of
397 /// * There is no guarantee that the memory pointed to by `ptr` contains a
398 /// valid nul terminator byte at the end of the string.
400 /// > **Note**: This operation is intended to be a 0-cost cast but it is
401 /// > currently implemented with an up-front calculation of the length of
402 /// > the string. This is not guaranteed to always be the case.
408 /// use std::ffi::CStr;
409 /// use std::os::raw::c_char;
412 /// fn my_string() -> *const c_char;
416 /// let slice = CStr::from_ptr(my_string());
417 /// println!("string returned: {}", slice.to_str().unwrap());
421 #[stable(feature = "rust1", since = "1.0.0")]
422 pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
423 let len = libc::strlen(ptr);
424 mem::transmute(slice::from_raw_parts(ptr, len as usize + 1))
427 /// Returns the inner pointer to this C string.
429 /// The returned pointer will be valid for as long as `self` is and points
430 /// to a contiguous region of memory terminated with a 0 byte to represent
431 /// the end of the string.
432 #[stable(feature = "rust1", since = "1.0.0")]
433 pub fn as_ptr(&self) -> *const c_char {
437 /// Converts this C string to a byte slice.
439 /// This function will calculate the length of this string (which normally
440 /// requires a linear amount of work to be done) and then return the
441 /// resulting slice of `u8` elements.
443 /// The returned slice will **not** contain the trailing nul that this C
446 /// > **Note**: This method is currently implemented as a 0-cost cast, but
447 /// > it is planned to alter its definition in the future to perform the
448 /// > length calculation whenever this method is called.
449 #[stable(feature = "rust1", since = "1.0.0")]
450 pub fn to_bytes(&self) -> &[u8] {
451 let bytes = self.to_bytes_with_nul();
452 &bytes[..bytes.len() - 1]
455 /// Converts this C string to a byte slice containing the trailing 0 byte.
457 /// This function is the equivalent of `to_bytes` except that it will retain
458 /// the trailing nul instead of chopping it off.
460 /// > **Note**: This method is currently implemented as a 0-cost cast, but
461 /// > it is planned to alter its definition in the future to perform the
462 /// > length calculation whenever this method is called.
463 #[stable(feature = "rust1", since = "1.0.0")]
464 pub fn to_bytes_with_nul(&self) -> &[u8] {
465 unsafe { mem::transmute(&self.inner) }
468 /// Yields a `&str` slice if the `CStr` contains valid UTF-8.
470 /// This function will calculate the length of this string and check for
471 /// UTF-8 validity, and then return the `&str` if it's valid.
473 /// > **Note**: This method is currently implemented to check for validity
474 /// > after a 0-cost cast, but it is planned to alter its definition in the
475 /// > future to perform the length calculation in addition to the UTF-8
476 /// > check whenever this method is called.
477 #[stable(feature = "cstr_to_str", since = "1.4.0")]
478 pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
479 // NB: When CStr is changed to perform the length check in .to_bytes()
480 // instead of in from_ptr(), it may be worth considering if this should
481 // be rewritten to do the UTF-8 check inline with the length calculation
482 // instead of doing it afterwards.
483 str::from_utf8(self.to_bytes())
486 /// Converts a `CStr` into a `Cow<str>`.
488 /// This function will calculate the length of this string (which normally
489 /// requires a linear amount of work to be done) and then return the
490 /// resulting slice as a `Cow<str>`, replacing any invalid UTF-8 sequences
491 /// with `U+FFFD REPLACEMENT CHARACTER`.
493 /// > **Note**: This method is currently implemented to check for validity
494 /// > after a 0-cost cast, but it is planned to alter its definition in the
495 /// > future to perform the length calculation in addition to the UTF-8
496 /// > check whenever this method is called.
497 #[stable(feature = "cstr_to_str", since = "1.4.0")]
498 pub fn to_string_lossy(&self) -> Cow<str> {
499 String::from_utf8_lossy(self.to_bytes())
503 #[stable(feature = "rust1", since = "1.0.0")]
504 impl PartialEq for CStr {
505 fn eq(&self, other: &CStr) -> bool {
506 self.to_bytes().eq(other.to_bytes())
509 #[stable(feature = "rust1", since = "1.0.0")]
511 #[stable(feature = "rust1", since = "1.0.0")]
512 impl PartialOrd for CStr {
513 fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
514 self.to_bytes().partial_cmp(&other.to_bytes())
517 #[stable(feature = "rust1", since = "1.0.0")]
519 fn cmp(&self, other: &CStr) -> Ordering {
520 self.to_bytes().cmp(&other.to_bytes())
524 #[stable(feature = "cstr_borrow", since = "1.3.0")]
525 impl ToOwned for CStr {
526 type Owned = CString;
528 fn to_owned(&self) -> CString {
529 unsafe { CString::from_vec_unchecked(self.to_bytes().to_vec()) }
533 #[stable(feature = "cstring_asref", since = "1.7.0")]
534 impl<'a> From<&'a CStr> for CString {
535 fn from(s: &'a CStr) -> CString {
540 #[stable(feature = "cstring_asref", since = "1.7.0")]
541 impl ops::Index<ops::RangeFull> for CString {
545 fn index(&self, _index: ops::RangeFull) -> &CStr {
550 #[stable(feature = "cstring_asref", since = "1.7.0")]
551 impl AsRef<CStr> for CStr {
552 fn as_ref(&self) -> &CStr {
557 #[stable(feature = "cstring_asref", since = "1.7.0")]
558 impl AsRef<CStr> for CString {
559 fn as_ref(&self) -> &CStr {
569 use borrow::Cow::{Borrowed, Owned};
570 use hash::{SipHasher, Hash, Hasher};
575 let ptr = data.as_ptr() as *const c_char;
577 assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
578 assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
584 let s = CString::new("1234").unwrap();
585 assert_eq!(s.as_bytes(), b"1234");
586 assert_eq!(s.as_bytes_with_nul(), b"1234\0");
590 fn build_with_zero1() {
591 assert!(CString::new(&b"\0"[..]).is_err());
594 fn build_with_zero2() {
595 assert!(CString::new(vec![0]).is_err());
599 fn build_with_zero3() {
601 let s = CString::from_vec_unchecked(vec![0]);
602 assert_eq!(s.as_bytes(), b"\0");
608 let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
609 assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
615 let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
616 assert_eq!(s.to_bytes(), b"12");
617 assert_eq!(s.to_bytes_with_nul(), b"12\0");
623 let data = b"123\xE2\x80\xA6\0";
624 let ptr = data.as_ptr() as *const c_char;
626 assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
627 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
629 let data = b"123\xE2\0";
630 let ptr = data.as_ptr() as *const c_char;
632 assert!(CStr::from_ptr(ptr).to_str().is_err());
633 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
640 let ptr = data.as_ptr() as *const c_char;
642 let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
643 assert_eq!(owned.as_bytes_with_nul(), data);
648 let data = b"123\xE2\xFA\xA6\0";
649 let ptr = data.as_ptr() as *const c_char;
650 let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
652 let mut s = SipHasher::new_with_keys(0, 0);
654 let cstr_hash = s.finish();
655 let mut s = SipHasher::new_with_keys(0, 0);
656 CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
657 let cstring_hash = s.finish();
659 assert_eq!(cstr_hash, cstring_hash);