Add as_c_str method on strings
This commit is contained in:
parent
91a7073900
commit
c77d58fad8
2 changed files with 40 additions and 23 deletions
|
@ -45,7 +45,7 @@ pub use path::PosixPath;
|
||||||
pub use path::WindowsPath;
|
pub use path::WindowsPath;
|
||||||
pub use ptr::Ptr;
|
pub use ptr::Ptr;
|
||||||
pub use ascii::{Ascii, AsciiCast, OwnedAsciiCast, AsciiStr};
|
pub use ascii::{Ascii, AsciiCast, OwnedAsciiCast, AsciiStr};
|
||||||
pub use str::{StrSlice, OwnedStr};
|
pub use str::{StrSlice, OwnedStr, StrUtil};
|
||||||
pub use from_str::{FromStr};
|
pub use from_str::{FromStr};
|
||||||
pub use to_bytes::IterBytes;
|
pub use to_bytes::IterBytes;
|
||||||
pub use to_str::{ToStr, ToStrConsume};
|
pub use to_str::{ToStr, ToStrConsume};
|
||||||
|
|
|
@ -2165,6 +2165,10 @@ pub fn as_bytes_slice<'a>(s: &'a str) -> &'a [u8] {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* A dummy trait to hold all the utility methods that we implement on strings.
|
||||||
|
*/
|
||||||
|
pub trait StrUtil {
|
||||||
|
/**
|
||||||
* Work with the byte buffer of a string as a null-terminated C string.
|
* Work with the byte buffer of a string as a null-terminated C string.
|
||||||
*
|
*
|
||||||
* Allows for unsafe manipulation of strings, which is useful for foreign
|
* Allows for unsafe manipulation of strings, which is useful for foreign
|
||||||
|
@ -2176,20 +2180,33 @@ pub fn as_bytes_slice<'a>(s: &'a str) -> &'a [u8] {
|
||||||
* # Example
|
* # Example
|
||||||
*
|
*
|
||||||
* ~~~ {.rust}
|
* ~~~ {.rust}
|
||||||
* let s = str::as_c_str("PATH", { |path| libc::getenv(path) });
|
* let s = "PATH".as_c_str(|path| libc::getenv(path));
|
||||||
* ~~~
|
* ~~~
|
||||||
*/
|
*/
|
||||||
#[inline]
|
fn as_c_str<T>(self, f: &fn(*libc::c_char) -> T) -> T;
|
||||||
pub fn as_c_str<T>(s: &str, f: &fn(*libc::c_char) -> T) -> T {
|
}
|
||||||
do as_buf(s) |buf, len| {
|
|
||||||
|
impl<'self> StrUtil for &'self str {
|
||||||
|
#[inline]
|
||||||
|
fn as_c_str<T>(self, f: &fn(*libc::c_char) -> T) -> T {
|
||||||
|
do as_buf(self) |buf, len| {
|
||||||
// NB: len includes the trailing null.
|
// NB: len includes the trailing null.
|
||||||
assert!(len > 0);
|
assert!(len > 0);
|
||||||
if unsafe { *(ptr::offset(buf,len-1)) != 0 } {
|
if unsafe { *(ptr::offset(buf,len-1)) != 0 } {
|
||||||
as_c_str(to_owned(s), f)
|
to_owned(self).as_c_str(f)
|
||||||
} else {
|
} else {
|
||||||
f(buf as *libc::c_char)
|
f(buf as *libc::c_char)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deprecated. Use the `as_c_str` method on strings instead.
|
||||||
|
*/
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn as_c_str<T>(s: &str, f: &fn(*libc::c_char) -> T) -> T {
|
||||||
|
s.as_c_str(f)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue