]> git.lizzy.rs Git - rust.git/blob - src/libstd/ffi/c_str.rs
Add doc example for `CString::as_bytes`.
[rust.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. A [`u8`]
34 /// slice can be obtained with the `as_bytes` method. Slices produced from a
35 /// `CString` do *not* contain the trailing nul terminator unless otherwise
36 /// specified.
37 ///
38 /// [`u8`]: ../primitive.u8.html
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 /// [`from_ptr`]: #method.from_ptr
90 ///
91 /// # Examples
92 ///
93 /// Inspecting a foreign C string:
94 ///
95 /// ```no_run
96 /// use std::ffi::CStr;
97 /// use std::os::raw::c_char;
98 ///
99 /// extern { fn my_string() -> *const c_char; }
100 ///
101 /// unsafe {
102 ///     let slice = CStr::from_ptr(my_string());
103 ///     println!("string length: {}", slice.to_bytes().len());
104 /// }
105 /// ```
106 ///
107 /// Passing a Rust-originating C string:
108 ///
109 /// ```no_run
110 /// use std::ffi::{CString, CStr};
111 /// use std::os::raw::c_char;
112 ///
113 /// fn work(data: &CStr) {
114 ///     extern { fn work_with(data: *const c_char); }
115 ///
116 ///     unsafe { work_with(data.as_ptr()) }
117 /// }
118 ///
119 /// let s = CString::new("data data data data").unwrap();
120 /// work(&s);
121 /// ```
122 ///
123 /// Converting a foreign C string into a Rust [`String`]:
124 ///
125 /// [`String`]: ../string/struct.String.html
126 ///
127 /// ```no_run
128 /// use std::ffi::CStr;
129 /// use std::os::raw::c_char;
130 ///
131 /// extern { fn my_string() -> *const c_char; }
132 ///
133 /// fn my_string_safe() -> String {
134 ///     unsafe {
135 ///         CStr::from_ptr(my_string()).to_string_lossy().into_owned()
136 ///     }
137 /// }
138 ///
139 /// println!("string: {}", my_string_safe());
140 /// ```
141 #[derive(Hash)]
142 #[stable(feature = "rust1", since = "1.0.0")]
143 pub struct CStr {
144     // FIXME: this should not be represented with a DST slice but rather with
145     //        just a raw `c_char` along with some form of marker to make
146     //        this an unsized type. Essentially `sizeof(&CStr)` should be the
147     //        same as `sizeof(&c_char)` but `CStr` should be an unsized type.
148     inner: [c_char]
149 }
150
151 /// An error returned from [`CString::new`] to indicate that a nul byte was found
152 /// in the vector provided.
153 ///
154 /// [`CString::new`]: struct.CString.html#method.new
155 #[derive(Clone, PartialEq, Eq, Debug)]
156 #[stable(feature = "rust1", since = "1.0.0")]
157 pub struct NulError(usize, Vec<u8>);
158
159 /// An error returned from [`CStr::from_bytes_with_nul`] to indicate that a nul
160 /// byte was found too early in the slice provided or one wasn't found at all.
161 ///
162 /// [`CStr::from_bytes_with_nul`]: struct.CStr.html#method.from_bytes_with_nul
163 #[derive(Clone, PartialEq, Eq, Debug)]
164 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
165 pub struct FromBytesWithNulError {
166     kind: FromBytesWithNulErrorKind,
167 }
168
169 #[derive(Clone, PartialEq, Eq, Debug)]
170 enum FromBytesWithNulErrorKind {
171     InteriorNul(usize),
172     NotNulTerminated,
173 }
174
175 impl FromBytesWithNulError {
176     fn interior_nul(pos: usize) -> FromBytesWithNulError {
177         FromBytesWithNulError {
178             kind: FromBytesWithNulErrorKind::InteriorNul(pos),
179         }
180     }
181     fn not_nul_terminated() -> FromBytesWithNulError {
182         FromBytesWithNulError {
183             kind: FromBytesWithNulErrorKind::NotNulTerminated,
184         }
185     }
186 }
187
188 /// An error returned from [`CString::into_string`] to indicate that a UTF-8 error
189 /// was encountered during the conversion.
190 ///
191 /// [`CString::into_string`]: struct.CString.html#method.into_string
192 #[derive(Clone, PartialEq, Eq, Debug)]
193 #[stable(feature = "cstring_into", since = "1.7.0")]
194 pub struct IntoStringError {
195     inner: CString,
196     error: Utf8Error,
197 }
198
199 impl CString {
200     /// Creates a new C-compatible string from a container of bytes.
201     ///
202     /// This method will consume the provided data and use the underlying bytes
203     /// to construct a new string, ensuring that there is a trailing 0 byte.
204     ///
205     /// # Examples
206     ///
207     /// ```no_run
208     /// use std::ffi::CString;
209     /// use std::os::raw::c_char;
210     ///
211     /// extern { fn puts(s: *const c_char); }
212     ///
213     /// let to_print = CString::new("Hello!").unwrap();
214     /// unsafe {
215     ///     puts(to_print.as_ptr());
216     /// }
217     /// ```
218     ///
219     /// # Errors
220     ///
221     /// This function will return an error if the bytes yielded contain an
222     /// internal 0 byte. The error returned will contain the bytes as well as
223     /// the position of the nul byte.
224     #[stable(feature = "rust1", since = "1.0.0")]
225     pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
226         Self::_new(t.into())
227     }
228
229     fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
230         match memchr::memchr(0, &bytes) {
231             Some(i) => Err(NulError(i, bytes)),
232             None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
233         }
234     }
235
236     /// Creates a C-compatible string from a byte vector without checking for
237     /// interior 0 bytes.
238     ///
239     /// This method is equivalent to [`new`] except that no runtime assertion
240     /// is made that `v` contains no 0 bytes, and it requires an actual
241     /// byte vector, not anything that can be converted to one with Into.
242     ///
243     /// [`new`]: #method.new
244     ///
245     /// # Examples
246     ///
247     /// ```
248     /// use std::ffi::CString;
249     ///
250     /// let raw = b"foo".to_vec();
251     /// unsafe {
252     ///     let c_string = CString::from_vec_unchecked(raw);
253     /// }
254     /// ```
255     #[stable(feature = "rust1", since = "1.0.0")]
256     pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
257         v.reserve_exact(1);
258         v.push(0);
259         CString { inner: v.into_boxed_slice() }
260     }
261
262     /// Retakes ownership of a `CString` that was transferred to C.
263     ///
264     /// Additionally, the length of the string will be recalculated from the pointer.
265     ///
266     /// # Safety
267     ///
268     /// This should only ever be called with a pointer that was earlier
269     /// obtained by calling [`into_raw`] on a `CString`. Other usage (e.g. trying to take
270     /// ownership of a string that was allocated by foreign code) is likely to lead
271     /// to undefined behavior or allocator corruption.
272     ///
273     /// [`into_raw`]: #method.into_raw
274     #[stable(feature = "cstr_memory", since = "1.4.0")]
275     pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
276         let len = libc::strlen(ptr) + 1; // Including the NUL byte
277         let slice = slice::from_raw_parts(ptr, len as usize);
278         CString { inner: mem::transmute(slice) }
279     }
280
281     /// Transfers ownership of the string to a C caller.
282     ///
283     /// The pointer must be returned to Rust and reconstituted using
284     /// [`from_raw`] to be properly deallocated. Specifically, one
285     /// should *not* use the standard C `free` function to deallocate
286     /// this string.
287     ///
288     /// Failure to call [`from_raw`] will lead to a memory leak.
289     ///
290     /// [`from_raw`]: #method.from_raw
291     ///
292     /// # Examples
293     ///
294     /// ```
295     /// use std::ffi::CString;
296     ///
297     /// let c_string = CString::new("foo").unwrap();
298     ///
299     /// let ptr = c_string.into_raw();
300     ///
301     /// unsafe {
302     ///     assert_eq!(b'f', *ptr as u8);
303     ///     assert_eq!(b'o', *ptr.offset(1) as u8);
304     ///     assert_eq!(b'o', *ptr.offset(2) as u8);
305     ///     assert_eq!(b'\0', *ptr.offset(3) as u8);
306     ///
307     ///     // retake pointer to free memory
308     ///     let _ = CString::from_raw(ptr);
309     /// }
310     /// ```
311     #[stable(feature = "cstr_memory", since = "1.4.0")]
312     pub fn into_raw(self) -> *mut c_char {
313         Box::into_raw(self.into_inner()) as *mut c_char
314     }
315
316     /// Converts the `CString` into a [`String`] if it contains valid Unicode data.
317     ///
318     /// On failure, ownership of the original `CString` is returned.
319     ///
320     /// [`String`]: ../string/struct.String.html
321     #[stable(feature = "cstring_into", since = "1.7.0")]
322     pub fn into_string(self) -> Result<String, IntoStringError> {
323         String::from_utf8(self.into_bytes())
324             .map_err(|e| IntoStringError {
325                 error: e.utf8_error(),
326                 inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
327             })
328     }
329
330     /// Returns the underlying byte buffer.
331     ///
332     /// The returned buffer does **not** contain the trailing nul separator and
333     /// it is guaranteed to not have any interior nul bytes.
334     ///
335     /// # Examples
336     ///
337     /// ```
338     /// use std::ffi::CString;
339     ///
340     /// let c_string = CString::new("foo").unwrap();
341     /// let bytes = c_string.into_bytes();
342     /// assert_eq!(bytes, vec![b'f', b'o', b'o']);
343     /// ```
344     #[stable(feature = "cstring_into", since = "1.7.0")]
345     pub fn into_bytes(self) -> Vec<u8> {
346         let mut vec = self.into_inner().into_vec();
347         let _nul = vec.pop();
348         debug_assert_eq!(_nul, Some(0u8));
349         vec
350     }
351
352     /// Equivalent to the [`into_bytes`] function except that the returned vector
353     /// includes the trailing nul byte.
354     ///
355     /// [`into_bytes`]: #method.into_bytes
356     ///
357     /// # Examples
358     ///
359     /// ```
360     /// use std::ffi::CString;
361     ///
362     /// let c_string = CString::new("foo").unwrap();
363     /// let bytes = c_string.into_bytes_with_nul();
364     /// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
365     /// ```
366     #[stable(feature = "cstring_into", since = "1.7.0")]
367     pub fn into_bytes_with_nul(self) -> Vec<u8> {
368         self.into_inner().into_vec()
369     }
370
371     /// Returns the contents of this `CString` as a slice of bytes.
372     ///
373     /// The returned slice does **not** contain the trailing nul separator and
374     /// it is guaranteed to not have any interior nul bytes.
375     ///
376     /// # Examples
377     ///
378     /// ```
379     /// use std::ffi::CString;
380     ///
381     /// let c_string = CString::new("foo").unwrap();
382     /// let bytes = c_string.as_bytes();
383     /// assert_eq!(bytes, &[b'f', b'o', b'o']);
384     /// ```
385     #[stable(feature = "rust1", since = "1.0.0")]
386     pub fn as_bytes(&self) -> &[u8] {
387         &self.inner[..self.inner.len() - 1]
388     }
389
390     /// Equivalent to the [`as_bytes`] function except that the returned slice
391     /// includes the trailing nul byte.
392     ///
393     /// [`as_bytes`]: #method.as_bytes
394     ///
395     /// # Examples
396     ///
397     /// ```
398     /// use std::ffi::CString;
399     ///
400     /// let c_string = CString::new("foo").unwrap();
401     /// let bytes = c_string.as_bytes_with_nul();
402     /// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
403     /// ```
404     #[stable(feature = "rust1", since = "1.0.0")]
405     pub fn as_bytes_with_nul(&self) -> &[u8] {
406         &self.inner
407     }
408
409     /// Extracts a [`CStr`] slice containing the entire string.
410     ///
411     /// [`CStr`]: struct.CStr.html
412     #[unstable(feature = "as_c_str", issue = "40380")]
413     pub fn as_c_str(&self) -> &CStr {
414         &*self
415     }
416
417     /// Converts this `CString` into a boxed [`CStr`].
418     ///
419     /// [`CStr`]: struct.CStr.html
420     #[unstable(feature = "into_boxed_c_str", issue = "40380")]
421     pub fn into_boxed_c_str(self) -> Box<CStr> {
422         unsafe { mem::transmute(self.into_inner()) }
423     }
424
425     // Bypass "move out of struct which implements [`Drop`] trait" restriction.
426     ///
427     /// [`Drop`]: ../ops/trait.Drop.html
428     fn into_inner(self) -> Box<[u8]> {
429         unsafe {
430             let result = ptr::read(&self.inner);
431             mem::forget(self);
432             result
433         }
434     }
435 }
436
437 // Turns this `CString` into an empty string to prevent
438 // memory unsafe code from working by accident. Inline
439 // to prevent LLVM from optimizing it away in debug builds.
440 #[stable(feature = "cstring_drop", since = "1.13.0")]
441 impl Drop for CString {
442     #[inline]
443     fn drop(&mut self) {
444         unsafe { *self.inner.get_unchecked_mut(0) = 0; }
445     }
446 }
447
448 #[stable(feature = "rust1", since = "1.0.0")]
449 impl ops::Deref for CString {
450     type Target = CStr;
451
452     fn deref(&self) -> &CStr {
453         unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
454     }
455 }
456
457 #[stable(feature = "rust1", since = "1.0.0")]
458 impl fmt::Debug for CString {
459     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
460         fmt::Debug::fmt(&**self, f)
461     }
462 }
463
464 #[stable(feature = "cstring_into", since = "1.7.0")]
465 impl From<CString> for Vec<u8> {
466     fn from(s: CString) -> Vec<u8> {
467         s.into_bytes()
468     }
469 }
470
471 #[stable(feature = "cstr_debug", since = "1.3.0")]
472 impl fmt::Debug for CStr {
473     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
474         write!(f, "\"")?;
475         for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
476             f.write_char(byte as char)?;
477         }
478         write!(f, "\"")
479     }
480 }
481
482 #[stable(feature = "cstr_default", since = "1.10.0")]
483 impl<'a> Default for &'a CStr {
484     fn default() -> &'a CStr {
485         static SLICE: &'static [c_char] = &[0];
486         unsafe { CStr::from_ptr(SLICE.as_ptr()) }
487     }
488 }
489
490 #[stable(feature = "cstr_default", since = "1.10.0")]
491 impl Default for CString {
492     /// Creates an empty `CString`.
493     fn default() -> CString {
494         let a: &CStr = Default::default();
495         a.to_owned()
496     }
497 }
498
499 #[stable(feature = "cstr_borrow", since = "1.3.0")]
500 impl Borrow<CStr> for CString {
501     fn borrow(&self) -> &CStr { self }
502 }
503
504 #[stable(feature = "box_from_c_str", since = "1.17.0")]
505 impl<'a> From<&'a CStr> for Box<CStr> {
506     fn from(s: &'a CStr) -> Box<CStr> {
507         let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul());
508         unsafe { mem::transmute(boxed) }
509     }
510 }
511
512 #[stable(feature = "c_string_from_box", since = "1.18.0")]
513 impl From<Box<CStr>> for CString {
514     fn from(s: Box<CStr>) -> CString {
515         s.into_c_string()
516     }
517 }
518
519 #[stable(feature = "box_from_c_string", since = "1.18.0")]
520 impl Into<Box<CStr>> for CString {
521     fn into(self) -> Box<CStr> {
522         self.into_boxed_c_str()
523     }
524 }
525
526 #[stable(feature = "default_box_extra", since = "1.17.0")]
527 impl Default for Box<CStr> {
528     fn default() -> Box<CStr> {
529         let boxed: Box<[u8]> = Box::from([0]);
530         unsafe { mem::transmute(boxed) }
531     }
532 }
533
534 impl NulError {
535     /// Returns the position of the nul byte in the slice that was provided to
536     /// [`CString::new`].
537     ///
538     /// [`CString::new`]: struct.CString.html#method.new
539     ///
540     /// # Examples
541     ///
542     /// ```
543     /// use std::ffi::CString;
544     ///
545     /// let nul_error = CString::new("foo\0bar").unwrap_err();
546     /// assert_eq!(nul_error.nul_position(), 3);
547     ///
548     /// let nul_error = CString::new("foo bar\0").unwrap_err();
549     /// assert_eq!(nul_error.nul_position(), 7);
550     /// ```
551     #[stable(feature = "rust1", since = "1.0.0")]
552     pub fn nul_position(&self) -> usize { self.0 }
553
554     /// Consumes this error, returning the underlying vector of bytes which
555     /// generated the error in the first place.
556     ///
557     /// # Examples
558     ///
559     /// ```
560     /// use std::ffi::CString;
561     ///
562     /// let nul_error = CString::new("foo\0bar").unwrap_err();
563     /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
564     /// ```
565     #[stable(feature = "rust1", since = "1.0.0")]
566     pub fn into_vec(self) -> Vec<u8> { self.1 }
567 }
568
569 #[stable(feature = "rust1", since = "1.0.0")]
570 impl Error for NulError {
571     fn description(&self) -> &str { "nul byte found in data" }
572 }
573
574 #[stable(feature = "rust1", since = "1.0.0")]
575 impl fmt::Display for NulError {
576     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
577         write!(f, "nul byte found in provided data at position: {}", self.0)
578     }
579 }
580
581 #[stable(feature = "rust1", since = "1.0.0")]
582 impl From<NulError> for io::Error {
583     fn from(_: NulError) -> io::Error {
584         io::Error::new(io::ErrorKind::InvalidInput,
585                        "data provided contains a nul byte")
586     }
587 }
588
589 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
590 impl Error for FromBytesWithNulError {
591     fn description(&self) -> &str {
592         match self.kind {
593             FromBytesWithNulErrorKind::InteriorNul(..) =>
594                 "data provided contains an interior nul byte",
595             FromBytesWithNulErrorKind::NotNulTerminated =>
596                 "data provided is not nul terminated",
597         }
598     }
599 }
600
601 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
602 impl fmt::Display for FromBytesWithNulError {
603     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
604         f.write_str(self.description())?;
605         if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind {
606             write!(f, " at byte pos {}", pos)?;
607         }
608         Ok(())
609     }
610 }
611
612 impl IntoStringError {
613     /// Consumes this error, returning original [`CString`] which generated the
614     /// error.
615     ///
616     /// [`CString`]: struct.CString.html
617     #[stable(feature = "cstring_into", since = "1.7.0")]
618     pub fn into_cstring(self) -> CString {
619         self.inner
620     }
621
622     /// Access the underlying UTF-8 error that was the cause of this error.
623     #[stable(feature = "cstring_into", since = "1.7.0")]
624     pub fn utf8_error(&self) -> Utf8Error {
625         self.error
626     }
627 }
628
629 #[stable(feature = "cstring_into", since = "1.7.0")]
630 impl Error for IntoStringError {
631     fn description(&self) -> &str {
632         "C string contained non-utf8 bytes"
633     }
634
635     fn cause(&self) -> Option<&Error> {
636         Some(&self.error)
637     }
638 }
639
640 #[stable(feature = "cstring_into", since = "1.7.0")]
641 impl fmt::Display for IntoStringError {
642     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
643         self.description().fmt(f)
644     }
645 }
646
647 impl CStr {
648     /// Casts a raw C string to a safe C string wrapper.
649     ///
650     /// This function will cast the provided `ptr` to the `CStr` wrapper which
651     /// allows inspection and interoperation of non-owned C strings. This method
652     /// is unsafe for a number of reasons:
653     ///
654     /// * There is no guarantee to the validity of `ptr`.
655     /// * The returned lifetime is not guaranteed to be the actual lifetime of
656     ///   `ptr`.
657     /// * There is no guarantee that the memory pointed to by `ptr` contains a
658     ///   valid nul terminator byte at the end of the string.
659     ///
660     /// > **Note**: This operation is intended to be a 0-cost cast but it is
661     /// > currently implemented with an up-front calculation of the length of
662     /// > the string. This is not guaranteed to always be the case.
663     ///
664     /// # Examples
665     ///
666     /// ```no_run
667     /// # fn main() {
668     /// use std::ffi::CStr;
669     /// use std::os::raw::c_char;
670     ///
671     /// extern {
672     ///     fn my_string() -> *const c_char;
673     /// }
674     ///
675     /// unsafe {
676     ///     let slice = CStr::from_ptr(my_string());
677     ///     println!("string returned: {}", slice.to_str().unwrap());
678     /// }
679     /// # }
680     /// ```
681     #[stable(feature = "rust1", since = "1.0.0")]
682     pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
683         let len = libc::strlen(ptr);
684         let ptr = ptr as *const u8;
685         CStr::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr, len as usize + 1))
686     }
687
688     /// Creates a C string wrapper from a byte slice.
689     ///
690     /// This function will cast the provided `bytes` to a `CStr` wrapper after
691     /// ensuring that it is null terminated and does not contain any interior
692     /// nul bytes.
693     ///
694     /// # Examples
695     ///
696     /// ```
697     /// use std::ffi::CStr;
698     ///
699     /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
700     /// assert!(cstr.is_ok());
701     /// ```
702     #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
703     pub fn from_bytes_with_nul(bytes: &[u8])
704                                -> Result<&CStr, FromBytesWithNulError> {
705         let nul_pos = memchr::memchr(0, bytes);
706         if let Some(nul_pos) = nul_pos {
707             if nul_pos + 1 != bytes.len() {
708                 return Err(FromBytesWithNulError::interior_nul(nul_pos));
709             }
710             Ok(unsafe { CStr::from_bytes_with_nul_unchecked(bytes) })
711         } else {
712             Err(FromBytesWithNulError::not_nul_terminated())
713         }
714     }
715
716     /// Unsafely creates a C string wrapper from a byte slice.
717     ///
718     /// This function will cast the provided `bytes` to a `CStr` wrapper without
719     /// performing any sanity checks. The provided slice must be null terminated
720     /// and not contain any interior nul bytes.
721     ///
722     /// # Examples
723     ///
724     /// ```
725     /// use std::ffi::{CStr, CString};
726     ///
727     /// unsafe {
728     ///     let cstring = CString::new("hello").unwrap();
729     ///     let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
730     ///     assert_eq!(cstr, &*cstring);
731     /// }
732     /// ```
733     #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
734     pub unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
735         mem::transmute(bytes)
736     }
737
738     /// Returns the inner pointer to this C string.
739     ///
740     /// The returned pointer will be valid for as long as `self` is and points
741     /// to a contiguous region of memory terminated with a 0 byte to represent
742     /// the end of the string.
743     ///
744     /// **WARNING**
745     ///
746     /// It is your responsibility to make sure that the underlying memory is not
747     /// freed too early. For example, the following code will cause undefined
748     /// behaviour when `ptr` is used inside the `unsafe` block:
749     ///
750     /// ```no_run
751     /// use std::ffi::{CString};
752     ///
753     /// let ptr = CString::new("Hello").unwrap().as_ptr();
754     /// unsafe {
755     ///     // `ptr` is dangling
756     ///     *ptr;
757     /// }
758     /// ```
759     ///
760     /// This happens because the pointer returned by `as_ptr` does not carry any
761     /// lifetime information and the string is deallocated immediately after
762     /// the `CString::new("Hello").unwrap().as_ptr()` expression is evaluated.
763     /// To fix the problem, bind the string to a local variable:
764     ///
765     /// ```no_run
766     /// use std::ffi::{CString};
767     ///
768     /// let hello = CString::new("Hello").unwrap();
769     /// let ptr = hello.as_ptr();
770     /// unsafe {
771     ///     // `ptr` is valid because `hello` is in scope
772     ///     *ptr;
773     /// }
774     /// ```
775     #[stable(feature = "rust1", since = "1.0.0")]
776     pub fn as_ptr(&self) -> *const c_char {
777         self.inner.as_ptr()
778     }
779
780     /// Converts this C string to a byte slice.
781     ///
782     /// This function will calculate the length of this string (which normally
783     /// requires a linear amount of work to be done) and then return the
784     /// resulting slice of `u8` elements.
785     ///
786     /// The returned slice will **not** contain the trailing nul that this C
787     /// string has.
788     ///
789     /// > **Note**: This method is currently implemented as a 0-cost cast, but
790     /// > it is planned to alter its definition in the future to perform the
791     /// > length calculation whenever this method is called.
792     #[stable(feature = "rust1", since = "1.0.0")]
793     pub fn to_bytes(&self) -> &[u8] {
794         let bytes = self.to_bytes_with_nul();
795         &bytes[..bytes.len() - 1]
796     }
797
798     /// Converts this C string to a byte slice containing the trailing 0 byte.
799     ///
800     /// This function is the equivalent of [`to_bytes`] except that it will retain
801     /// the trailing nul instead of chopping it off.
802     ///
803     /// > **Note**: This method is currently implemented as a 0-cost cast, but
804     /// > it is planned to alter its definition in the future to perform the
805     /// > length calculation whenever this method is called.
806     ///
807     /// [`to_bytes`]: #method.to_bytes
808     #[stable(feature = "rust1", since = "1.0.0")]
809     pub fn to_bytes_with_nul(&self) -> &[u8] {
810         unsafe { mem::transmute(&self.inner) }
811     }
812
813     /// Yields a [`&str`] slice if the `CStr` contains valid UTF-8.
814     ///
815     /// This function will calculate the length of this string and check for
816     /// UTF-8 validity, and then return the [`&str`] if it's valid.
817     ///
818     /// > **Note**: This method is currently implemented to check for validity
819     /// > after a 0-cost cast, but it is planned to alter its definition in the
820     /// > future to perform the length calculation in addition to the UTF-8
821     /// > check whenever this method is called.
822     ///
823     /// [`&str`]: ../primitive.str.html
824     #[stable(feature = "cstr_to_str", since = "1.4.0")]
825     pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
826         // NB: When CStr is changed to perform the length check in .to_bytes()
827         // instead of in from_ptr(), it may be worth considering if this should
828         // be rewritten to do the UTF-8 check inline with the length calculation
829         // instead of doing it afterwards.
830         str::from_utf8(self.to_bytes())
831     }
832
833     /// Converts a `CStr` into a [`Cow`]`<`[`str`]`>`.
834     ///
835     /// This function will calculate the length of this string (which normally
836     /// requires a linear amount of work to be done) and then return the
837     /// resulting slice as a [`Cow`]`<`[`str`]`>`, replacing any invalid UTF-8 sequences
838     /// with `U+FFFD REPLACEMENT CHARACTER`.
839     ///
840     /// > **Note**: This method is currently implemented to check for validity
841     /// > after a 0-cost cast, but it is planned to alter its definition in the
842     /// > future to perform the length calculation in addition to the UTF-8
843     /// > check whenever this method is called.
844     ///
845     /// [`Cow`]: ../borrow/enum.Cow.html
846     /// [`str`]: ../primitive.str.html
847     #[stable(feature = "cstr_to_str", since = "1.4.0")]
848     pub fn to_string_lossy(&self) -> Cow<str> {
849         String::from_utf8_lossy(self.to_bytes())
850     }
851
852     /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating.
853     ///
854     /// [`Box`]: ../boxed/struct.Box.html
855     /// [`CString`]: struct.CString.html
856     #[unstable(feature = "into_boxed_c_str", issue = "40380")]
857     pub fn into_c_string(self: Box<CStr>) -> CString {
858         unsafe { mem::transmute(self) }
859     }
860 }
861
862 #[stable(feature = "rust1", since = "1.0.0")]
863 impl PartialEq for CStr {
864     fn eq(&self, other: &CStr) -> bool {
865         self.to_bytes().eq(other.to_bytes())
866     }
867 }
868 #[stable(feature = "rust1", since = "1.0.0")]
869 impl Eq for CStr {}
870 #[stable(feature = "rust1", since = "1.0.0")]
871 impl PartialOrd for CStr {
872     fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
873         self.to_bytes().partial_cmp(&other.to_bytes())
874     }
875 }
876 #[stable(feature = "rust1", since = "1.0.0")]
877 impl Ord for CStr {
878     fn cmp(&self, other: &CStr) -> Ordering {
879         self.to_bytes().cmp(&other.to_bytes())
880     }
881 }
882
883 #[stable(feature = "cstr_borrow", since = "1.3.0")]
884 impl ToOwned for CStr {
885     type Owned = CString;
886
887     fn to_owned(&self) -> CString {
888         CString { inner: self.to_bytes_with_nul().into() }
889     }
890 }
891
892 #[stable(feature = "cstring_asref", since = "1.7.0")]
893 impl<'a> From<&'a CStr> for CString {
894     fn from(s: &'a CStr) -> CString {
895         s.to_owned()
896     }
897 }
898
899 #[stable(feature = "cstring_asref", since = "1.7.0")]
900 impl ops::Index<ops::RangeFull> for CString {
901     type Output = CStr;
902
903     #[inline]
904     fn index(&self, _index: ops::RangeFull) -> &CStr {
905         self
906     }
907 }
908
909 #[stable(feature = "cstring_asref", since = "1.7.0")]
910 impl AsRef<CStr> for CStr {
911     fn as_ref(&self) -> &CStr {
912         self
913     }
914 }
915
916 #[stable(feature = "cstring_asref", since = "1.7.0")]
917 impl AsRef<CStr> for CString {
918     fn as_ref(&self) -> &CStr {
919         self
920     }
921 }
922
923 #[cfg(test)]
924 mod tests {
925     use super::*;
926     use os::raw::c_char;
927     use borrow::Cow::{Borrowed, Owned};
928     use hash::{Hash, Hasher};
929     use collections::hash_map::DefaultHasher;
930
931     #[test]
932     fn c_to_rust() {
933         let data = b"123\0";
934         let ptr = data.as_ptr() as *const c_char;
935         unsafe {
936             assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
937             assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
938         }
939     }
940
941     #[test]
942     fn simple() {
943         let s = CString::new("1234").unwrap();
944         assert_eq!(s.as_bytes(), b"1234");
945         assert_eq!(s.as_bytes_with_nul(), b"1234\0");
946     }
947
948     #[test]
949     fn build_with_zero1() {
950         assert!(CString::new(&b"\0"[..]).is_err());
951     }
952     #[test]
953     fn build_with_zero2() {
954         assert!(CString::new(vec![0]).is_err());
955     }
956
957     #[test]
958     fn build_with_zero3() {
959         unsafe {
960             let s = CString::from_vec_unchecked(vec![0]);
961             assert_eq!(s.as_bytes(), b"\0");
962         }
963     }
964
965     #[test]
966     fn formatted() {
967         let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
968         assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
969     }
970
971     #[test]
972     fn borrowed() {
973         unsafe {
974             let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
975             assert_eq!(s.to_bytes(), b"12");
976             assert_eq!(s.to_bytes_with_nul(), b"12\0");
977         }
978     }
979
980     #[test]
981     fn to_str() {
982         let data = b"123\xE2\x80\xA6\0";
983         let ptr = data.as_ptr() as *const c_char;
984         unsafe {
985             assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
986             assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
987         }
988         let data = b"123\xE2\0";
989         let ptr = data.as_ptr() as *const c_char;
990         unsafe {
991             assert!(CStr::from_ptr(ptr).to_str().is_err());
992             assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
993         }
994     }
995
996     #[test]
997     fn to_owned() {
998         let data = b"123\0";
999         let ptr = data.as_ptr() as *const c_char;
1000
1001         let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
1002         assert_eq!(owned.as_bytes_with_nul(), data);
1003     }
1004
1005     #[test]
1006     fn equal_hash() {
1007         let data = b"123\xE2\xFA\xA6\0";
1008         let ptr = data.as_ptr() as *const c_char;
1009         let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
1010
1011         let mut s = DefaultHasher::new();
1012         cstr.hash(&mut s);
1013         let cstr_hash = s.finish();
1014         let mut s = DefaultHasher::new();
1015         CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
1016         let cstring_hash = s.finish();
1017
1018         assert_eq!(cstr_hash, cstring_hash);
1019     }
1020
1021     #[test]
1022     fn from_bytes_with_nul() {
1023         let data = b"123\0";
1024         let cstr = CStr::from_bytes_with_nul(data);
1025         assert_eq!(cstr.map(CStr::to_bytes), Ok(&b"123"[..]));
1026         let cstr = CStr::from_bytes_with_nul(data);
1027         assert_eq!(cstr.map(CStr::to_bytes_with_nul), Ok(&b"123\0"[..]));
1028
1029         unsafe {
1030             let cstr = CStr::from_bytes_with_nul(data);
1031             let cstr_unchecked = CStr::from_bytes_with_nul_unchecked(data);
1032             assert_eq!(cstr, Ok(cstr_unchecked));
1033         }
1034     }
1035
1036     #[test]
1037     fn from_bytes_with_nul_unterminated() {
1038         let data = b"123";
1039         let cstr = CStr::from_bytes_with_nul(data);
1040         assert!(cstr.is_err());
1041     }
1042
1043     #[test]
1044     fn from_bytes_with_nul_interior() {
1045         let data = b"1\023\0";
1046         let cstr = CStr::from_bytes_with_nul(data);
1047         assert!(cstr.is_err());
1048     }
1049
1050     #[test]
1051     fn into_boxed() {
1052         let orig: &[u8] = b"Hello, world!\0";
1053         let cstr = CStr::from_bytes_with_nul(orig).unwrap();
1054         let boxed: Box<CStr> = Box::from(cstr);
1055         let cstring = cstr.to_owned().into_boxed_c_str().into_c_string();
1056         assert_eq!(cstr, &*boxed);
1057         assert_eq!(&*boxed, &*cstring);
1058         assert_eq!(&*cstring, cstr);
1059     }
1060
1061     #[test]
1062     fn boxed_default() {
1063         let boxed = <Box<CStr>>::default();
1064         assert_eq!(boxed.to_bytes_with_nul(), &[0]);
1065     }
1066 }