Trait CStrLike

Source
pub trait CStrLike {
    type Baked: Deref<Target = CStr>;
    type Error: Debug + Display;

    // Required methods
    fn bake(self) -> Result<Self::Baked, Self::Error>;
    fn into_c_string(self) -> Result<CString, Self::Error>;
}
Expand description

Value which can be converted into a C string.

The trait is used as argument to functions which wish to accept either &str or &CStr arguments while internally need to interact with C APIs. Accepting &str may be more convenient for users but requires conversion into CString internally which requires allocation. With this trait, latency-conscious users may choose to prepare CStr in advance and then pass it directly without having to incur the conversion cost.

To use the trait, function should accept impl CStrLike and after baking the argument (with CStrLike::bake method) it can use it as a &CStr (since the baked result dereferences into CStr).

§Example

use std::ffi::{CStr, CString};
use rocksdb::CStrLike;

fn strlen(arg: impl CStrLike) -> std::result::Result<usize, String> {
    let baked = arg.bake().map_err(|err| err.to_string())?;
    Ok(unsafe { libc::strlen(baked.as_ptr()) })
}

const FOO: &str = "foo";
const BAR: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b"bar\0") };

assert_eq!(Ok(3), strlen(FOO));
assert_eq!(Ok(3), strlen(BAR));

Required Associated Types§

Required Methods§

Source

fn bake(self) -> Result<Self::Baked, Self::Error>

Bakes self into value which can be freely converted into &CStr.

This may require allocation and may fail if self has invalid value.

Source

fn into_c_string(self) -> Result<CString, Self::Error>

Consumers and converts value into an owned CString.

If Self is already a CString simply returns it; if it’s a reference to a CString then the value is cloned. In other cases this may require allocation and may fail if self has invalid value.

Implementations on Foreign Types§

Source§

impl CStrLike for &str

Source§

impl CStrLike for &String

Source§

impl CStrLike for &CStr

Source§

impl CStrLike for CString

Source§

impl<'a> CStrLike for &'a CString

Source§

type Baked = &'a CStr

Source§

type Error = Infallible

Source§

fn bake(self) -> Result<Self::Baked, Self::Error>

Source§

fn into_c_string(self) -> Result<CString, Self::Error>

Implementors§