Skip to content

Commit b1e4d67

Browse files
author
Oliver Schneider
committed
Rollup merge of rust-lang#25416 - kballard:ffi-cstr-to-str-convenience, r=alexcrichton
This was motivated by http://www.evanmiller.org/a-taste-of-rust.html. A common problem when working with FFI right now is converting from raw C strings into `&str` or `String`. Right now you're required to say something like let cstr = unsafe { CStr::from_ptr(ptr) }; let result = str::from_utf8(cstr.to_bytes()); This is slightly awkward, and is not particularly intuitive for people who haven't used the ffi module before. We can do a bit better by providing some convenience methods on CStr: fn to_str(&self) -> Result<&str, str::Utf8Error> fn to_string_lossy(&self) -> Cow<str> This will make it immediately apparent to new users of CStr how to get a string from a raw C string, so they can say: let s = unsafe { CStr::from_ptr(ptr).to_string_lossy() };
2 parents f472403 + d0b5eb3 commit b1e4d67

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

src/libstd/ffi/c_str.rs

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
#![unstable(feature = "std_misc")]
1212

13+
use borrow::Cow;
1314
use convert::{Into, From};
1415
use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
1516
use error::Error;
@@ -22,6 +23,7 @@ use ops::Deref;
2223
use option::Option::{self, Some, None};
2324
use result::Result::{self, Ok, Err};
2425
use slice;
26+
use str;
2527
use string::String;
2628
use vec::Vec;
2729

@@ -113,6 +115,26 @@ pub struct CString {
113115
/// work(&s);
114116
/// }
115117
/// ```
118+
///
119+
/// Converting a foreign C string into a Rust `String`
120+
///
121+
/// ```no_run
122+
/// # #![feature(libc,cstr_to_str)]
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+
/// ```
116138
#[derive(Hash)]
117139
#[stable(feature = "rust1", since = "1.0.0")]
118140
pub struct CStr {
@@ -327,6 +349,39 @@ impl CStr {
327349
pub fn to_bytes_with_nul(&self) -> &[u8] {
328350
unsafe { mem::transmute::<&[libc::c_char], &[u8]>(&self.inner) }
329351
}
352+
353+
/// Yields a `&str` slice if the `CStr` contains valid UTF-8.
354+
///
355+
/// This function will calculate the length of this string and check for
356+
/// UTF-8 validity, and then return the `&str` if it's valid.
357+
///
358+
/// > **Note**: This method is currently implemented to check for validity
359+
/// > after a 0-cost cast, but it is planned to alter its definition in the
360+
/// > future to perform the length calculation in addition to the UTF-8
361+
/// > check whenever this method is called.
362+
#[unstable(feature = "cstr_to_str", reason = "recently added")]
363+
pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
364+
// NB: When CStr is changed to perform the length check in .to_bytes() instead of in
365+
// from_ptr(), it may be worth considering if this should be rewritten to do the UTF-8
366+
// check inline with the length calculation instead of doing it afterwards.
367+
str::from_utf8(self.to_bytes())
368+
}
369+
370+
/// Converts a `CStr` into a `Cow<str>`.
371+
///
372+
/// This function will calculate the length of this string (which normally
373+
/// requires a linear amount of work to be done) and then return the
374+
/// resulting slice as a `Cow<str>`, replacing any invalid UTF-8 sequences
375+
/// with `U+FFFD REPLACEMENT CHARACTER`.
376+
///
377+
/// > **Note**: This method is currently implemented to check for validity
378+
/// > after a 0-cost cast, but it is planned to alter its definition in the
379+
/// > future to perform the length calculation in addition to the UTF-8
380+
/// > check whenever this method is called.
381+
#[unstable(feature = "cstr_to_str", reason = "recently added")]
382+
pub fn to_string_lossy(&self) -> Cow<str> {
383+
String::from_utf8_lossy(self.to_bytes())
384+
}
330385
}
331386

332387
#[stable(feature = "rust1", since = "1.0.0")]
@@ -355,6 +410,7 @@ mod tests {
355410
use prelude::v1::*;
356411
use super::*;
357412
use libc;
413+
use borrow::Cow::{Borrowed, Owned};
358414

359415
#[test]
360416
fn c_to_rust() {
@@ -404,4 +460,20 @@ mod tests {
404460
assert_eq!(s.to_bytes_with_nul(), b"12\0");
405461
}
406462
}
463+
464+
#[test]
465+
fn to_str() {
466+
let data = b"123\xE2\x80\xA6\0";
467+
let ptr = data.as_ptr() as *const libc::c_char;
468+
unsafe {
469+
assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
470+
assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
471+
}
472+
let data = b"123\xE2\0";
473+
let ptr = data.as_ptr() as *const libc::c_char;
474+
unsafe {
475+
assert!(CStr::from_ptr(ptr).to_str().is_err());
476+
assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
477+
}
478+
}
407479
}

0 commit comments

Comments
 (0)