]> git.lizzy.rs Git - rust.git/blob - src/libstd/ffi/c_str.rs
Rollup merge of #28788 - tsurai:master, r=bluss
[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, ToOwned, Borrow};
13 use boxed::Box;
14 use convert::{Into, From};
15 use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
16 use error::Error;
17 use fmt::{self, Write};
18 use io;
19 use iter::Iterator;
20 use libc;
21 use mem;
22 use ops::Deref;
23 use option::Option::{self, Some, None};
24 use result::Result::{self, Ok, Err};
25 use slice;
26 use str;
27 use string::String;
28 use vec::Vec;
29
30 /// A type representing an owned C-compatible string
31 ///
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.
36 ///
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
43 /// specified.
44 ///
45 /// # Examples
46 ///
47 /// ```no_run
48 /// # #![feature(libc)]
49 /// # extern crate libc;
50 /// # fn main() {
51 /// use std::ffi::CString;
52 /// use libc;
53 ///
54 /// extern {
55 ///     fn my_printer(s: *const libc::c_char);
56 /// }
57 ///
58 /// let c_to_print = CString::new("Hello, world!").unwrap();
59 /// unsafe {
60 ///     my_printer(c_to_print.as_ptr());
61 /// }
62 /// # }
63 /// ```
64 #[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
65 #[stable(feature = "rust1", since = "1.0.0")]
66 pub struct CString {
67     inner: Box<[u8]>,
68 }
69
70 /// Representation of a borrowed C string.
71 ///
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.
75 ///
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.
80 ///
81 /// # Examples
82 ///
83 /// Inspecting a foreign C string
84 ///
85 /// ```no_run
86 /// # #![feature(libc)]
87 /// extern crate libc;
88 /// use std::ffi::CStr;
89 ///
90 /// extern { fn my_string() -> *const libc::c_char; }
91 ///
92 /// fn main() {
93 ///     unsafe {
94 ///         let slice = CStr::from_ptr(my_string());
95 ///         println!("string length: {}", slice.to_bytes().len());
96 ///     }
97 /// }
98 /// ```
99 ///
100 /// Passing a Rust-originating C string
101 ///
102 /// ```no_run
103 /// # #![feature(libc)]
104 /// extern crate libc;
105 /// use std::ffi::{CString, CStr};
106 ///
107 /// fn work(data: &CStr) {
108 ///     extern { fn work_with(data: *const libc::c_char); }
109 ///
110 ///     unsafe { work_with(data.as_ptr()) }
111 /// }
112 ///
113 /// fn main() {
114 ///     let s = CString::new("data data data data").unwrap();
115 ///     work(&s);
116 /// }
117 /// ```
118 ///
119 /// Converting a foreign C string into a Rust `String`
120 ///
121 /// ```no_run
122 /// # #![feature(libc)]
123 /// extern crate libc;
124 /// use std::ffi::CStr;
125 ///
126 /// extern { fn my_string() -> *const libc::c_char; }
127 ///
128 /// fn my_string_safe() -> String {
129 ///     unsafe {
130 ///         CStr::from_ptr(my_string()).to_string_lossy().into_owned()
131 ///     }
132 /// }
133 ///
134 /// fn main() {
135 ///     println!("string: {}", my_string_safe());
136 /// }
137 /// ```
138 #[derive(Hash)]
139 #[stable(feature = "rust1", since = "1.0.0")]
140 pub struct CStr {
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]
146 }
147
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>);
153
154 impl CString {
155     /// Creates a new C-compatible string from a container of bytes.
156     ///
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.
159     ///
160     /// # Examples
161     ///
162     /// ```no_run
163     /// # #![feature(libc)]
164     /// extern crate libc;
165     /// use std::ffi::CString;
166     ///
167     /// extern { fn puts(s: *const libc::c_char); }
168     ///
169     /// fn main() {
170     ///     let to_print = CString::new("Hello!").unwrap();
171     ///     unsafe {
172     ///         puts(to_print.as_ptr());
173     ///     }
174     /// }
175     /// ```
176     ///
177     /// # Errors
178     ///
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         Self::_new(t.into())
185     }
186
187     fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
188         match bytes.iter().position(|x| *x == 0) {
189             Some(i) => Err(NulError(i, bytes)),
190             None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
191         }
192     }
193
194     /// Creates a C-compatible string from a byte vector without checking for
195     /// interior 0 bytes.
196     ///
197     /// This method is equivalent to `new` except that no runtime assertion
198     /// is made that `v` contains no 0 bytes, and it requires an actual
199     /// byte vector, not anything that can be converted to one with Into.
200     #[stable(feature = "rust1", since = "1.0.0")]
201     pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
202         v.push(0);
203         CString { inner: v.into_boxed_slice() }
204     }
205
206     /// Retakes ownership of a CString that was transferred to C.
207     ///
208     /// The only appropriate argument is a pointer obtained by calling
209     /// `into_raw`. The length of the string will be recalculated
210     /// using the pointer.
211     #[unstable(feature = "cstr_memory2", reason = "recently added",
212                issue = "27769")]
213     #[deprecated(since = "1.4.0", reason = "renamed to from_raw")]
214     pub unsafe fn from_ptr(ptr: *const libc::c_char) -> CString {
215         CString::from_raw(ptr as *mut _)
216     }
217
218     /// Retakes ownership of a CString that was transferred to C.
219     ///
220     /// The only appropriate argument is a pointer obtained by calling
221     /// `into_raw`. The length of the string will be recalculated
222     /// using the pointer.
223     #[stable(feature = "cstr_memory", since = "1.4.0")]
224     pub unsafe fn from_raw(ptr: *mut libc::c_char) -> CString {
225         let len = libc::strlen(ptr) + 1; // Including the NUL byte
226         let slice = slice::from_raw_parts(ptr, len as usize);
227         CString { inner: mem::transmute(slice) }
228     }
229
230     /// Transfers ownership of the string to a C caller.
231     ///
232     /// The pointer must be returned to Rust and reconstituted using
233     /// `from_raw` to be properly deallocated. Specifically, one
234     /// should *not* use the standard C `free` function to deallocate
235     /// this string.
236     ///
237     /// Failure to call `from_raw` will lead to a memory leak.
238     #[unstable(feature = "cstr_memory2", reason = "recently added",
239                issue = "27769")]
240     #[deprecated(since = "1.4.0", reason = "renamed to into_raw")]
241     pub fn into_ptr(self) -> *const libc::c_char {
242         self.into_raw() as *const _
243     }
244
245     /// Transfers ownership of the string to a C caller.
246     ///
247     /// The pointer must be returned to Rust and reconstituted using
248     /// `from_raw` to be properly deallocated. Specifically, one
249     /// should *not* use the standard C `free` function to deallocate
250     /// this string.
251     ///
252     /// Failure to call `from_raw` will lead to a memory leak.
253     #[stable(feature = "cstr_memory", since = "1.4.0")]
254     pub fn into_raw(self) -> *mut libc::c_char {
255         Box::into_raw(self.inner) as *mut libc::c_char
256     }
257
258     /// Returns the contents of this `CString` as a slice of bytes.
259     ///
260     /// The returned slice does **not** contain the trailing nul separator and
261     /// it is guaranteed to not have any interior nul bytes.
262     #[stable(feature = "rust1", since = "1.0.0")]
263     pub fn as_bytes(&self) -> &[u8] {
264         &self.inner[..self.inner.len() - 1]
265     }
266
267     /// Equivalent to the `as_bytes` function except that the returned slice
268     /// includes the trailing nul byte.
269     #[stable(feature = "rust1", since = "1.0.0")]
270     pub fn as_bytes_with_nul(&self) -> &[u8] {
271         &self.inner
272     }
273 }
274
275 #[stable(feature = "rust1", since = "1.0.0")]
276 impl Deref for CString {
277     type Target = CStr;
278
279     fn deref(&self) -> &CStr {
280         unsafe { mem::transmute(self.as_bytes_with_nul()) }
281     }
282 }
283
284 #[stable(feature = "rust1", since = "1.0.0")]
285 impl fmt::Debug for CString {
286     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
287         fmt::Debug::fmt(&**self, f)
288     }
289 }
290
291 #[stable(feature = "cstr_debug", since = "1.3.0")]
292 impl fmt::Debug for CStr {
293     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
294         try!(write!(f, "\""));
295         for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
296             try!(f.write_char(byte as char));
297         }
298         write!(f, "\"")
299     }
300 }
301
302 #[stable(feature = "cstr_borrow", since = "1.3.0")]
303 impl Borrow<CStr> for CString {
304     fn borrow(&self) -> &CStr { self }
305 }
306
307 impl NulError {
308     /// Returns the position of the nul byte in the slice that was provided to
309     /// `CString::new`.
310     #[stable(feature = "rust1", since = "1.0.0")]
311     pub fn nul_position(&self) -> usize { self.0 }
312
313     /// Consumes this error, returning the underlying vector of bytes which
314     /// generated the error in the first place.
315     #[stable(feature = "rust1", since = "1.0.0")]
316     pub fn into_vec(self) -> Vec<u8> { self.1 }
317 }
318
319 #[stable(feature = "rust1", since = "1.0.0")]
320 impl Error for NulError {
321     fn description(&self) -> &str { "nul byte found in data" }
322 }
323
324 #[stable(feature = "rust1", since = "1.0.0")]
325 impl fmt::Display for NulError {
326     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
327         write!(f, "nul byte found in provided data at position: {}", self.0)
328     }
329 }
330
331 #[stable(feature = "rust1", since = "1.0.0")]
332 impl From<NulError> for io::Error {
333     fn from(_: NulError) -> io::Error {
334         io::Error::new(io::ErrorKind::InvalidInput,
335                        "data provided contains a nul byte")
336     }
337 }
338
339 impl CStr {
340     /// Casts a raw C string to a safe C string wrapper.
341     ///
342     /// This function will cast the provided `ptr` to the `CStr` wrapper which
343     /// allows inspection and interoperation of non-owned C strings. This method
344     /// is unsafe for a number of reasons:
345     ///
346     /// * There is no guarantee to the validity of `ptr`
347     /// * The returned lifetime is not guaranteed to be the actual lifetime of
348     ///   `ptr`
349     /// * There is no guarantee that the memory pointed to by `ptr` contains a
350     ///   valid nul terminator byte at the end of the string.
351     ///
352     /// > **Note**: This operation is intended to be a 0-cost cast but it is
353     /// > currently implemented with an up-front calculation of the length of
354     /// > the string. This is not guaranteed to always be the case.
355     ///
356     /// # Examples
357     ///
358     /// ```no_run
359     /// # #![feature(libc)]
360     /// # extern crate libc;
361     /// # fn main() {
362     /// use std::ffi::CStr;
363     /// use std::str;
364     /// use libc;
365     ///
366     /// extern {
367     ///     fn my_string() -> *const libc::c_char;
368     /// }
369     ///
370     /// unsafe {
371     ///     let slice = CStr::from_ptr(my_string());
372     ///     println!("string returned: {}",
373     ///              str::from_utf8(slice.to_bytes()).unwrap());
374     /// }
375     /// # }
376     /// ```
377     #[stable(feature = "rust1", since = "1.0.0")]
378     pub unsafe fn from_ptr<'a>(ptr: *const libc::c_char) -> &'a CStr {
379         let len = libc::strlen(ptr);
380         mem::transmute(slice::from_raw_parts(ptr, len as usize + 1))
381     }
382
383     /// Returns the inner pointer to this C string.
384     ///
385     /// The returned pointer will be valid for as long as `self` is and points
386     /// to a contiguous region of memory terminated with a 0 byte to represent
387     /// the end of the string.
388     #[stable(feature = "rust1", since = "1.0.0")]
389     pub fn as_ptr(&self) -> *const libc::c_char {
390         self.inner.as_ptr()
391     }
392
393     /// Converts this C string to a byte slice.
394     ///
395     /// This function will calculate the length of this string (which normally
396     /// requires a linear amount of work to be done) and then return the
397     /// resulting slice of `u8` elements.
398     ///
399     /// The returned slice will **not** contain the trailing nul that this C
400     /// string has.
401     ///
402     /// > **Note**: This method is currently implemented as a 0-cost cast, but
403     /// > it is planned to alter its definition in the future to perform the
404     /// > length calculation whenever this method is called.
405     #[stable(feature = "rust1", since = "1.0.0")]
406     pub fn to_bytes(&self) -> &[u8] {
407         let bytes = self.to_bytes_with_nul();
408         &bytes[..bytes.len() - 1]
409     }
410
411     /// Converts this C string to a byte slice containing the trailing 0 byte.
412     ///
413     /// This function is the equivalent of `to_bytes` except that it will retain
414     /// the trailing nul instead of chopping it off.
415     ///
416     /// > **Note**: This method is currently implemented as a 0-cost cast, but
417     /// > it is planned to alter its definition in the future to perform the
418     /// > length calculation whenever this method is called.
419     #[stable(feature = "rust1", since = "1.0.0")]
420     pub fn to_bytes_with_nul(&self) -> &[u8] {
421         unsafe { mem::transmute(&self.inner) }
422     }
423
424     /// Yields a `&str` slice if the `CStr` contains valid UTF-8.
425     ///
426     /// This function will calculate the length of this string and check for
427     /// UTF-8 validity, and then return the `&str` if it's valid.
428     ///
429     /// > **Note**: This method is currently implemented to check for validity
430     /// > after a 0-cost cast, but it is planned to alter its definition in the
431     /// > future to perform the length calculation in addition to the UTF-8
432     /// > check whenever this method is called.
433     #[stable(feature = "cstr_to_str", since = "1.4.0")]
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())
440     }
441
442     /// Converts a `CStr` into a `Cow<str>`.
443     ///
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`.
448     ///
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     #[stable(feature = "cstr_to_str", since = "1.4.0")]
454     pub fn to_string_lossy(&self) -> Cow<str> {
455         String::from_utf8_lossy(self.to_bytes())
456     }
457 }
458
459 #[stable(feature = "rust1", since = "1.0.0")]
460 impl PartialEq for CStr {
461     fn eq(&self, other: &CStr) -> bool {
462         self.to_bytes().eq(other.to_bytes())
463     }
464 }
465 #[stable(feature = "rust1", since = "1.0.0")]
466 impl Eq for CStr {}
467 #[stable(feature = "rust1", since = "1.0.0")]
468 impl PartialOrd for CStr {
469     fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
470         self.to_bytes().partial_cmp(&other.to_bytes())
471     }
472 }
473 #[stable(feature = "rust1", since = "1.0.0")]
474 impl Ord for CStr {
475     fn cmp(&self, other: &CStr) -> Ordering {
476         self.to_bytes().cmp(&other.to_bytes())
477     }
478 }
479
480 #[stable(feature = "cstr_borrow", since = "1.3.0")]
481 impl ToOwned for CStr {
482     type Owned = CString;
483
484     fn to_owned(&self) -> CString {
485         unsafe { CString::from_vec_unchecked(self.to_bytes().to_vec()) }
486     }
487 }
488
489 #[cfg(test)]
490 mod tests {
491     use prelude::v1::*;
492     use super::*;
493     use libc;
494     use borrow::Cow::{Borrowed, Owned};
495     use hash::{SipHasher, Hash, Hasher};
496
497     #[test]
498     fn c_to_rust() {
499         let data = b"123\0";
500         let ptr = data.as_ptr() as *const libc::c_char;
501         unsafe {
502             assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
503             assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
504         }
505     }
506
507     #[test]
508     fn simple() {
509         let s = CString::new("1234").unwrap();
510         assert_eq!(s.as_bytes(), b"1234");
511         assert_eq!(s.as_bytes_with_nul(), b"1234\0");
512     }
513
514     #[test]
515     fn build_with_zero1() {
516         assert!(CString::new(&b"\0"[..]).is_err());
517     }
518     #[test]
519     fn build_with_zero2() {
520         assert!(CString::new(vec![0]).is_err());
521     }
522
523     #[test]
524     fn build_with_zero3() {
525         unsafe {
526             let s = CString::from_vec_unchecked(vec![0]);
527             assert_eq!(s.as_bytes(), b"\0");
528         }
529     }
530
531     #[test]
532     fn formatted() {
533         let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
534         assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
535     }
536
537     #[test]
538     fn borrowed() {
539         unsafe {
540             let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
541             assert_eq!(s.to_bytes(), b"12");
542             assert_eq!(s.to_bytes_with_nul(), b"12\0");
543         }
544     }
545
546     #[test]
547     fn to_str() {
548         let data = b"123\xE2\x80\xA6\0";
549         let ptr = data.as_ptr() as *const libc::c_char;
550         unsafe {
551             assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
552             assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
553         }
554         let data = b"123\xE2\0";
555         let ptr = data.as_ptr() as *const libc::c_char;
556         unsafe {
557             assert!(CStr::from_ptr(ptr).to_str().is_err());
558             assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
559         }
560     }
561
562     #[test]
563     fn to_owned() {
564         let data = b"123\0";
565         let ptr = data.as_ptr() as *const libc::c_char;
566
567         let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
568         assert_eq!(owned.as_bytes_with_nul(), data);
569     }
570
571     #[test]
572     fn equal_hash() {
573         let data = b"123\xE2\xFA\xA6\0";
574         let ptr = data.as_ptr() as *const libc::c_char;
575         let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
576
577         let mut s = SipHasher::new_with_keys(0, 0);
578         cstr.hash(&mut s);
579         let cstr_hash = s.finish();
580         let mut s = SipHasher::new_with_keys(0, 0);
581         CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
582         let cstring_hash = s.finish();
583
584         assert_eq!(cstr_hash, cstring_hash);
585     }
586 }