]> git.lizzy.rs Git - rust.git/blob - src/libstd/ffi/c_str.rs
Auto merge of #28396 - arielb1:misplaced-binding, r=eddyb
[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         let bytes = t.into();
185         match bytes.iter().position(|x| *x == 0) {
186             Some(i) => Err(NulError(i, bytes)),
187             None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
188         }
189     }
190
191     /// Creates a C-compatible string from a byte vector without checking for
192     /// interior 0 bytes.
193     ///
194     /// This method is equivalent to `new` except that no runtime assertion
195     /// is made that `v` contains no 0 bytes, and it requires an actual
196     /// byte vector, not anything that can be converted to one with Into.
197     #[stable(feature = "rust1", since = "1.0.0")]
198     pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
199         v.push(0);
200         CString { inner: v.into_boxed_slice() }
201     }
202
203     /// Retakes ownership of a CString that was transferred to C.
204     ///
205     /// The only appropriate argument is a pointer obtained by calling
206     /// `into_ptr`. The length of the string will be recalculated
207     /// using the pointer.
208     #[unstable(feature = "cstr_memory2", reason = "recently added",
209                issue = "27769")]
210     #[deprecated(since = "1.4.0", reason = "renamed to from_raw")]
211     pub unsafe fn from_ptr(ptr: *const libc::c_char) -> CString {
212         CString::from_raw(ptr as *mut _)
213     }
214
215     /// Retakes ownership of a CString that was transferred to C.
216     ///
217     /// The only appropriate argument is a pointer obtained by calling
218     /// `into_raw`. The length of the string will be recalculated
219     /// using the pointer.
220     #[stable(feature = "cstr_memory", since = "1.4.0")]
221     pub unsafe fn from_raw(ptr: *mut libc::c_char) -> CString {
222         let len = libc::strlen(ptr) + 1; // Including the NUL byte
223         let slice = slice::from_raw_parts(ptr, len as usize);
224         CString { inner: mem::transmute(slice) }
225     }
226
227     /// Transfers ownership of the string to a C caller.
228     ///
229     /// The pointer must be returned to Rust and reconstituted using
230     /// `from_raw` to be properly deallocated. Specifically, one
231     /// should *not* use the standard C `free` function to deallocate
232     /// this string.
233     ///
234     /// Failure to call `from_raw` will lead to a memory leak.
235     #[unstable(feature = "cstr_memory2", reason = "recently added",
236                issue = "27769")]
237     #[deprecated(since = "1.4.0", reason = "renamed to into_raw")]
238     pub fn into_ptr(self) -> *const libc::c_char {
239         self.into_raw() as *const _
240     }
241
242     /// Transfers ownership of the string to a C caller.
243     ///
244     /// The pointer must be returned to Rust and reconstituted using
245     /// `from_ptr` to be properly deallocated. Specifically, one
246     /// should *not* use the standard C `free` function to deallocate
247     /// this string.
248     ///
249     /// Failure to call `from_ptr` will lead to a memory leak.
250     #[stable(feature = "cstr_memory", since = "1.4.0")]
251     pub fn into_raw(self) -> *mut libc::c_char {
252         Box::into_raw(self.inner) as *mut libc::c_char
253     }
254
255     /// Returns the contents of this `CString` as a slice of bytes.
256     ///
257     /// The returned slice does **not** contain the trailing nul separator and
258     /// it is guaranteed to not have any interior nul bytes.
259     #[stable(feature = "rust1", since = "1.0.0")]
260     pub fn as_bytes(&self) -> &[u8] {
261         &self.inner[..self.inner.len() - 1]
262     }
263
264     /// Equivalent to the `as_bytes` function except that the returned slice
265     /// includes the trailing nul byte.
266     #[stable(feature = "rust1", since = "1.0.0")]
267     pub fn as_bytes_with_nul(&self) -> &[u8] {
268         &self.inner
269     }
270 }
271
272 #[stable(feature = "rust1", since = "1.0.0")]
273 impl Deref for CString {
274     type Target = CStr;
275
276     fn deref(&self) -> &CStr {
277         unsafe { mem::transmute(self.as_bytes_with_nul()) }
278     }
279 }
280
281 #[stable(feature = "rust1", since = "1.0.0")]
282 impl fmt::Debug for CString {
283     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
284         fmt::Debug::fmt(&**self, f)
285     }
286 }
287
288 #[stable(feature = "cstr_debug", since = "1.3.0")]
289 impl fmt::Debug for CStr {
290     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
291         try!(write!(f, "\""));
292         for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
293             try!(f.write_char(byte as char));
294         }
295         write!(f, "\"")
296     }
297 }
298
299 #[stable(feature = "cstr_borrow", since = "1.3.0")]
300 impl Borrow<CStr> for CString {
301     fn borrow(&self) -> &CStr { self }
302 }
303
304 impl NulError {
305     /// Returns the position of the nul byte in the slice that was provided to
306     /// `CString::new`.
307     #[stable(feature = "rust1", since = "1.0.0")]
308     pub fn nul_position(&self) -> usize { self.0 }
309
310     /// Consumes this error, returning the underlying vector of bytes which
311     /// generated the error in the first place.
312     #[stable(feature = "rust1", since = "1.0.0")]
313     pub fn into_vec(self) -> Vec<u8> { self.1 }
314 }
315
316 #[stable(feature = "rust1", since = "1.0.0")]
317 impl Error for NulError {
318     fn description(&self) -> &str { "nul byte found in data" }
319 }
320
321 #[stable(feature = "rust1", since = "1.0.0")]
322 impl fmt::Display for NulError {
323     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
324         write!(f, "nul byte found in provided data at position: {}", self.0)
325     }
326 }
327
328 #[stable(feature = "rust1", since = "1.0.0")]
329 impl From<NulError> for io::Error {
330     fn from(_: NulError) -> io::Error {
331         io::Error::new(io::ErrorKind::InvalidInput,
332                        "data provided contains a nul byte")
333     }
334 }
335
336 impl CStr {
337     /// Casts a raw C string to a safe C string wrapper.
338     ///
339     /// This function will cast the provided `ptr` to the `CStr` wrapper which
340     /// allows inspection and interoperation of non-owned C strings. This method
341     /// is unsafe for a number of reasons:
342     ///
343     /// * There is no guarantee to the validity of `ptr`
344     /// * The returned lifetime is not guaranteed to be the actual lifetime of
345     ///   `ptr`
346     /// * There is no guarantee that the memory pointed to by `ptr` contains a
347     ///   valid nul terminator byte at the end of the string.
348     ///
349     /// > **Note**: This operation is intended to be a 0-cost cast but it is
350     /// > currently implemented with an up-front calculation of the length of
351     /// > the string. This is not guaranteed to always be the case.
352     ///
353     /// # Examples
354     ///
355     /// ```no_run
356     /// # #![feature(libc)]
357     /// # extern crate libc;
358     /// # fn main() {
359     /// use std::ffi::CStr;
360     /// use std::str;
361     /// use libc;
362     ///
363     /// extern {
364     ///     fn my_string() -> *const libc::c_char;
365     /// }
366     ///
367     /// unsafe {
368     ///     let slice = CStr::from_ptr(my_string());
369     ///     println!("string returned: {}",
370     ///              str::from_utf8(slice.to_bytes()).unwrap());
371     /// }
372     /// # }
373     /// ```
374     #[stable(feature = "rust1", since = "1.0.0")]
375     pub unsafe fn from_ptr<'a>(ptr: *const libc::c_char) -> &'a CStr {
376         let len = libc::strlen(ptr);
377         mem::transmute(slice::from_raw_parts(ptr, len as usize + 1))
378     }
379
380     /// Returns the inner pointer to this C string.
381     ///
382     /// The returned pointer will be valid for as long as `self` is and points
383     /// to a contiguous region of memory terminated with a 0 byte to represent
384     /// the end of the string.
385     #[stable(feature = "rust1", since = "1.0.0")]
386     pub fn as_ptr(&self) -> *const libc::c_char {
387         self.inner.as_ptr()
388     }
389
390     /// Converts this C string to a byte slice.
391     ///
392     /// This function will calculate the length of this string (which normally
393     /// requires a linear amount of work to be done) and then return the
394     /// resulting slice of `u8` elements.
395     ///
396     /// The returned slice will **not** contain the trailing nul that this C
397     /// string has.
398     ///
399     /// > **Note**: This method is currently implemented as a 0-cost cast, but
400     /// > it is planned to alter its definition in the future to perform the
401     /// > length calculation whenever this method is called.
402     #[stable(feature = "rust1", since = "1.0.0")]
403     pub fn to_bytes(&self) -> &[u8] {
404         let bytes = self.to_bytes_with_nul();
405         &bytes[..bytes.len() - 1]
406     }
407
408     /// Converts this C string to a byte slice containing the trailing 0 byte.
409     ///
410     /// This function is the equivalent of `to_bytes` except that it will retain
411     /// the trailing nul instead of chopping it off.
412     ///
413     /// > **Note**: This method is currently implemented as a 0-cost cast, but
414     /// > it is planned to alter its definition in the future to perform the
415     /// > length calculation whenever this method is called.
416     #[stable(feature = "rust1", since = "1.0.0")]
417     pub fn to_bytes_with_nul(&self) -> &[u8] {
418         unsafe { mem::transmute(&self.inner) }
419     }
420
421     /// Yields a `&str` slice if the `CStr` contains valid UTF-8.
422     ///
423     /// This function will calculate the length of this string and check for
424     /// UTF-8 validity, and then return the `&str` if it's valid.
425     ///
426     /// > **Note**: This method is currently implemented to check for validity
427     /// > after a 0-cost cast, but it is planned to alter its definition in the
428     /// > future to perform the length calculation in addition to the UTF-8
429     /// > check whenever this method is called.
430     #[stable(feature = "cstr_to_str", since = "1.4.0")]
431     pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
432         // NB: When CStr is changed to perform the length check in .to_bytes()
433         // instead of in from_ptr(), it may be worth considering if this should
434         // be rewritten to do the UTF-8 check inline with the length calculation
435         // instead of doing it afterwards.
436         str::from_utf8(self.to_bytes())
437     }
438
439     /// Converts a `CStr` into a `Cow<str>`.
440     ///
441     /// This function will calculate the length of this string (which normally
442     /// requires a linear amount of work to be done) and then return the
443     /// resulting slice as a `Cow<str>`, replacing any invalid UTF-8 sequences
444     /// with `U+FFFD REPLACEMENT CHARACTER`.
445     ///
446     /// > **Note**: This method is currently implemented to check for validity
447     /// > after a 0-cost cast, but it is planned to alter its definition in the
448     /// > future to perform the length calculation in addition to the UTF-8
449     /// > check whenever this method is called.
450     #[stable(feature = "cstr_to_str", since = "1.4.0")]
451     pub fn to_string_lossy(&self) -> Cow<str> {
452         String::from_utf8_lossy(self.to_bytes())
453     }
454 }
455
456 #[stable(feature = "rust1", since = "1.0.0")]
457 impl PartialEq for CStr {
458     fn eq(&self, other: &CStr) -> bool {
459         self.to_bytes().eq(other.to_bytes())
460     }
461 }
462 #[stable(feature = "rust1", since = "1.0.0")]
463 impl Eq for CStr {}
464 #[stable(feature = "rust1", since = "1.0.0")]
465 impl PartialOrd for CStr {
466     fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
467         self.to_bytes().partial_cmp(&other.to_bytes())
468     }
469 }
470 #[stable(feature = "rust1", since = "1.0.0")]
471 impl Ord for CStr {
472     fn cmp(&self, other: &CStr) -> Ordering {
473         self.to_bytes().cmp(&other.to_bytes())
474     }
475 }
476
477 #[stable(feature = "cstr_borrow", since = "1.3.0")]
478 impl ToOwned for CStr {
479     type Owned = CString;
480
481     fn to_owned(&self) -> CString {
482         unsafe { CString::from_vec_unchecked(self.to_bytes().to_vec()) }
483     }
484 }
485
486 #[cfg(test)]
487 mod tests {
488     use prelude::v1::*;
489     use super::*;
490     use libc;
491     use borrow::Cow::{Borrowed, Owned};
492     use hash::{SipHasher, Hash, Hasher};
493
494     #[test]
495     fn c_to_rust() {
496         let data = b"123\0";
497         let ptr = data.as_ptr() as *const libc::c_char;
498         unsafe {
499             assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
500             assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
501         }
502     }
503
504     #[test]
505     fn simple() {
506         let s = CString::new("1234").unwrap();
507         assert_eq!(s.as_bytes(), b"1234");
508         assert_eq!(s.as_bytes_with_nul(), b"1234\0");
509     }
510
511     #[test]
512     fn build_with_zero1() {
513         assert!(CString::new(&b"\0"[..]).is_err());
514     }
515     #[test]
516     fn build_with_zero2() {
517         assert!(CString::new(vec![0]).is_err());
518     }
519
520     #[test]
521     fn build_with_zero3() {
522         unsafe {
523             let s = CString::from_vec_unchecked(vec![0]);
524             assert_eq!(s.as_bytes(), b"\0");
525         }
526     }
527
528     #[test]
529     fn formatted() {
530         let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
531         assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
532     }
533
534     #[test]
535     fn borrowed() {
536         unsafe {
537             let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
538             assert_eq!(s.to_bytes(), b"12");
539             assert_eq!(s.to_bytes_with_nul(), b"12\0");
540         }
541     }
542
543     #[test]
544     fn to_str() {
545         let data = b"123\xE2\x80\xA6\0";
546         let ptr = data.as_ptr() as *const libc::c_char;
547         unsafe {
548             assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
549             assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
550         }
551         let data = b"123\xE2\0";
552         let ptr = data.as_ptr() as *const libc::c_char;
553         unsafe {
554             assert!(CStr::from_ptr(ptr).to_str().is_err());
555             assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
556         }
557     }
558
559     #[test]
560     fn to_owned() {
561         let data = b"123\0";
562         let ptr = data.as_ptr() as *const libc::c_char;
563
564         let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
565         assert_eq!(owned.as_bytes_with_nul(), data);
566     }
567
568     #[test]
569     fn equal_hash() {
570         let data = b"123\xE2\xFA\xA6\0";
571         let ptr = data.as_ptr() as *const libc::c_char;
572         let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
573
574         let mut s = SipHasher::new_with_keys(0, 0);
575         cstr.hash(&mut s);
576         let cstr_hash = s.finish();
577         let mut s = SipHasher::new_with_keys(0, 0);
578         CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
579         let cstring_hash = s.finish();
580
581         assert_eq!(cstr_hash, cstring_hash);
582     }
583 }