pub trait CStrArgument: Debug + Sized {
type Output: AsRef<CStr>;
// Required method
fn try_into_cstr(self) -> Result<Self::Output, NulError<Self>>;
// Provided method
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
}Required Associated Types§
Required Methods§
Provided Methods§
Sourcefn into_cstr(self) -> Self::Output
fn into_cstr(self) -> Self::Output
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.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.