Trait cstr_argument::CStrArgument [] [src]

pub trait CStrArgument: Debug + Sized {
    type Output: AsRef<CStr>;
    fn into_cstr(self) -> Result<Self::Output, NulError<Self>>;
}

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().expect("argument contained interior nulls");
    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

The type of the string after conversion. The type may or may not own the resulting string.

Required Methods

The function that converts the string.

Errors

This function will return an error if the string contains a null byte at any position other than the final.

Implementors