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 { ... }
}

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

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

Required Methods

Returns the string with a null terminator or an error.

Errors

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

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.

Implementations on Foreign Types

impl<'a> CStrArgument for CString
[src]

[src]

[src]

impl<'a> CStrArgument for &'a CString
[src]

[src]

[src]

impl<'a> CStrArgument for &'a CStr
[src]

[src]

[src]

impl CStrArgument for String
[src]

[src]

[src]

impl<'a> CStrArgument for &'a String
[src]

[src]

[src]

impl<'a> CStrArgument for &'a str
[src]

[src]

[src]

impl<'a> CStrArgument for Vec<u8>
[src]

[src]

[src]

impl<'a> CStrArgument for &'a Vec<u8>
[src]

[src]

[src]

impl<'a> CStrArgument for &'a [u8]
[src]

[src]

[src]

Implementors