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};
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,cstr_to_str)]
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>);
155 /// Creates a new C-compatible string from a container of bytes.
157 /// This method will consume the provided data and use the underlying bytes
158 /// to construct a new string, ensuring that there is a trailing 0 byte.
163 /// # #![feature(libc)]
164 /// extern crate libc;
165 /// use std::ffi::CString;
167 /// extern { fn puts(s: *const libc::c_char); }
170 /// let to_print = CString::new("Hello!").unwrap();
172 /// puts(to_print.as_ptr());
179 /// This function will return an error if the bytes yielded contain an
180 /// internal 0 byte. The error returned will contain the bytes as well as
181 /// the position of the nul byte.
182 #[stable(feature = "rust1", since = "1.0.0")]
183 pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
184 let bytes = t.into();
185 match bytes.iter().position(|x| *x == 0) {
186 Some(i) => Err(NulError(i, bytes)),
187 None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
191 /// Creates a C-compatible string from a byte vector without checking for
192 /// interior 0 bytes.
194 /// This method is equivalent to `new` except that no runtime assertion
195 /// is made that `v` contains no 0 bytes, and it requires an actual
196 /// byte vector, not anything that can be converted to one with Into.
197 #[stable(feature = "rust1", since = "1.0.0")]
198 pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
200 CString { inner: v.into_boxed_slice() }
203 /// Retakes ownership of a CString that was transferred to C.
205 /// The only appropriate argument is a pointer obtained by calling
206 /// `into_ptr`. The length of the string will be recalculated
207 /// using the pointer.
208 #[unstable(feature = "cstr_memory", reason = "recently added",
210 #[deprecated(since = "1.4.0", reason = "renamed to from_raw")]
211 pub unsafe fn from_ptr(ptr: *const libc::c_char) -> CString {
212 CString::from_raw(ptr as *mut _)
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_memory", reason = "recently added",
222 pub unsafe fn from_raw(ptr: *mut libc::c_char) -> CString {
223 let len = libc::strlen(ptr) + 1; // Including the NUL byte
224 let slice = slice::from_raw_parts(ptr, len as usize);
225 CString { inner: mem::transmute(slice) }
228 /// Transfers ownership of the string to a C caller.
230 /// The pointer must be returned to Rust and reconstituted using
231 /// `from_raw` to be properly deallocated. Specifically, one
232 /// should *not* use the standard C `free` function to deallocate
235 /// Failure to call `from_raw` will lead to a memory leak.
236 #[unstable(feature = "cstr_memory", reason = "recently added",
238 #[deprecated(since = "1.4.0", reason = "renamed to into_raw")]
239 pub fn into_ptr(self) -> *const libc::c_char {
240 self.into_raw() as *const _
243 /// Transfers ownership of the string to a C caller.
245 /// The pointer must be returned to Rust and reconstituted using
246 /// `from_ptr` to be properly deallocated. Specifically, one
247 /// should *not* use the standard C `free` function to deallocate
250 /// Failure to call `from_ptr` will lead to a memory leak.
251 #[unstable(feature = "cstr_memory", reason = "recently added",
253 pub fn into_raw(self) -> *mut libc::c_char {
254 Box::into_raw(self.inner) as *mut libc::c_char
257 /// Returns the contents of this `CString` as a slice of bytes.
259 /// The returned slice does **not** contain the trailing nul separator and
260 /// it is guaranteed to not have any interior nul bytes.
261 #[stable(feature = "rust1", since = "1.0.0")]
262 pub fn as_bytes(&self) -> &[u8] {
263 &self.inner[..self.inner.len() - 1]
266 /// Equivalent to the `as_bytes` function except that the returned slice
267 /// includes the trailing nul byte.
268 #[stable(feature = "rust1", since = "1.0.0")]
269 pub fn as_bytes_with_nul(&self) -> &[u8] {
274 #[stable(feature = "rust1", since = "1.0.0")]
275 impl Deref for CString {
278 fn deref(&self) -> &CStr {
279 unsafe { mem::transmute(self.as_bytes_with_nul()) }
283 #[stable(feature = "rust1", since = "1.0.0")]
284 impl fmt::Debug for CString {
285 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
286 fmt::Debug::fmt(&**self, f)
290 #[stable(feature = "cstr_debug", since = "1.3.0")]
291 impl fmt::Debug for CStr {
292 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
293 try!(write!(f, "\""));
294 for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
295 try!(f.write_char(byte as char));
301 #[stable(feature = "cstr_borrow", since = "1.3.0")]
302 impl Borrow<CStr> for CString {
303 fn borrow(&self) -> &CStr { self }
307 /// Returns the position of the nul byte in the slice that was provided to
309 #[stable(feature = "rust1", since = "1.0.0")]
310 pub fn nul_position(&self) -> usize { self.0 }
312 /// Consumes this error, returning the underlying vector of bytes which
313 /// generated the error in the first place.
314 #[stable(feature = "rust1", since = "1.0.0")]
315 pub fn into_vec(self) -> Vec<u8> { self.1 }
318 #[stable(feature = "rust1", since = "1.0.0")]
319 impl Error for NulError {
320 fn description(&self) -> &str { "nul byte found in data" }
323 #[stable(feature = "rust1", since = "1.0.0")]
324 impl fmt::Display for NulError {
325 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
326 write!(f, "nul byte found in provided data at position: {}", self.0)
330 #[stable(feature = "rust1", since = "1.0.0")]
331 impl From<NulError> for io::Error {
332 fn from(_: NulError) -> io::Error {
333 io::Error::new(io::ErrorKind::InvalidInput,
334 "data provided contains a nul byte")
339 /// Casts a raw C string to a safe C string wrapper.
341 /// This function will cast the provided `ptr` to the `CStr` wrapper which
342 /// allows inspection and interoperation of non-owned C strings. This method
343 /// is unsafe for a number of reasons:
345 /// * There is no guarantee to the validity of `ptr`
346 /// * The returned lifetime is not guaranteed to be the actual lifetime of
348 /// * There is no guarantee that the memory pointed to by `ptr` contains a
349 /// valid nul terminator byte at the end of the string.
351 /// > **Note**: This operation is intended to be a 0-cost cast but it is
352 /// > currently implemented with an up-front calculation of the length of
353 /// > the string. This is not guaranteed to always be the case.
358 /// # #![feature(libc)]
359 /// # extern crate libc;
361 /// use std::ffi::CStr;
366 /// fn my_string() -> *const libc::c_char;
370 /// let slice = CStr::from_ptr(my_string());
371 /// println!("string returned: {}",
372 /// str::from_utf8(slice.to_bytes()).unwrap());
376 #[stable(feature = "rust1", since = "1.0.0")]
377 pub unsafe fn from_ptr<'a>(ptr: *const libc::c_char) -> &'a CStr {
378 let len = libc::strlen(ptr);
379 mem::transmute(slice::from_raw_parts(ptr, len as usize + 1))
382 /// Returns the inner pointer to this C string.
384 /// The returned pointer will be valid for as long as `self` is and points
385 /// to a contiguous region of memory terminated with a 0 byte to represent
386 /// the end of the string.
387 #[stable(feature = "rust1", since = "1.0.0")]
388 pub fn as_ptr(&self) -> *const libc::c_char {
392 /// Converts this C string to a byte slice.
394 /// This function will calculate the length of this string (which normally
395 /// requires a linear amount of work to be done) and then return the
396 /// resulting slice of `u8` elements.
398 /// The returned slice will **not** contain the trailing nul that this C
401 /// > **Note**: This method is currently implemented as a 0-cost cast, but
402 /// > it is planned to alter its definition in the future to perform the
403 /// > length calculation whenever this method is called.
404 #[stable(feature = "rust1", since = "1.0.0")]
405 pub fn to_bytes(&self) -> &[u8] {
406 let bytes = self.to_bytes_with_nul();
407 &bytes[..bytes.len() - 1]
410 /// Converts this C string to a byte slice containing the trailing 0 byte.
412 /// This function is the equivalent of `to_bytes` except that it will retain
413 /// the trailing nul instead of chopping it off.
415 /// > **Note**: This method is currently implemented as a 0-cost cast, but
416 /// > it is planned to alter its definition in the future to perform the
417 /// > length calculation whenever this method is called.
418 #[stable(feature = "rust1", since = "1.0.0")]
419 pub fn to_bytes_with_nul(&self) -> &[u8] {
420 unsafe { mem::transmute(&self.inner) }
423 /// Yields a `&str` slice if the `CStr` contains valid UTF-8.
425 /// This function will calculate the length of this string and check for
426 /// UTF-8 validity, and then return the `&str` if it's valid.
428 /// > **Note**: This method is currently implemented to check for validity
429 /// > after a 0-cost cast, but it is planned to alter its definition in the
430 /// > future to perform the length calculation in addition to the UTF-8
431 /// > check whenever this method is called.
432 #[unstable(feature = "cstr_to_str", reason = "recently added",
434 pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
435 // NB: When CStr is changed to perform the length check in .to_bytes()
436 // instead of in from_ptr(), it may be worth considering if this should
437 // be rewritten to do the UTF-8 check inline with the length calculation
438 // instead of doing it afterwards.
439 str::from_utf8(self.to_bytes())
442 /// Converts a `CStr` into a `Cow<str>`.
444 /// This function will calculate the length of this string (which normally
445 /// requires a linear amount of work to be done) and then return the
446 /// resulting slice as a `Cow<str>`, replacing any invalid UTF-8 sequences
447 /// with `U+FFFD REPLACEMENT CHARACTER`.
449 /// > **Note**: This method is currently implemented to check for validity
450 /// > after a 0-cost cast, but it is planned to alter its definition in the
451 /// > future to perform the length calculation in addition to the UTF-8
452 /// > check whenever this method is called.
453 #[unstable(feature = "cstr_to_str", reason = "recently added",
455 pub fn to_string_lossy(&self) -> Cow<str> {
456 String::from_utf8_lossy(self.to_bytes())
460 #[stable(feature = "rust1", since = "1.0.0")]
461 impl PartialEq for CStr {
462 fn eq(&self, other: &CStr) -> bool {
463 self.to_bytes().eq(other.to_bytes())
466 #[stable(feature = "rust1", since = "1.0.0")]
468 #[stable(feature = "rust1", since = "1.0.0")]
469 impl PartialOrd for CStr {
470 fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
471 self.to_bytes().partial_cmp(&other.to_bytes())
474 #[stable(feature = "rust1", since = "1.0.0")]
476 fn cmp(&self, other: &CStr) -> Ordering {
477 self.to_bytes().cmp(&other.to_bytes())
481 #[stable(feature = "cstr_borrow", since = "1.3.0")]
482 impl ToOwned for CStr {
483 type Owned = CString;
485 fn to_owned(&self) -> CString {
486 unsafe { CString::from_vec_unchecked(self.to_bytes().to_vec()) }
495 use borrow::Cow::{Borrowed, Owned};
496 use hash::{SipHasher, Hash, Hasher};
501 let ptr = data.as_ptr() as *const libc::c_char;
503 assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
504 assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
510 let s = CString::new("1234").unwrap();
511 assert_eq!(s.as_bytes(), b"1234");
512 assert_eq!(s.as_bytes_with_nul(), b"1234\0");
516 fn build_with_zero1() {
517 assert!(CString::new(&b"\0"[..]).is_err());
520 fn build_with_zero2() {
521 assert!(CString::new(vec![0]).is_err());
525 fn build_with_zero3() {
527 let s = CString::from_vec_unchecked(vec![0]);
528 assert_eq!(s.as_bytes(), b"\0");
534 let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
535 assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
541 let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
542 assert_eq!(s.to_bytes(), b"12");
543 assert_eq!(s.to_bytes_with_nul(), b"12\0");
549 let data = b"123\xE2\x80\xA6\0";
550 let ptr = data.as_ptr() as *const libc::c_char;
552 assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
553 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
555 let data = b"123\xE2\0";
556 let ptr = data.as_ptr() as *const libc::c_char;
558 assert!(CStr::from_ptr(ptr).to_str().is_err());
559 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
566 let ptr = data.as_ptr() as *const libc::c_char;
568 let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
569 assert_eq!(owned.as_bytes_with_nul(), data);
574 let data = b"123\xE2\xFA\xA6\0";
575 let ptr = data.as_ptr() as *const libc::c_char;
576 let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
578 let mut s = SipHasher::new_with_keys(0, 0);
580 let cstr_hash = s.finish();
581 let mut s = SipHasher::new_with_keys(0, 0);
582 CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
583 let cstring_hash = s.finish();
585 assert_eq!(cstr_hash, cstring_hash);