Trait cstr_argument::CStrArgument [−][src]
pub trait CStrArgument: Debug + Sized {
type Output: AsRef<CStr>;
fn try_into_cstr(self) -> Result<Self::Output, NulError<Self>>;
fn into_cstr(self) -> Self::Output { ... }
}
Expand description
A trait for converting function arguments to null terminated strings. It can be used to convert string arguments that are passed on to C APIs using the minimal amount of allocations.
Strings that are already null terminated are just wrapped in a CStr without any allocations. Strings that are not already null terminated are converted to a CString possibly requiring one or more allocations. Trying to convert strings with a null byte in any position other than the final will result in an error.
Example
use std::os::raw::c_char;
use cstr_argument::CStrArgument;
extern "C" {
fn foo(s: *const c_char);
}
fn bar<S: CStrArgument>(s: S) {
let s = s.into_cstr();
unsafe {
foo(s.as_ref().as_ptr())
}
}
fn baz() {
bar("hello "); // Argument will be converted to a CString requiring an allocation
bar("world\0"); // Argument will be converted to a CStr without any allocations
bar("!".to_owned()); // Argument will be converted to a CString possibly requiring an
// allocation
}
Associated Types
Required methods
Provided methods
Returns the string with a null terminator.
Panics
This function will panic if the string contains a null byte at any position other
than the final. See try_into_cstr
for a non-panicking version
of this function.