]> git.proxmox.com Git - rustc.git/blob - src/libstd/ffi/c_str.rs
New upstream version 1.15.0+dfsg1
[rustc.git] / src / libstd / ffi / c_str.rs
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.
4 //
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.
10
11 use ascii;
12 use borrow::{Cow, Borrow};
13 use cmp::Ordering;
14 use error::Error;
15 use fmt::{self, Write};
16 use io;
17 use libc;
18 use mem;
19 use memchr;
20 use ops;
21 use os::raw::c_char;
22 use ptr;
23 use slice;
24 use str::{self, Utf8Error};
25
26 /// A type representing an owned C-compatible string
27 ///
28 /// This type serves the primary purpose of being able to safely generate a
29 /// C-compatible string from a Rust byte slice or vector. An instance of this
30 /// type is a static guarantee that the underlying bytes contain no interior 0
31 /// bytes and the final byte is 0.
32 ///
33 /// A `CString` is created from either a byte slice or a byte vector. After
34 /// being created, a `CString` predominately inherits all of its methods from
35 /// the `Deref` implementation to `[c_char]`. Note that the underlying array
36 /// is represented as an array of `c_char` as opposed to `u8`. A `u8` slice
37 /// can be obtained with the `as_bytes` method. Slices produced from a `CString`
38 /// do *not* contain the trailing nul terminator unless otherwise specified.
39 ///
40 /// # Examples
41 ///
42 /// ```no_run
43 /// # fn main() {
44 /// use std::ffi::CString;
45 /// use std::os::raw::c_char;
46 ///
47 /// extern {
48 /// fn my_printer(s: *const c_char);
49 /// }
50 ///
51 /// let c_to_print = CString::new("Hello, world!").unwrap();
52 /// unsafe {
53 /// my_printer(c_to_print.as_ptr());
54 /// }
55 /// # }
56 /// ```
57 ///
58 /// # Safety
59 ///
60 /// `CString` is intended for working with traditional C-style strings
61 /// (a sequence of non-null bytes terminated by a single null byte); the
62 /// primary use case for these kinds of strings is interoperating with C-like
63 /// code. Often you will need to transfer ownership to/from that external
64 /// code. It is strongly recommended that you thoroughly read through the
65 /// documentation of `CString` before use, as improper ownership management
66 /// of `CString` instances can lead to invalid memory accesses, memory leaks,
67 /// and other memory errors.
68
69 #[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
70 #[stable(feature = "rust1", since = "1.0.0")]
71 pub struct CString {
72 // Invariant 1: the slice ends with a zero byte and has a length of at least one.
73 // Invariant 2: the slice contains only one zero byte.
74 // Improper usage of unsafe function can break Invariant 2, but not Invariant 1.
75 inner: Box<[u8]>,
76 }
77
78 /// Representation of a borrowed C string.
79 ///
80 /// This dynamically sized type is only safely constructed via a borrowed
81 /// version of an instance of `CString`. This type can be constructed from a raw
82 /// C string as well and represents a C string borrowed from another location.
83 ///
84 /// Note that this structure is **not** `repr(C)` and is not recommended to be
85 /// placed in the signatures of FFI functions. Instead safe wrappers of FFI
86 /// functions may leverage the unsafe `from_ptr` constructor to provide a safe
87 /// interface to other consumers.
88 ///
89 /// # Examples
90 ///
91 /// Inspecting a foreign C string
92 ///
93 /// ```no_run
94 /// use std::ffi::CStr;
95 /// use std::os::raw::c_char;
96 ///
97 /// extern { fn my_string() -> *const c_char; }
98 ///
99 /// unsafe {
100 /// let slice = CStr::from_ptr(my_string());
101 /// println!("string length: {}", slice.to_bytes().len());
102 /// }
103 /// ```
104 ///
105 /// Passing a Rust-originating C string
106 ///
107 /// ```no_run
108 /// use std::ffi::{CString, CStr};
109 /// use std::os::raw::c_char;
110 ///
111 /// fn work(data: &CStr) {
112 /// extern { fn work_with(data: *const c_char); }
113 ///
114 /// unsafe { work_with(data.as_ptr()) }
115 /// }
116 ///
117 /// let s = CString::new("data data data data").unwrap();
118 /// work(&s);
119 /// ```
120 ///
121 /// Converting a foreign C string into a Rust `String`
122 ///
123 /// ```no_run
124 /// use std::ffi::CStr;
125 /// use std::os::raw::c_char;
126 ///
127 /// extern { fn my_string() -> *const c_char; }
128 ///
129 /// fn my_string_safe() -> String {
130 /// unsafe {
131 /// CStr::from_ptr(my_string()).to_string_lossy().into_owned()
132 /// }
133 /// }
134 ///
135 /// println!("string: {}", my_string_safe());
136 /// ```
137 #[derive(Hash)]
138 #[stable(feature = "rust1", since = "1.0.0")]
139 pub struct CStr {
140 // FIXME: this should not be represented with a DST slice but rather with
141 // just a raw `c_char` along with some form of marker to make
142 // this an unsized type. Essentially `sizeof(&CStr)` should be the
143 // same as `sizeof(&c_char)` but `CStr` should be an unsized type.
144 inner: [c_char]
145 }
146
147 /// An error returned from `CString::new` to indicate that a nul byte was found
148 /// in the vector provided.
149 #[derive(Clone, PartialEq, Eq, Debug)]
150 #[stable(feature = "rust1", since = "1.0.0")]
151 pub struct NulError(usize, Vec<u8>);
152
153 /// An error returned from `CStr::from_bytes_with_nul` to indicate that a nul
154 /// byte was found too early in the slice provided or one wasn't found at all.
155 #[derive(Clone, PartialEq, Eq, Debug)]
156 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
157 pub struct FromBytesWithNulError { _a: () }
158
159 /// An error returned from `CString::into_string` to indicate that a UTF-8 error
160 /// was encountered during the conversion.
161 #[derive(Clone, PartialEq, Eq, Debug)]
162 #[stable(feature = "cstring_into", since = "1.7.0")]
163 pub struct IntoStringError {
164 inner: CString,
165 error: Utf8Error,
166 }
167
168 impl CString {
169 /// Creates a new C-compatible string from a container of bytes.
170 ///
171 /// This method will consume the provided data and use the underlying bytes
172 /// to construct a new string, ensuring that there is a trailing 0 byte.
173 ///
174 /// # Examples
175 ///
176 /// ```no_run
177 /// use std::ffi::CString;
178 /// use std::os::raw::c_char;
179 ///
180 /// extern { fn puts(s: *const c_char); }
181 ///
182 /// let to_print = CString::new("Hello!").unwrap();
183 /// unsafe {
184 /// puts(to_print.as_ptr());
185 /// }
186 /// ```
187 ///
188 /// # Errors
189 ///
190 /// This function will return an error if the bytes yielded contain an
191 /// internal 0 byte. The error returned will contain the bytes as well as
192 /// the position of the nul byte.
193 #[stable(feature = "rust1", since = "1.0.0")]
194 pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
195 Self::_new(t.into())
196 }
197
198 fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
199 match memchr::memchr(0, &bytes) {
200 Some(i) => Err(NulError(i, bytes)),
201 None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
202 }
203 }
204
205 /// Creates a C-compatible string from a byte vector without checking for
206 /// interior 0 bytes.
207 ///
208 /// This method is equivalent to `new` except that no runtime assertion
209 /// is made that `v` contains no 0 bytes, and it requires an actual
210 /// byte vector, not anything that can be converted to one with Into.
211 ///
212 /// # Examples
213 ///
214 /// ```
215 /// use std::ffi::CString;
216 ///
217 /// let raw = b"foo".to_vec();
218 /// unsafe {
219 /// let c_string = CString::from_vec_unchecked(raw);
220 /// }
221 /// ```
222 #[stable(feature = "rust1", since = "1.0.0")]
223 pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
224 v.reserve_exact(1);
225 v.push(0);
226 CString { inner: v.into_boxed_slice() }
227 }
228
229 /// Retakes ownership of a `CString` that was transferred to C.
230 ///
231 /// Additionally, the length of the string will be recalculated from the pointer.
232 ///
233 /// # Safety
234 ///
235 /// This should only ever be called with a pointer that was earlier
236 /// obtained by calling `into_raw` on a `CString`. Other usage (e.g. trying to take
237 /// ownership of a string that was allocated by foreign code) is likely to lead
238 /// to undefined behavior or allocator corruption.
239 #[stable(feature = "cstr_memory", since = "1.4.0")]
240 pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
241 let len = libc::strlen(ptr) + 1; // Including the NUL byte
242 let slice = slice::from_raw_parts(ptr, len as usize);
243 CString { inner: mem::transmute(slice) }
244 }
245
246 /// Transfers ownership of the string to a C caller.
247 ///
248 /// The pointer must be returned to Rust and reconstituted using
249 /// `from_raw` to be properly deallocated. Specifically, one
250 /// should *not* use the standard C `free` function to deallocate
251 /// this string.
252 ///
253 /// Failure to call `from_raw` will lead to a memory leak.
254 #[stable(feature = "cstr_memory", since = "1.4.0")]
255 pub fn into_raw(self) -> *mut c_char {
256 Box::into_raw(self.into_inner()) as *mut c_char
257 }
258
259 /// Converts the `CString` into a `String` if it contains valid Unicode data.
260 ///
261 /// On failure, ownership of the original `CString` is returned.
262 #[stable(feature = "cstring_into", since = "1.7.0")]
263 pub fn into_string(self) -> Result<String, IntoStringError> {
264 String::from_utf8(self.into_bytes())
265 .map_err(|e| IntoStringError {
266 error: e.utf8_error(),
267 inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
268 })
269 }
270
271 /// Returns the underlying byte buffer.
272 ///
273 /// The returned buffer does **not** contain the trailing nul separator and
274 /// it is guaranteed to not have any interior nul bytes.
275 #[stable(feature = "cstring_into", since = "1.7.0")]
276 pub fn into_bytes(self) -> Vec<u8> {
277 let mut vec = self.into_inner().into_vec();
278 let _nul = vec.pop();
279 debug_assert_eq!(_nul, Some(0u8));
280 vec
281 }
282
283 /// Equivalent to the `into_bytes` function except that the returned vector
284 /// includes the trailing nul byte.
285 #[stable(feature = "cstring_into", since = "1.7.0")]
286 pub fn into_bytes_with_nul(self) -> Vec<u8> {
287 self.into_inner().into_vec()
288 }
289
290 /// Returns the contents of this `CString` as a slice of bytes.
291 ///
292 /// The returned slice does **not** contain the trailing nul separator and
293 /// it is guaranteed to not have any interior nul bytes.
294 #[stable(feature = "rust1", since = "1.0.0")]
295 pub fn as_bytes(&self) -> &[u8] {
296 &self.inner[..self.inner.len() - 1]
297 }
298
299 /// Equivalent to the `as_bytes` function except that the returned slice
300 /// includes the trailing nul byte.
301 #[stable(feature = "rust1", since = "1.0.0")]
302 pub fn as_bytes_with_nul(&self) -> &[u8] {
303 &self.inner
304 }
305
306 // Bypass "move out of struct which implements `Drop` trait" restriction.
307 fn into_inner(self) -> Box<[u8]> {
308 unsafe {
309 let result = ptr::read(&self.inner);
310 mem::forget(self);
311 result
312 }
313 }
314 }
315
316 // Turns this `CString` into an empty string to prevent
317 // memory unsafe code from working by accident. Inline
318 // to prevent LLVM from optimizing it away in debug builds.
319 #[stable(feature = "cstring_drop", since = "1.13.0")]
320 impl Drop for CString {
321 #[inline]
322 fn drop(&mut self) {
323 unsafe { *self.inner.get_unchecked_mut(0) = 0; }
324 }
325 }
326
327 #[stable(feature = "rust1", since = "1.0.0")]
328 impl ops::Deref for CString {
329 type Target = CStr;
330
331 fn deref(&self) -> &CStr {
332 unsafe { mem::transmute(self.as_bytes_with_nul()) }
333 }
334 }
335
336 #[stable(feature = "rust1", since = "1.0.0")]
337 impl fmt::Debug for CString {
338 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
339 fmt::Debug::fmt(&**self, f)
340 }
341 }
342
343 #[stable(feature = "cstring_into", since = "1.7.0")]
344 impl From<CString> for Vec<u8> {
345 fn from(s: CString) -> Vec<u8> {
346 s.into_bytes()
347 }
348 }
349
350 #[stable(feature = "cstr_debug", since = "1.3.0")]
351 impl fmt::Debug for CStr {
352 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
353 write!(f, "\"")?;
354 for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
355 f.write_char(byte as char)?;
356 }
357 write!(f, "\"")
358 }
359 }
360
361 #[stable(feature = "cstr_default", since = "1.10.0")]
362 impl<'a> Default for &'a CStr {
363 fn default() -> &'a CStr {
364 static SLICE: &'static [c_char] = &[0];
365 unsafe { CStr::from_ptr(SLICE.as_ptr()) }
366 }
367 }
368
369 #[stable(feature = "cstr_default", since = "1.10.0")]
370 impl Default for CString {
371 /// Creates an empty `CString`.
372 fn default() -> CString {
373 let a: &CStr = Default::default();
374 a.to_owned()
375 }
376 }
377
378 #[stable(feature = "cstr_borrow", since = "1.3.0")]
379 impl Borrow<CStr> for CString {
380 fn borrow(&self) -> &CStr { self }
381 }
382
383 impl NulError {
384 /// Returns the position of the nul byte in the slice that was provided to
385 /// `CString::new`.
386 ///
387 /// # Examples
388 ///
389 /// ```
390 /// use std::ffi::CString;
391 ///
392 /// let nul_error = CString::new("foo\0bar").unwrap_err();
393 /// assert_eq!(nul_error.nul_position(), 3);
394 ///
395 /// let nul_error = CString::new("foo bar\0").unwrap_err();
396 /// assert_eq!(nul_error.nul_position(), 7);
397 /// ```
398 #[stable(feature = "rust1", since = "1.0.0")]
399 pub fn nul_position(&self) -> usize { self.0 }
400
401 /// Consumes this error, returning the underlying vector of bytes which
402 /// generated the error in the first place.
403 ///
404 /// # Examples
405 ///
406 /// ```
407 /// use std::ffi::CString;
408 ///
409 /// let nul_error = CString::new("foo\0bar").unwrap_err();
410 /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
411 /// ```
412 #[stable(feature = "rust1", since = "1.0.0")]
413 pub fn into_vec(self) -> Vec<u8> { self.1 }
414 }
415
416 #[stable(feature = "rust1", since = "1.0.0")]
417 impl Error for NulError {
418 fn description(&self) -> &str { "nul byte found in data" }
419 }
420
421 #[stable(feature = "rust1", since = "1.0.0")]
422 impl fmt::Display for NulError {
423 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
424 write!(f, "nul byte found in provided data at position: {}", self.0)
425 }
426 }
427
428 #[stable(feature = "rust1", since = "1.0.0")]
429 impl From<NulError> for io::Error {
430 fn from(_: NulError) -> io::Error {
431 io::Error::new(io::ErrorKind::InvalidInput,
432 "data provided contains a nul byte")
433 }
434 }
435
436 impl IntoStringError {
437 /// Consumes this error, returning original `CString` which generated the
438 /// error.
439 #[stable(feature = "cstring_into", since = "1.7.0")]
440 pub fn into_cstring(self) -> CString {
441 self.inner
442 }
443
444 /// Access the underlying UTF-8 error that was the cause of this error.
445 #[stable(feature = "cstring_into", since = "1.7.0")]
446 pub fn utf8_error(&self) -> Utf8Error {
447 self.error
448 }
449 }
450
451 #[stable(feature = "cstring_into", since = "1.7.0")]
452 impl Error for IntoStringError {
453 fn description(&self) -> &str {
454 "C string contained non-utf8 bytes"
455 }
456
457 fn cause(&self) -> Option<&Error> {
458 Some(&self.error)
459 }
460 }
461
462 #[stable(feature = "cstring_into", since = "1.7.0")]
463 impl fmt::Display for IntoStringError {
464 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
465 self.description().fmt(f)
466 }
467 }
468
469 impl CStr {
470 /// Casts a raw C string to a safe C string wrapper.
471 ///
472 /// This function will cast the provided `ptr` to the `CStr` wrapper which
473 /// allows inspection and interoperation of non-owned C strings. This method
474 /// is unsafe for a number of reasons:
475 ///
476 /// * There is no guarantee to the validity of `ptr`
477 /// * The returned lifetime is not guaranteed to be the actual lifetime of
478 /// `ptr`
479 /// * There is no guarantee that the memory pointed to by `ptr` contains a
480 /// valid nul terminator byte at the end of the string.
481 ///
482 /// > **Note**: This operation is intended to be a 0-cost cast but it is
483 /// > currently implemented with an up-front calculation of the length of
484 /// > the string. This is not guaranteed to always be the case.
485 ///
486 /// # Examples
487 ///
488 /// ```no_run
489 /// # fn main() {
490 /// use std::ffi::CStr;
491 /// use std::os::raw::c_char;
492 ///
493 /// extern {
494 /// fn my_string() -> *const c_char;
495 /// }
496 ///
497 /// unsafe {
498 /// let slice = CStr::from_ptr(my_string());
499 /// println!("string returned: {}", slice.to_str().unwrap());
500 /// }
501 /// # }
502 /// ```
503 #[stable(feature = "rust1", since = "1.0.0")]
504 pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
505 let len = libc::strlen(ptr);
506 mem::transmute(slice::from_raw_parts(ptr, len as usize + 1))
507 }
508
509 /// Creates a C string wrapper from a byte slice.
510 ///
511 /// This function will cast the provided `bytes` to a `CStr` wrapper after
512 /// ensuring that it is null terminated and does not contain any interior
513 /// nul bytes.
514 ///
515 /// # Examples
516 ///
517 /// ```
518 /// use std::ffi::CStr;
519 ///
520 /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
521 /// assert!(cstr.is_ok());
522 /// ```
523 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
524 pub fn from_bytes_with_nul(bytes: &[u8])
525 -> Result<&CStr, FromBytesWithNulError> {
526 if bytes.is_empty() || memchr::memchr(0, &bytes) != Some(bytes.len() - 1) {
527 Err(FromBytesWithNulError { _a: () })
528 } else {
529 Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) })
530 }
531 }
532
533 /// Unsafely creates a C string wrapper from a byte slice.
534 ///
535 /// This function will cast the provided `bytes` to a `CStr` wrapper without
536 /// performing any sanity checks. The provided slice must be null terminated
537 /// and not contain any interior nul bytes.
538 ///
539 /// # Examples
540 ///
541 /// ```
542 /// use std::ffi::{CStr, CString};
543 ///
544 /// unsafe {
545 /// let cstring = CString::new("hello").unwrap();
546 /// let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
547 /// assert_eq!(cstr, &*cstring);
548 /// }
549 /// ```
550 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
551 pub unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
552 mem::transmute(bytes)
553 }
554
555 /// Returns the inner pointer to this C string.
556 ///
557 /// The returned pointer will be valid for as long as `self` is and points
558 /// to a contiguous region of memory terminated with a 0 byte to represent
559 /// the end of the string.
560 ///
561 /// **WARNING**
562 ///
563 /// It is your responsibility to make sure that the underlying memory is not
564 /// freed too early. For example, the following code will cause undefined
565 /// behaviour when `ptr` is used inside the `unsafe` block:
566 ///
567 /// ```no_run
568 /// use std::ffi::{CString};
569 ///
570 /// let ptr = CString::new("Hello").unwrap().as_ptr();
571 /// unsafe {
572 /// // `ptr` is dangling
573 /// *ptr;
574 /// }
575 /// ```
576 ///
577 /// This happens because the pointer returned by `as_ptr` does not carry any
578 /// lifetime information and the string is deallocated immediately after
579 /// the `CString::new("Hello").unwrap().as_ptr()` expression is evaluated.
580 /// To fix the problem, bind the string to a local variable:
581 ///
582 /// ```no_run
583 /// use std::ffi::{CString};
584 ///
585 /// let hello = CString::new("Hello").unwrap();
586 /// let ptr = hello.as_ptr();
587 /// unsafe {
588 /// // `ptr` is valid because `hello` is in scope
589 /// *ptr;
590 /// }
591 /// ```
592 #[stable(feature = "rust1", since = "1.0.0")]
593 pub fn as_ptr(&self) -> *const c_char {
594 self.inner.as_ptr()
595 }
596
597 /// Converts this C string to a byte slice.
598 ///
599 /// This function will calculate the length of this string (which normally
600 /// requires a linear amount of work to be done) and then return the
601 /// resulting slice of `u8` elements.
602 ///
603 /// The returned slice will **not** contain the trailing nul that this C
604 /// string has.
605 ///
606 /// > **Note**: This method is currently implemented as a 0-cost cast, but
607 /// > it is planned to alter its definition in the future to perform the
608 /// > length calculation whenever this method is called.
609 #[stable(feature = "rust1", since = "1.0.0")]
610 pub fn to_bytes(&self) -> &[u8] {
611 let bytes = self.to_bytes_with_nul();
612 &bytes[..bytes.len() - 1]
613 }
614
615 /// Converts this C string to a byte slice containing the trailing 0 byte.
616 ///
617 /// This function is the equivalent of `to_bytes` except that it will retain
618 /// the trailing nul instead of chopping it off.
619 ///
620 /// > **Note**: This method is currently implemented as a 0-cost cast, but
621 /// > it is planned to alter its definition in the future to perform the
622 /// > length calculation whenever this method is called.
623 #[stable(feature = "rust1", since = "1.0.0")]
624 pub fn to_bytes_with_nul(&self) -> &[u8] {
625 unsafe { mem::transmute(&self.inner) }
626 }
627
628 /// Yields a `&str` slice if the `CStr` contains valid UTF-8.
629 ///
630 /// This function will calculate the length of this string and check for
631 /// UTF-8 validity, and then return the `&str` if it's valid.
632 ///
633 /// > **Note**: This method is currently implemented to check for validity
634 /// > after a 0-cost cast, but it is planned to alter its definition in the
635 /// > future to perform the length calculation in addition to the UTF-8
636 /// > check whenever this method is called.
637 #[stable(feature = "cstr_to_str", since = "1.4.0")]
638 pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
639 // NB: When CStr is changed to perform the length check in .to_bytes()
640 // instead of in from_ptr(), it may be worth considering if this should
641 // be rewritten to do the UTF-8 check inline with the length calculation
642 // instead of doing it afterwards.
643 str::from_utf8(self.to_bytes())
644 }
645
646 /// Converts a `CStr` into a `Cow<str>`.
647 ///
648 /// This function will calculate the length of this string (which normally
649 /// requires a linear amount of work to be done) and then return the
650 /// resulting slice as a `Cow<str>`, replacing any invalid UTF-8 sequences
651 /// with `U+FFFD REPLACEMENT CHARACTER`.
652 ///
653 /// > **Note**: This method is currently implemented to check for validity
654 /// > after a 0-cost cast, but it is planned to alter its definition in the
655 /// > future to perform the length calculation in addition to the UTF-8
656 /// > check whenever this method is called.
657 #[stable(feature = "cstr_to_str", since = "1.4.0")]
658 pub fn to_string_lossy(&self) -> Cow<str> {
659 String::from_utf8_lossy(self.to_bytes())
660 }
661 }
662
663 #[stable(feature = "rust1", since = "1.0.0")]
664 impl PartialEq for CStr {
665 fn eq(&self, other: &CStr) -> bool {
666 self.to_bytes().eq(other.to_bytes())
667 }
668 }
669 #[stable(feature = "rust1", since = "1.0.0")]
670 impl Eq for CStr {}
671 #[stable(feature = "rust1", since = "1.0.0")]
672 impl PartialOrd for CStr {
673 fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
674 self.to_bytes().partial_cmp(&other.to_bytes())
675 }
676 }
677 #[stable(feature = "rust1", since = "1.0.0")]
678 impl Ord for CStr {
679 fn cmp(&self, other: &CStr) -> Ordering {
680 self.to_bytes().cmp(&other.to_bytes())
681 }
682 }
683
684 #[stable(feature = "cstr_borrow", since = "1.3.0")]
685 impl ToOwned for CStr {
686 type Owned = CString;
687
688 fn to_owned(&self) -> CString {
689 CString { inner: self.to_bytes_with_nul().to_vec().into_boxed_slice() }
690 }
691 }
692
693 #[stable(feature = "cstring_asref", since = "1.7.0")]
694 impl<'a> From<&'a CStr> for CString {
695 fn from(s: &'a CStr) -> CString {
696 s.to_owned()
697 }
698 }
699
700 #[stable(feature = "cstring_asref", since = "1.7.0")]
701 impl ops::Index<ops::RangeFull> for CString {
702 type Output = CStr;
703
704 #[inline]
705 fn index(&self, _index: ops::RangeFull) -> &CStr {
706 self
707 }
708 }
709
710 #[stable(feature = "cstring_asref", since = "1.7.0")]
711 impl AsRef<CStr> for CStr {
712 fn as_ref(&self) -> &CStr {
713 self
714 }
715 }
716
717 #[stable(feature = "cstring_asref", since = "1.7.0")]
718 impl AsRef<CStr> for CString {
719 fn as_ref(&self) -> &CStr {
720 self
721 }
722 }
723
724 #[cfg(test)]
725 mod tests {
726 use super::*;
727 use os::raw::c_char;
728 use borrow::Cow::{Borrowed, Owned};
729 use hash::{Hash, Hasher};
730 use collections::hash_map::DefaultHasher;
731
732 #[test]
733 fn c_to_rust() {
734 let data = b"123\0";
735 let ptr = data.as_ptr() as *const c_char;
736 unsafe {
737 assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
738 assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
739 }
740 }
741
742 #[test]
743 fn simple() {
744 let s = CString::new("1234").unwrap();
745 assert_eq!(s.as_bytes(), b"1234");
746 assert_eq!(s.as_bytes_with_nul(), b"1234\0");
747 }
748
749 #[test]
750 fn build_with_zero1() {
751 assert!(CString::new(&b"\0"[..]).is_err());
752 }
753 #[test]
754 fn build_with_zero2() {
755 assert!(CString::new(vec![0]).is_err());
756 }
757
758 #[test]
759 fn build_with_zero3() {
760 unsafe {
761 let s = CString::from_vec_unchecked(vec![0]);
762 assert_eq!(s.as_bytes(), b"\0");
763 }
764 }
765
766 #[test]
767 fn formatted() {
768 let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
769 assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
770 }
771
772 #[test]
773 fn borrowed() {
774 unsafe {
775 let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
776 assert_eq!(s.to_bytes(), b"12");
777 assert_eq!(s.to_bytes_with_nul(), b"12\0");
778 }
779 }
780
781 #[test]
782 fn to_str() {
783 let data = b"123\xE2\x80\xA6\0";
784 let ptr = data.as_ptr() as *const c_char;
785 unsafe {
786 assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
787 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
788 }
789 let data = b"123\xE2\0";
790 let ptr = data.as_ptr() as *const c_char;
791 unsafe {
792 assert!(CStr::from_ptr(ptr).to_str().is_err());
793 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
794 }
795 }
796
797 #[test]
798 fn to_owned() {
799 let data = b"123\0";
800 let ptr = data.as_ptr() as *const c_char;
801
802 let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
803 assert_eq!(owned.as_bytes_with_nul(), data);
804 }
805
806 #[test]
807 fn equal_hash() {
808 let data = b"123\xE2\xFA\xA6\0";
809 let ptr = data.as_ptr() as *const c_char;
810 let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
811
812 let mut s = DefaultHasher::new();
813 cstr.hash(&mut s);
814 let cstr_hash = s.finish();
815 let mut s = DefaultHasher::new();
816 CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
817 let cstring_hash = s.finish();
818
819 assert_eq!(cstr_hash, cstring_hash);
820 }
821
822 #[test]
823 fn from_bytes_with_nul() {
824 let data = b"123\0";
825 let cstr = CStr::from_bytes_with_nul(data);
826 assert_eq!(cstr.map(CStr::to_bytes), Ok(&b"123"[..]));
827 let cstr = CStr::from_bytes_with_nul(data);
828 assert_eq!(cstr.map(CStr::to_bytes_with_nul), Ok(&b"123\0"[..]));
829
830 unsafe {
831 let cstr = CStr::from_bytes_with_nul(data);
832 let cstr_unchecked = CStr::from_bytes_with_nul_unchecked(data);
833 assert_eq!(cstr, Ok(cstr_unchecked));
834 }
835 }
836
837 #[test]
838 fn from_bytes_with_nul_unterminated() {
839 let data = b"123";
840 let cstr = CStr::from_bytes_with_nul(data);
841 assert!(cstr.is_err());
842 }
843
844 #[test]
845 fn from_bytes_with_nul_interior() {
846 let data = b"1\023\0";
847 let cstr = CStr::from_bytes_with_nul(data);
848 assert!(cstr.is_err());
849 }
850 }