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};
23 use option::Option::{self, Some, None};
24 use result::Result::{self, Ok, Err};
26 use str::{self, Utf8Error};
30 /// A type representing an owned C-compatible string
32 /// This type serves the primary purpose of being able to safely generate a
33 /// C-compatible string from a Rust byte slice or vector. An instance of this
34 /// type is a static guarantee that the underlying bytes contain no interior 0
35 /// bytes and the final byte is 0.
37 /// A `CString` is created from either a byte slice or a byte vector. After
38 /// being created, a `CString` predominately inherits all of its methods from
39 /// the `Deref` implementation to `[libc::c_char]`. Note that the underlying
40 /// array is represented as an array of `libc::c_char` as opposed to `u8`. A
41 /// `u8` slice can be obtained with the `as_bytes` method. Slices produced from
42 /// a `CString` do *not* contain the trailing nul terminator unless otherwise
48 /// # #![feature(libc)]
49 /// # extern crate libc;
51 /// use std::ffi::CString;
55 /// fn my_printer(s: *const libc::c_char);
58 /// let c_to_print = CString::new("Hello, world!").unwrap();
60 /// my_printer(c_to_print.as_ptr());
64 #[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
65 #[stable(feature = "rust1", since = "1.0.0")]
70 /// Representation of a borrowed C string.
72 /// This dynamically sized type is only safely constructed via a borrowed
73 /// version of an instance of `CString`. This type can be constructed from a raw
74 /// C string as well and represents a C string borrowed from another location.
76 /// Note that this structure is **not** `repr(C)` and is not recommended to be
77 /// placed in the signatures of FFI functions. Instead safe wrappers of FFI
78 /// functions may leverage the unsafe `from_ptr` constructor to provide a safe
79 /// interface to other consumers.
83 /// Inspecting a foreign C string
86 /// # #![feature(libc)]
87 /// extern crate libc;
88 /// use std::ffi::CStr;
90 /// extern { fn my_string() -> *const libc::c_char; }
94 /// let slice = CStr::from_ptr(my_string());
95 /// println!("string length: {}", slice.to_bytes().len());
100 /// Passing a Rust-originating C string
103 /// # #![feature(libc)]
104 /// extern crate libc;
105 /// use std::ffi::{CString, CStr};
107 /// fn work(data: &CStr) {
108 /// extern { fn work_with(data: *const libc::c_char); }
110 /// unsafe { work_with(data.as_ptr()) }
114 /// let s = CString::new("data data data data").unwrap();
119 /// Converting a foreign C string into a Rust `String`
122 /// # #![feature(libc)]
123 /// extern crate libc;
124 /// use std::ffi::CStr;
126 /// extern { fn my_string() -> *const libc::c_char; }
128 /// fn my_string_safe() -> String {
130 /// CStr::from_ptr(my_string()).to_string_lossy().into_owned()
135 /// println!("string: {}", my_string_safe());
139 #[stable(feature = "rust1", since = "1.0.0")]
141 // FIXME: this should not be represented with a DST slice but rather with
142 // just a raw `libc::c_char` along with some form of marker to make
143 // this an unsized type. Essentially `sizeof(&CStr)` should be the
144 // same as `sizeof(&c_char)` but `CStr` should be an unsized type.
145 inner: [libc::c_char]
148 /// An error returned from `CString::new` to indicate that a nul byte was found
149 /// in the vector provided.
150 #[derive(Clone, PartialEq, Debug)]
151 #[stable(feature = "rust1", since = "1.0.0")]
152 pub struct NulError(usize, Vec<u8>);
154 /// An error returned from `CString::into_string` to indicate that a UTF-8 error
155 /// was encountered during the conversion.
156 #[derive(Clone, PartialEq, Debug)]
157 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
158 pub struct IntoStringError {
164 /// Creates a new C-compatible string from a container of bytes.
166 /// This method will consume the provided data and use the underlying bytes
167 /// to construct a new string, ensuring that there is a trailing 0 byte.
172 /// # #![feature(libc)]
173 /// extern crate libc;
174 /// use std::ffi::CString;
176 /// extern { fn puts(s: *const libc::c_char); }
179 /// let to_print = CString::new("Hello!").unwrap();
181 /// puts(to_print.as_ptr());
188 /// This function will return an error if the bytes yielded contain an
189 /// internal 0 byte. The error returned will contain the bytes as well as
190 /// the position of the nul byte.
191 #[stable(feature = "rust1", since = "1.0.0")]
192 pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
196 fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
197 match bytes.iter().position(|x| *x == 0) {
198 Some(i) => Err(NulError(i, bytes)),
199 None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
203 /// Creates a C-compatible string from a byte vector without checking for
204 /// interior 0 bytes.
206 /// This method is equivalent to `new` except that no runtime assertion
207 /// is made that `v` contains no 0 bytes, and it requires an actual
208 /// byte vector, not anything that can be converted to one with Into.
209 #[stable(feature = "rust1", since = "1.0.0")]
210 pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
212 CString { inner: v.into_boxed_slice() }
215 /// Retakes ownership of a CString that was transferred to C.
217 /// The only appropriate argument is a pointer obtained by calling
218 /// `into_raw`. The length of the string will be recalculated
219 /// using the pointer.
220 #[unstable(feature = "cstr_memory2", reason = "recently added",
222 #[deprecated(since = "1.4.0", reason = "renamed to from_raw")]
223 pub unsafe fn from_ptr(ptr: *const libc::c_char) -> CString {
224 CString::from_raw(ptr as *mut _)
227 /// Retakes ownership of a CString that was transferred to C.
229 /// The only appropriate argument is a pointer obtained by calling
230 /// `into_raw`. The length of the string will be recalculated
231 /// using the pointer.
232 #[stable(feature = "cstr_memory", since = "1.4.0")]
233 pub unsafe fn from_raw(ptr: *mut libc::c_char) -> CString {
234 let len = libc::strlen(ptr) + 1; // Including the NUL byte
235 let slice = slice::from_raw_parts(ptr, len as usize);
236 CString { inner: mem::transmute(slice) }
239 /// Transfers ownership of the string to a C caller.
241 /// The pointer must be returned to Rust and reconstituted using
242 /// `from_raw` to be properly deallocated. Specifically, one
243 /// should *not* use the standard C `free` function to deallocate
246 /// Failure to call `from_raw` will lead to a memory leak.
247 #[unstable(feature = "cstr_memory2", reason = "recently added",
249 #[deprecated(since = "1.4.0", reason = "renamed to into_raw")]
250 pub fn into_ptr(self) -> *const libc::c_char {
251 self.into_raw() as *const _
254 /// Transfers ownership of the string to a C caller.
256 /// The pointer must be returned to Rust and reconstituted using
257 /// `from_raw` to be properly deallocated. Specifically, one
258 /// should *not* use the standard C `free` function to deallocate
261 /// Failure to call `from_raw` will lead to a memory leak.
262 #[stable(feature = "cstr_memory", since = "1.4.0")]
263 pub fn into_raw(self) -> *mut libc::c_char {
264 Box::into_raw(self.inner) as *mut libc::c_char
267 /// Converts the `CString` into a `String` if it contains valid Unicode data.
269 /// On failure, ownership of the original `CString` is returned.
270 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
271 pub fn into_string(self) -> Result<String, IntoStringError> {
272 String::from_utf8(self.into_bytes())
273 .map_err(|e| IntoStringError {
274 error: e.utf8_error(),
275 inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
279 /// Returns the underlying byte buffer.
281 /// The returned buffer does **not** contain the trailing nul separator and
282 /// it is guaranteed to not have any interior nul bytes.
283 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
284 pub fn into_bytes(self) -> Vec<u8> {
285 // FIXME: Once this method becomes stable, add an `impl Into<Vec<u8>> for CString`
286 let mut vec = self.inner.into_vec();
287 let _nul = vec.pop();
288 debug_assert_eq!(_nul, Some(0u8));
292 /// Equivalent to the `into_bytes` function except that the returned vector
293 /// includes the trailing nul byte.
294 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
295 pub fn into_bytes_with_nul(self) -> Vec<u8> {
296 self.inner.into_vec()
299 /// Returns the contents of this `CString` as a slice of bytes.
301 /// The returned slice does **not** contain the trailing nul separator and
302 /// it is guaranteed to not have any interior nul bytes.
303 #[stable(feature = "rust1", since = "1.0.0")]
304 pub fn as_bytes(&self) -> &[u8] {
305 &self.inner[..self.inner.len() - 1]
308 /// Equivalent to the `as_bytes` function except that the returned slice
309 /// includes the trailing nul byte.
310 #[stable(feature = "rust1", since = "1.0.0")]
311 pub fn as_bytes_with_nul(&self) -> &[u8] {
316 #[stable(feature = "rust1", since = "1.0.0")]
317 impl Deref for CString {
320 fn deref(&self) -> &CStr {
321 unsafe { mem::transmute(self.as_bytes_with_nul()) }
325 #[stable(feature = "rust1", since = "1.0.0")]
326 impl fmt::Debug for CString {
327 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
328 fmt::Debug::fmt(&**self, f)
332 #[stable(feature = "cstr_debug", since = "1.3.0")]
333 impl fmt::Debug for CStr {
334 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
335 try!(write!(f, "\""));
336 for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
337 try!(f.write_char(byte as char));
343 #[stable(feature = "cstr_borrow", since = "1.3.0")]
344 impl Borrow<CStr> for CString {
345 fn borrow(&self) -> &CStr { self }
349 /// Returns the position of the nul byte in the slice that was provided to
351 #[stable(feature = "rust1", since = "1.0.0")]
352 pub fn nul_position(&self) -> usize { self.0 }
354 /// Consumes this error, returning the underlying vector of bytes which
355 /// generated the error in the first place.
356 #[stable(feature = "rust1", since = "1.0.0")]
357 pub fn into_vec(self) -> Vec<u8> { self.1 }
360 #[stable(feature = "rust1", since = "1.0.0")]
361 impl Error for NulError {
362 fn description(&self) -> &str { "nul byte found in data" }
365 #[stable(feature = "rust1", since = "1.0.0")]
366 impl fmt::Display for NulError {
367 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
368 write!(f, "nul byte found in provided data at position: {}", self.0)
372 #[stable(feature = "rust1", since = "1.0.0")]
373 impl From<NulError> for io::Error {
374 fn from(_: NulError) -> io::Error {
375 io::Error::new(io::ErrorKind::InvalidInput,
376 "data provided contains a nul byte")
380 impl IntoStringError {
381 /// Consumes this error, returning original `CString` which generated the
383 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
384 pub fn into_cstring(self) -> CString {
388 /// Access the underlying UTF-8 error that was the cause of this error.
389 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
390 pub fn utf8_error(&self) -> Utf8Error {
395 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
396 impl Error for IntoStringError {
397 fn description(&self) -> &str {
398 Error::description(&self.error)
402 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
403 impl fmt::Display for IntoStringError {
404 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
405 fmt::Display::fmt(&self.error, f)
410 /// Casts a raw C string to a safe C string wrapper.
412 /// This function will cast the provided `ptr` to the `CStr` wrapper which
413 /// allows inspection and interoperation of non-owned C strings. This method
414 /// is unsafe for a number of reasons:
416 /// * There is no guarantee to the validity of `ptr`
417 /// * The returned lifetime is not guaranteed to be the actual lifetime of
419 /// * There is no guarantee that the memory pointed to by `ptr` contains a
420 /// valid nul terminator byte at the end of the string.
422 /// > **Note**: This operation is intended to be a 0-cost cast but it is
423 /// > currently implemented with an up-front calculation of the length of
424 /// > the string. This is not guaranteed to always be the case.
429 /// # #![feature(libc)]
430 /// # extern crate libc;
432 /// use std::ffi::CStr;
437 /// fn my_string() -> *const libc::c_char;
441 /// let slice = CStr::from_ptr(my_string());
442 /// println!("string returned: {}",
443 /// str::from_utf8(slice.to_bytes()).unwrap());
447 #[stable(feature = "rust1", since = "1.0.0")]
448 pub unsafe fn from_ptr<'a>(ptr: *const libc::c_char) -> &'a CStr {
449 let len = libc::strlen(ptr);
450 mem::transmute(slice::from_raw_parts(ptr, len as usize + 1))
453 /// Returns the inner pointer to this C string.
455 /// The returned pointer will be valid for as long as `self` is and points
456 /// to a contiguous region of memory terminated with a 0 byte to represent
457 /// the end of the string.
458 #[stable(feature = "rust1", since = "1.0.0")]
459 pub fn as_ptr(&self) -> *const libc::c_char {
463 /// Converts this C string to a byte slice.
465 /// This function will calculate the length of this string (which normally
466 /// requires a linear amount of work to be done) and then return the
467 /// resulting slice of `u8` elements.
469 /// The returned slice will **not** contain the trailing nul that this C
472 /// > **Note**: This method is currently implemented as a 0-cost cast, but
473 /// > it is planned to alter its definition in the future to perform the
474 /// > length calculation whenever this method is called.
475 #[stable(feature = "rust1", since = "1.0.0")]
476 pub fn to_bytes(&self) -> &[u8] {
477 let bytes = self.to_bytes_with_nul();
478 &bytes[..bytes.len() - 1]
481 /// Converts this C string to a byte slice containing the trailing 0 byte.
483 /// This function is the equivalent of `to_bytes` except that it will retain
484 /// the trailing nul instead of chopping it off.
486 /// > **Note**: This method is currently implemented as a 0-cost cast, but
487 /// > it is planned to alter its definition in the future to perform the
488 /// > length calculation whenever this method is called.
489 #[stable(feature = "rust1", since = "1.0.0")]
490 pub fn to_bytes_with_nul(&self) -> &[u8] {
491 unsafe { mem::transmute(&self.inner) }
494 /// Yields a `&str` slice if the `CStr` contains valid UTF-8.
496 /// This function will calculate the length of this string and check for
497 /// UTF-8 validity, and then return the `&str` if it's valid.
499 /// > **Note**: This method is currently implemented to check for validity
500 /// > after a 0-cost cast, but it is planned to alter its definition in the
501 /// > future to perform the length calculation in addition to the UTF-8
502 /// > check whenever this method is called.
503 #[stable(feature = "cstr_to_str", since = "1.4.0")]
504 pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
505 // NB: When CStr is changed to perform the length check in .to_bytes()
506 // instead of in from_ptr(), it may be worth considering if this should
507 // be rewritten to do the UTF-8 check inline with the length calculation
508 // instead of doing it afterwards.
509 str::from_utf8(self.to_bytes())
512 /// Converts a `CStr` into a `Cow<str>`.
514 /// This function will calculate the length of this string (which normally
515 /// requires a linear amount of work to be done) and then return the
516 /// resulting slice as a `Cow<str>`, replacing any invalid UTF-8 sequences
517 /// with `U+FFFD REPLACEMENT CHARACTER`.
519 /// > **Note**: This method is currently implemented to check for validity
520 /// > after a 0-cost cast, but it is planned to alter its definition in the
521 /// > future to perform the length calculation in addition to the UTF-8
522 /// > check whenever this method is called.
523 #[stable(feature = "cstr_to_str", since = "1.4.0")]
524 pub fn to_string_lossy(&self) -> Cow<str> {
525 String::from_utf8_lossy(self.to_bytes())
529 #[stable(feature = "rust1", since = "1.0.0")]
530 impl PartialEq for CStr {
531 fn eq(&self, other: &CStr) -> bool {
532 self.to_bytes().eq(other.to_bytes())
535 #[stable(feature = "rust1", since = "1.0.0")]
537 #[stable(feature = "rust1", since = "1.0.0")]
538 impl PartialOrd for CStr {
539 fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
540 self.to_bytes().partial_cmp(&other.to_bytes())
543 #[stable(feature = "rust1", since = "1.0.0")]
545 fn cmp(&self, other: &CStr) -> Ordering {
546 self.to_bytes().cmp(&other.to_bytes())
550 #[stable(feature = "cstr_borrow", since = "1.3.0")]
551 impl ToOwned for CStr {
552 type Owned = CString;
554 fn to_owned(&self) -> CString {
555 unsafe { CString::from_vec_unchecked(self.to_bytes().to_vec()) }
564 use borrow::Cow::{Borrowed, Owned};
565 use hash::{SipHasher, Hash, Hasher};
570 let ptr = data.as_ptr() as *const libc::c_char;
572 assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
573 assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
579 let s = CString::new("1234").unwrap();
580 assert_eq!(s.as_bytes(), b"1234");
581 assert_eq!(s.as_bytes_with_nul(), b"1234\0");
585 fn build_with_zero1() {
586 assert!(CString::new(&b"\0"[..]).is_err());
589 fn build_with_zero2() {
590 assert!(CString::new(vec![0]).is_err());
594 fn build_with_zero3() {
596 let s = CString::from_vec_unchecked(vec![0]);
597 assert_eq!(s.as_bytes(), b"\0");
603 let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
604 assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
610 let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
611 assert_eq!(s.to_bytes(), b"12");
612 assert_eq!(s.to_bytes_with_nul(), b"12\0");
618 let data = b"123\xE2\x80\xA6\0";
619 let ptr = data.as_ptr() as *const libc::c_char;
621 assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
622 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
624 let data = b"123\xE2\0";
625 let ptr = data.as_ptr() as *const libc::c_char;
627 assert!(CStr::from_ptr(ptr).to_str().is_err());
628 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
635 let ptr = data.as_ptr() as *const libc::c_char;
637 let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
638 assert_eq!(owned.as_bytes_with_nul(), data);
643 let data = b"123\xE2\xFA\xA6\0";
644 let ptr = data.as_ptr() as *const libc::c_char;
645 let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
647 let mut s = SipHasher::new_with_keys(0, 0);
649 let cstr_hash = s.finish();
650 let mut s = SipHasher::new_with_keys(0, 0);
651 CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
652 let cstring_hash = s.finish();
654 assert_eq!(cstr_hash, cstring_hash);