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 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
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 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
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 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
252 pub fn into_bytes(self) -> Vec<u8> {
253 // FIXME: Once this method becomes stable, add an `impl Into<Vec<u8>> for CString`
254 let mut vec = self.inner.into_vec();
255 let _nul = vec.pop();
256 debug_assert_eq!(_nul, Some(0u8));
260 /// Equivalent to the `into_bytes` function except that the returned vector
261 /// includes the trailing nul byte.
262 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
263 pub fn into_bytes_with_nul(self) -> Vec<u8> {
264 self.inner.into_vec()
267 /// Returns the contents of this `CString` as a slice of bytes.
269 /// The returned slice does **not** contain the trailing nul separator and
270 /// it is guaranteed to not have any interior nul bytes.
271 #[stable(feature = "rust1", since = "1.0.0")]
272 pub fn as_bytes(&self) -> &[u8] {
273 &self.inner[..self.inner.len() - 1]
276 /// Equivalent to the `as_bytes` function except that the returned slice
277 /// includes the trailing nul byte.
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub fn as_bytes_with_nul(&self) -> &[u8] {
284 #[stable(feature = "rust1", since = "1.0.0")]
285 impl ops::Deref for CString {
288 fn deref(&self) -> &CStr {
289 unsafe { mem::transmute(self.as_bytes_with_nul()) }
293 #[stable(feature = "rust1", since = "1.0.0")]
294 impl fmt::Debug for CString {
295 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
296 fmt::Debug::fmt(&**self, f)
300 #[stable(feature = "cstr_debug", since = "1.3.0")]
301 impl fmt::Debug for CStr {
302 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
303 try!(write!(f, "\""));
304 for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
305 try!(f.write_char(byte as char));
311 #[stable(feature = "cstr_borrow", since = "1.3.0")]
312 impl Borrow<CStr> for CString {
313 fn borrow(&self) -> &CStr { self }
317 /// Returns the position of the nul byte in the slice that was provided to
319 #[stable(feature = "rust1", since = "1.0.0")]
320 pub fn nul_position(&self) -> usize { self.0 }
322 /// Consumes this error, returning the underlying vector of bytes which
323 /// generated the error in the first place.
324 #[stable(feature = "rust1", since = "1.0.0")]
325 pub fn into_vec(self) -> Vec<u8> { self.1 }
328 #[stable(feature = "rust1", since = "1.0.0")]
329 impl Error for NulError {
330 fn description(&self) -> &str { "nul byte found in data" }
333 #[stable(feature = "rust1", since = "1.0.0")]
334 impl fmt::Display for NulError {
335 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
336 write!(f, "nul byte found in provided data at position: {}", self.0)
340 #[stable(feature = "rust1", since = "1.0.0")]
341 impl From<NulError> for io::Error {
342 fn from(_: NulError) -> io::Error {
343 io::Error::new(io::ErrorKind::InvalidInput,
344 "data provided contains a nul byte")
348 impl IntoStringError {
349 /// Consumes this error, returning original `CString` which generated the
351 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
352 pub fn into_cstring(self) -> CString {
356 /// Access the underlying UTF-8 error that was the cause of this error.
357 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
358 pub fn utf8_error(&self) -> Utf8Error {
363 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
364 impl Error for IntoStringError {
365 fn description(&self) -> &str {
366 Error::description(&self.error)
370 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
371 impl fmt::Display for IntoStringError {
372 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
373 fmt::Display::fmt(&self.error, f)
378 /// Casts a raw C string to a safe C string wrapper.
380 /// This function will cast the provided `ptr` to the `CStr` wrapper which
381 /// allows inspection and interoperation of non-owned C strings. This method
382 /// is unsafe for a number of reasons:
384 /// * There is no guarantee to the validity of `ptr`
385 /// * The returned lifetime is not guaranteed to be the actual lifetime of
387 /// * There is no guarantee that the memory pointed to by `ptr` contains a
388 /// valid nul terminator byte at the end of the string.
390 /// > **Note**: This operation is intended to be a 0-cost cast but it is
391 /// > currently implemented with an up-front calculation of the length of
392 /// > the string. This is not guaranteed to always be the case.
398 /// use std::ffi::CStr;
399 /// use std::os::raw::c_char;
403 /// fn my_string() -> *const c_char;
407 /// let slice = CStr::from_ptr(my_string());
408 /// println!("string returned: {}",
409 /// str::from_utf8(slice.to_bytes()).unwrap());
413 #[stable(feature = "rust1", since = "1.0.0")]
414 pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
415 let len = libc::strlen(ptr);
416 mem::transmute(slice::from_raw_parts(ptr, len as usize + 1))
419 /// Returns the inner pointer to this C string.
421 /// The returned pointer will be valid for as long as `self` is and points
422 /// to a contiguous region of memory terminated with a 0 byte to represent
423 /// the end of the string.
424 #[stable(feature = "rust1", since = "1.0.0")]
425 pub fn as_ptr(&self) -> *const c_char {
429 /// Converts this C string to a byte slice.
431 /// This function will calculate the length of this string (which normally
432 /// requires a linear amount of work to be done) and then return the
433 /// resulting slice of `u8` elements.
435 /// The returned slice will **not** contain the trailing nul that this C
438 /// > **Note**: This method is currently implemented as a 0-cost cast, but
439 /// > it is planned to alter its definition in the future to perform the
440 /// > length calculation whenever this method is called.
441 #[stable(feature = "rust1", since = "1.0.0")]
442 pub fn to_bytes(&self) -> &[u8] {
443 let bytes = self.to_bytes_with_nul();
444 &bytes[..bytes.len() - 1]
447 /// Converts this C string to a byte slice containing the trailing 0 byte.
449 /// This function is the equivalent of `to_bytes` except that it will retain
450 /// the trailing nul instead of chopping it off.
452 /// > **Note**: This method is currently implemented as a 0-cost cast, but
453 /// > it is planned to alter its definition in the future to perform the
454 /// > length calculation whenever this method is called.
455 #[stable(feature = "rust1", since = "1.0.0")]
456 pub fn to_bytes_with_nul(&self) -> &[u8] {
457 unsafe { mem::transmute(&self.inner) }
460 /// Yields a `&str` slice if the `CStr` contains valid UTF-8.
462 /// This function will calculate the length of this string and check for
463 /// UTF-8 validity, and then return the `&str` if it's valid.
465 /// > **Note**: This method is currently implemented to check for validity
466 /// > after a 0-cost cast, but it is planned to alter its definition in the
467 /// > future to perform the length calculation in addition to the UTF-8
468 /// > check whenever this method is called.
469 #[stable(feature = "cstr_to_str", since = "1.4.0")]
470 pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
471 // NB: When CStr is changed to perform the length check in .to_bytes()
472 // instead of in from_ptr(), it may be worth considering if this should
473 // be rewritten to do the UTF-8 check inline with the length calculation
474 // instead of doing it afterwards.
475 str::from_utf8(self.to_bytes())
478 /// Converts a `CStr` into a `Cow<str>`.
480 /// This function will calculate the length of this string (which normally
481 /// requires a linear amount of work to be done) and then return the
482 /// resulting slice as a `Cow<str>`, replacing any invalid UTF-8 sequences
483 /// with `U+FFFD REPLACEMENT CHARACTER`.
485 /// > **Note**: This method is currently implemented to check for validity
486 /// > after a 0-cost cast, but it is planned to alter its definition in the
487 /// > future to perform the length calculation in addition to the UTF-8
488 /// > check whenever this method is called.
489 #[stable(feature = "cstr_to_str", since = "1.4.0")]
490 pub fn to_string_lossy(&self) -> Cow<str> {
491 String::from_utf8_lossy(self.to_bytes())
495 #[stable(feature = "rust1", since = "1.0.0")]
496 impl PartialEq for CStr {
497 fn eq(&self, other: &CStr) -> bool {
498 self.to_bytes().eq(other.to_bytes())
501 #[stable(feature = "rust1", since = "1.0.0")]
503 #[stable(feature = "rust1", since = "1.0.0")]
504 impl PartialOrd for CStr {
505 fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
506 self.to_bytes().partial_cmp(&other.to_bytes())
509 #[stable(feature = "rust1", since = "1.0.0")]
511 fn cmp(&self, other: &CStr) -> Ordering {
512 self.to_bytes().cmp(&other.to_bytes())
516 #[stable(feature = "cstr_borrow", since = "1.3.0")]
517 impl ToOwned for CStr {
518 type Owned = CString;
520 fn to_owned(&self) -> CString {
521 unsafe { CString::from_vec_unchecked(self.to_bytes().to_vec()) }
525 #[stable(feature = "cstring_asref", since = "1.7.0")]
526 impl<'a> From<&'a CStr> for CString {
527 fn from(s: &'a CStr) -> CString {
532 #[stable(feature = "cstring_asref", since = "1.7.0")]
533 impl ops::Index<ops::RangeFull> for CString {
537 fn index(&self, _index: ops::RangeFull) -> &CStr {
542 #[stable(feature = "cstring_asref", since = "1.7.0")]
543 impl AsRef<CStr> for CStr {
544 fn as_ref(&self) -> &CStr {
549 #[stable(feature = "cstring_asref", since = "1.7.0")]
550 impl AsRef<CStr> for CString {
551 fn as_ref(&self) -> &CStr {
561 use borrow::Cow::{Borrowed, Owned};
562 use hash::{SipHasher, Hash, Hasher};
567 let ptr = data.as_ptr() as *const c_char;
569 assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
570 assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
576 let s = CString::new("1234").unwrap();
577 assert_eq!(s.as_bytes(), b"1234");
578 assert_eq!(s.as_bytes_with_nul(), b"1234\0");
582 fn build_with_zero1() {
583 assert!(CString::new(&b"\0"[..]).is_err());
586 fn build_with_zero2() {
587 assert!(CString::new(vec![0]).is_err());
591 fn build_with_zero3() {
593 let s = CString::from_vec_unchecked(vec![0]);
594 assert_eq!(s.as_bytes(), b"\0");
600 let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
601 assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
607 let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
608 assert_eq!(s.to_bytes(), b"12");
609 assert_eq!(s.to_bytes_with_nul(), b"12\0");
615 let data = b"123\xE2\x80\xA6\0";
616 let ptr = data.as_ptr() as *const c_char;
618 assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
619 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
621 let data = b"123\xE2\0";
622 let ptr = data.as_ptr() as *const c_char;
624 assert!(CStr::from_ptr(ptr).to_str().is_err());
625 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
632 let ptr = data.as_ptr() as *const c_char;
634 let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
635 assert_eq!(owned.as_bytes_with_nul(), data);
640 let data = b"123\xE2\xFA\xA6\0";
641 let ptr = data.as_ptr() as *const c_char;
642 let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
644 let mut s = SipHasher::new_with_keys(0, 0);
646 let cstr_hash = s.finish();
647 let mut s = SipHasher::new_with_keys(0, 0);
648 CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
649 let cstring_hash = s.finish();
651 assert_eq!(cstr_hash, cstring_hash);