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}
;
25 use result
::Result
::{self, Ok, Err}
;
27 use str::{self, Utf8Error}
;
31 /// A type representing an owned C-compatible string
33 /// This type serves the primary purpose of being able to safely generate a
34 /// C-compatible string from a Rust byte slice or vector. An instance of this
35 /// type is a static guarantee that the underlying bytes contain no interior 0
36 /// bytes and the final byte is 0.
38 /// A `CString` is created from either a byte slice or a byte vector. After
39 /// being created, a `CString` predominately inherits all of its methods from
40 /// the `Deref` implementation to `[c_char]`. Note that the underlying array
41 /// is represented as an array of `c_char` as opposed to `u8`. A `u8` slice
42 /// can be obtained with the `as_bytes` method. Slices produced from a `CString`
43 /// do *not* contain the trailing nul terminator unless otherwise specified.
49 /// use std::ffi::CString;
50 /// use std::os::raw::c_char;
53 /// fn my_printer(s: *const c_char);
56 /// let c_to_print = CString::new("Hello, world!").unwrap();
58 /// my_printer(c_to_print.as_ptr());
62 #[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
63 #[stable(feature = "rust1", since = "1.0.0")]
68 /// Representation of a borrowed C string.
70 /// This dynamically sized type is only safely constructed via a borrowed
71 /// version of an instance of `CString`. This type can be constructed from a raw
72 /// C string as well and represents a C string borrowed from another location.
74 /// Note that this structure is **not** `repr(C)` and is not recommended to be
75 /// placed in the signatures of FFI functions. Instead safe wrappers of FFI
76 /// functions may leverage the unsafe `from_ptr` constructor to provide a safe
77 /// interface to other consumers.
81 /// Inspecting a foreign C string
84 /// use std::ffi::CStr;
85 /// use std::os::raw::c_char;
87 /// extern { fn my_string() -> *const c_char; }
91 /// let slice = CStr::from_ptr(my_string());
92 /// println!("string length: {}", slice.to_bytes().len());
97 /// Passing a Rust-originating C string
100 /// use std::ffi::{CString, CStr};
101 /// use std::os::raw::c_char;
103 /// fn work(data: &CStr) {
104 /// extern { fn work_with(data: *const c_char); }
106 /// unsafe { work_with(data.as_ptr()) }
110 /// let s = CString::new("data data data data").unwrap();
115 /// Converting a foreign C string into a Rust `String`
118 /// use std::ffi::CStr;
119 /// use std::os::raw::c_char;
121 /// extern { fn my_string() -> *const c_char; }
123 /// fn my_string_safe() -> String {
125 /// CStr::from_ptr(my_string()).to_string_lossy().into_owned()
130 /// println!("string: {}", my_string_safe());
134 #[stable(feature = "rust1", since = "1.0.0")]
136 // FIXME: this should not be represented with a DST slice but rather with
137 // just a raw `c_char` along with some form of marker to make
138 // this an unsized type. Essentially `sizeof(&CStr)` should be the
139 // same as `sizeof(&c_char)` but `CStr` should be an unsized type.
143 /// An error returned from `CString::new` to indicate that a nul byte was found
144 /// in the vector provided.
145 #[derive(Clone, PartialEq, Debug)]
146 #[stable(feature = "rust1", since = "1.0.0")]
147 pub struct NulError(usize, Vec
<u8>);
149 /// An error returned from `CString::into_string` to indicate that a UTF-8 error
150 /// was encountered during the conversion.
151 #[derive(Clone, PartialEq, Debug)]
152 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
153 pub struct IntoStringError
{
159 /// Creates a new C-compatible string from a container of bytes.
161 /// This method will consume the provided data and use the underlying bytes
162 /// to construct a new string, ensuring that there is a trailing 0 byte.
167 /// use std::ffi::CString;
168 /// use std::os::raw::c_char;
170 /// extern { fn puts(s: *const c_char); }
173 /// let to_print = CString::new("Hello!").unwrap();
175 /// puts(to_print.as_ptr());
182 /// This function will return an error if the bytes yielded contain an
183 /// internal 0 byte. The error returned will contain the bytes as well as
184 /// the position of the nul byte.
185 #[stable(feature = "rust1", since = "1.0.0")]
186 pub fn new
<T
: Into
<Vec
<u8>>>(t
: T
) -> Result
<CString
, NulError
> {
190 fn _new(bytes
: Vec
<u8>) -> Result
<CString
, NulError
> {
191 match bytes
.iter().position(|x
| *x
== 0) {
192 Some(i
) => Err(NulError(i
, bytes
)),
193 None
=> Ok(unsafe { CString::from_vec_unchecked(bytes) }
),
197 /// Creates a C-compatible string from a byte vector without checking for
198 /// interior 0 bytes.
200 /// This method is equivalent to `new` except that no runtime assertion
201 /// is made that `v` contains no 0 bytes, and it requires an actual
202 /// byte vector, not anything that can be converted to one with Into.
203 #[stable(feature = "rust1", since = "1.0.0")]
204 pub unsafe fn from_vec_unchecked(mut v
: Vec
<u8>) -> CString
{
206 CString { inner: v.into_boxed_slice() }
209 /// Retakes ownership of a CString that was transferred to C.
211 /// The only appropriate argument is a pointer obtained by calling
212 /// `into_raw`. The length of the string will be recalculated
213 /// using the pointer.
214 #[unstable(feature = "cstr_memory2", reason = "recently added",
216 #[rustc_deprecated(since = "1.4.0", reason = "renamed to from_raw")]
217 pub unsafe fn from_ptr(ptr
: *const c_char
) -> CString
{
218 CString
::from_raw(ptr
as *mut _
)
221 /// Retakes ownership of a CString that was transferred to C.
223 /// The only appropriate argument is a pointer obtained by calling
224 /// `into_raw`. The length of the string will be recalculated
225 /// using 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 #[unstable(feature = "cstr_memory2", reason = "recently added",
243 #[rustc_deprecated(since = "1.4.0", reason = "renamed to into_raw")]
244 pub fn into_ptr(self) -> *const c_char
{
245 self.into_raw() as *const _
248 /// Transfers ownership of the string to a C caller.
250 /// The pointer must be returned to Rust and reconstituted using
251 /// `from_raw` to be properly deallocated. Specifically, one
252 /// should *not* use the standard C `free` function to deallocate
255 /// Failure to call `from_raw` will lead to a memory leak.
256 #[stable(feature = "cstr_memory", since = "1.4.0")]
257 pub fn into_raw(self) -> *mut c_char
{
258 Box
::into_raw(self.inner
) as *mut c_char
261 /// Converts the `CString` into a `String` if it contains valid Unicode data.
263 /// On failure, ownership of the original `CString` is returned.
264 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
265 pub fn into_string(self) -> Result
<String
, IntoStringError
> {
266 String
::from_utf8(self.into_bytes())
267 .map_err(|e
| IntoStringError
{
268 error
: e
.utf8_error(),
269 inner
: unsafe { CString::from_vec_unchecked(e.into_bytes()) }
,
273 /// Returns the underlying byte buffer.
275 /// The returned buffer does **not** contain the trailing nul separator and
276 /// it is guaranteed to not have any interior nul bytes.
277 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
278 pub fn into_bytes(self) -> Vec
<u8> {
279 // FIXME: Once this method becomes stable, add an `impl Into<Vec<u8>> for CString`
280 let mut vec
= self.inner
.into_vec();
281 let _nul
= vec
.pop();
282 debug_assert_eq
!(_nul
, Some(0u8));
286 /// Equivalent to the `into_bytes` function except that the returned vector
287 /// includes the trailing nul byte.
288 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
289 pub fn into_bytes_with_nul(self) -> Vec
<u8> {
290 self.inner
.into_vec()
293 /// Returns the contents of this `CString` as a slice of bytes.
295 /// The returned slice does **not** contain the trailing nul separator and
296 /// it is guaranteed to not have any interior nul bytes.
297 #[stable(feature = "rust1", since = "1.0.0")]
298 pub fn as_bytes(&self) -> &[u8] {
299 &self.inner
[..self.inner
.len() - 1]
302 /// Equivalent to the `as_bytes` function except that the returned slice
303 /// includes the trailing nul byte.
304 #[stable(feature = "rust1", since = "1.0.0")]
305 pub fn as_bytes_with_nul(&self) -> &[u8] {
310 #[stable(feature = "rust1", since = "1.0.0")]
311 impl Deref
for CString
{
314 fn deref(&self) -> &CStr
{
315 unsafe { mem::transmute(self.as_bytes_with_nul()) }
319 #[stable(feature = "rust1", since = "1.0.0")]
320 impl fmt
::Debug
for CString
{
321 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
322 fmt
::Debug
::fmt(&**self, f
)
326 #[stable(feature = "cstr_debug", since = "1.3.0")]
327 impl fmt
::Debug
for CStr
{
328 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
329 try
!(write
!(f
, "\""));
330 for byte
in self.to_bytes().iter().flat_map(|&b
| ascii
::escape_default(b
)) {
331 try
!(f
.write_char(byte
as char));
337 #[stable(feature = "cstr_borrow", since = "1.3.0")]
338 impl Borrow
<CStr
> for CString
{
339 fn borrow(&self) -> &CStr { self }
343 /// Returns the position of the nul byte in the slice that was provided to
345 #[stable(feature = "rust1", since = "1.0.0")]
346 pub fn nul_position(&self) -> usize { self.0 }
348 /// Consumes this error, returning the underlying vector of bytes which
349 /// generated the error in the first place.
350 #[stable(feature = "rust1", since = "1.0.0")]
351 pub fn into_vec(self) -> Vec
<u8> { self.1 }
354 #[stable(feature = "rust1", since = "1.0.0")]
355 impl Error
for NulError
{
356 fn description(&self) -> &str { "nul byte found in data" }
359 #[stable(feature = "rust1", since = "1.0.0")]
360 impl fmt
::Display
for NulError
{
361 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
362 write
!(f
, "nul byte found in provided data at position: {}", self.0)
366 #[stable(feature = "rust1", since = "1.0.0")]
367 impl From
<NulError
> for io
::Error
{
368 fn from(_
: NulError
) -> io
::Error
{
369 io
::Error
::new(io
::ErrorKind
::InvalidInput
,
370 "data provided contains a nul byte")
374 impl IntoStringError
{
375 /// Consumes this error, returning original `CString` which generated the
377 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
378 pub fn into_cstring(self) -> CString
{
382 /// Access the underlying UTF-8 error that was the cause of this error.
383 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
384 pub fn utf8_error(&self) -> Utf8Error
{
389 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
390 impl Error
for IntoStringError
{
391 fn description(&self) -> &str {
392 Error
::description(&self.error
)
396 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
397 impl fmt
::Display
for IntoStringError
{
398 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
399 fmt
::Display
::fmt(&self.error
, f
)
404 /// Casts a raw C string to a safe C string wrapper.
406 /// This function will cast the provided `ptr` to the `CStr` wrapper which
407 /// allows inspection and interoperation of non-owned C strings. This method
408 /// is unsafe for a number of reasons:
410 /// * There is no guarantee to the validity of `ptr`
411 /// * The returned lifetime is not guaranteed to be the actual lifetime of
413 /// * There is no guarantee that the memory pointed to by `ptr` contains a
414 /// valid nul terminator byte at the end of the string.
416 /// > **Note**: This operation is intended to be a 0-cost cast but it is
417 /// > currently implemented with an up-front calculation of the length of
418 /// > the string. This is not guaranteed to always be the case.
424 /// use std::ffi::CStr;
425 /// use std::os::raw::c_char;
429 /// fn my_string() -> *const c_char;
433 /// let slice = CStr::from_ptr(my_string());
434 /// println!("string returned: {}",
435 /// str::from_utf8(slice.to_bytes()).unwrap());
439 #[stable(feature = "rust1", since = "1.0.0")]
440 pub unsafe fn from_ptr
<'a
>(ptr
: *const c_char
) -> &'a CStr
{
441 let len
= libc
::strlen(ptr
);
442 mem
::transmute(slice
::from_raw_parts(ptr
, len
as usize + 1))
445 /// Returns the inner pointer to this C string.
447 /// The returned pointer will be valid for as long as `self` is and points
448 /// to a contiguous region of memory terminated with a 0 byte to represent
449 /// the end of the string.
450 #[stable(feature = "rust1", since = "1.0.0")]
451 pub fn as_ptr(&self) -> *const c_char
{
455 /// Converts this C string to a byte slice.
457 /// This function will calculate the length of this string (which normally
458 /// requires a linear amount of work to be done) and then return the
459 /// resulting slice of `u8` elements.
461 /// The returned slice will **not** contain the trailing nul that this C
464 /// > **Note**: This method is currently implemented as a 0-cost cast, but
465 /// > it is planned to alter its definition in the future to perform the
466 /// > length calculation whenever this method is called.
467 #[stable(feature = "rust1", since = "1.0.0")]
468 pub fn to_bytes(&self) -> &[u8] {
469 let bytes
= self.to_bytes_with_nul();
470 &bytes
[..bytes
.len() - 1]
473 /// Converts this C string to a byte slice containing the trailing 0 byte.
475 /// This function is the equivalent of `to_bytes` except that it will retain
476 /// the trailing nul instead of chopping it off.
478 /// > **Note**: This method is currently implemented as a 0-cost cast, but
479 /// > it is planned to alter its definition in the future to perform the
480 /// > length calculation whenever this method is called.
481 #[stable(feature = "rust1", since = "1.0.0")]
482 pub fn to_bytes_with_nul(&self) -> &[u8] {
483 unsafe { mem::transmute(&self.inner) }
486 /// Yields a `&str` slice if the `CStr` contains valid UTF-8.
488 /// This function will calculate the length of this string and check for
489 /// UTF-8 validity, and then return the `&str` if it's valid.
491 /// > **Note**: This method is currently implemented to check for validity
492 /// > after a 0-cost cast, but it is planned to alter its definition in the
493 /// > future to perform the length calculation in addition to the UTF-8
494 /// > check whenever this method is called.
495 #[stable(feature = "cstr_to_str", since = "1.4.0")]
496 pub fn to_str(&self) -> Result
<&str, str::Utf8Error
> {
497 // NB: When CStr is changed to perform the length check in .to_bytes()
498 // instead of in from_ptr(), it may be worth considering if this should
499 // be rewritten to do the UTF-8 check inline with the length calculation
500 // instead of doing it afterwards.
501 str::from_utf8(self.to_bytes())
504 /// Converts a `CStr` into a `Cow<str>`.
506 /// This function will calculate the length of this string (which normally
507 /// requires a linear amount of work to be done) and then return the
508 /// resulting slice as a `Cow<str>`, replacing any invalid UTF-8 sequences
509 /// with `U+FFFD REPLACEMENT CHARACTER`.
511 /// > **Note**: This method is currently implemented to check for validity
512 /// > after a 0-cost cast, but it is planned to alter its definition in the
513 /// > future to perform the length calculation in addition to the UTF-8
514 /// > check whenever this method is called.
515 #[stable(feature = "cstr_to_str", since = "1.4.0")]
516 pub fn to_string_lossy(&self) -> Cow
<str> {
517 String
::from_utf8_lossy(self.to_bytes())
521 #[stable(feature = "rust1", since = "1.0.0")]
522 impl PartialEq
for CStr
{
523 fn eq(&self, other
: &CStr
) -> bool
{
524 self.to_bytes().eq(other
.to_bytes())
527 #[stable(feature = "rust1", since = "1.0.0")]
529 #[stable(feature = "rust1", since = "1.0.0")]
530 impl PartialOrd
for CStr
{
531 fn partial_cmp(&self, other
: &CStr
) -> Option
<Ordering
> {
532 self.to_bytes().partial_cmp(&other
.to_bytes())
535 #[stable(feature = "rust1", since = "1.0.0")]
537 fn cmp(&self, other
: &CStr
) -> Ordering
{
538 self.to_bytes().cmp(&other
.to_bytes())
542 #[stable(feature = "cstr_borrow", since = "1.3.0")]
543 impl ToOwned
for CStr
{
544 type Owned
= CString
;
546 fn to_owned(&self) -> CString
{
547 unsafe { CString::from_vec_unchecked(self.to_bytes().to_vec()) }
556 use borrow
::Cow
::{Borrowed, Owned}
;
557 use hash
::{SipHasher, Hash, Hasher}
;
562 let ptr
= data
.as_ptr() as *const c_char
;
564 assert_eq
!(CStr
::from_ptr(ptr
).to_bytes(), b
"123");
565 assert_eq
!(CStr
::from_ptr(ptr
).to_bytes_with_nul(), b
"123\0");
571 let s
= CString
::new("1234").unwrap();
572 assert_eq
!(s
.as_bytes(), b
"1234");
573 assert_eq
!(s
.as_bytes_with_nul(), b
"1234\0");
577 fn build_with_zero1() {
578 assert
!(CString
::new(&b
"\0"[..]).is_err());
581 fn build_with_zero2() {
582 assert
!(CString
::new(vec
![0]).is_err());
586 fn build_with_zero3() {
588 let s
= CString
::from_vec_unchecked(vec
![0]);
589 assert_eq
!(s
.as_bytes(), b
"\0");
595 let s
= CString
::new(&b
"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
596 assert_eq
!(format
!("{:?}", s
), r
#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
602 let s
= CStr
::from_ptr(b
"12\0".as_ptr() as *const _
);
603 assert_eq
!(s
.to_bytes(), b
"12");
604 assert_eq
!(s
.to_bytes_with_nul(), b
"12\0");
610 let data
= b
"123\xE2\x80\xA6\0";
611 let ptr
= data
.as_ptr() as *const c_char
;
613 assert_eq
!(CStr
::from_ptr(ptr
).to_str(), Ok("123…"));
614 assert_eq
!(CStr
::from_ptr(ptr
).to_string_lossy(), Borrowed("123…"));
616 let data
= b
"123\xE2\0";
617 let ptr
= data
.as_ptr() as *const c_char
;
619 assert
!(CStr
::from_ptr(ptr
).to_str().is_err());
620 assert_eq
!(CStr
::from_ptr(ptr
).to_string_lossy(), Owned
::<str>(format
!("123\u{FFFD}")));
627 let ptr
= data
.as_ptr() as *const c_char
;
629 let owned
= unsafe { CStr::from_ptr(ptr).to_owned() }
;
630 assert_eq
!(owned
.as_bytes_with_nul(), data
);
635 let data
= b
"123\xE2\xFA\xA6\0";
636 let ptr
= data
.as_ptr() as *const c_char
;
637 let cstr
: &'
static CStr
= unsafe { CStr::from_ptr(ptr) }
;
639 let mut s
= SipHasher
::new_with_keys(0, 0);
641 let cstr_hash
= s
.finish();
642 let mut s
= SipHasher
::new_with_keys(0, 0);
643 CString
::new(&data
[..data
.len() - 1]).unwrap().hash(&mut s
);
644 let cstring_hash
= s
.finish();
646 assert_eq
!(cstr_hash
, cstring_hash
);