Cotton code
79 lines · 2.4 KB · RustRaw
//! Owned results from the existing C ABI, with exactly one matching free.use cotton_ffi::{cotton_call, cotton_close, cotton_open, cotton_string_free, CottonHandle};use std::ffi::{c_char, CStr, CString};#[derive(Debug, thiserror::Error)]pub(crate) enum Error {    #[error("{0}")]    Jni(#[from] jni::errors::Error),    #[error("the core refused to open: {0}")]    Open(String),    #[error("{0}")]    Invalid(String),}pub(crate) type Result<T> = std::result::Result<T, Error>;pub(crate) fn c_string(text: &str) -> Result<CString> {    CString::new(text).map_err(|_| Error::Invalid("a native argument contains a NUL byte".into()))}pub(crate) struct OwnedString(pub *mut c_char);impl OwnedString {    pub(crate) fn take(self) -> Result<String> {        if self.0.is_null() {            return Err(Error::Invalid("the core returned no answer".into()));        }        // SAFETY: only C ABI owned-string results construct this wrapper.        unsafe { CStr::from_ptr(self.0) }            .to_str()            .map(str::to_owned)            .map_err(|_| Error::Invalid("the core returned invalid UTF-8".into()))    }}impl Drop for OwnedString {    fn drop(&mut self) {        // SAFETY: this wrapper uniquely owns the C ABI result, including on errors.        unsafe { cotton_string_free(self.0) };    }}pub(crate) struct Core(pub *mut CottonHandle);// SAFETY: CottonHandle supports concurrent calls (the Swift adapter uses them).// The JNI registry holds this owner behind a read/write lock; close takes the// exclusive side, so no call can use a closed pointer.unsafe impl Send for Core {}unsafe impl Sync for Core {}impl Core {    pub(crate) fn open(config: &str) -> Result<Self> {        let config = c_string(config)?;        let mut error = std::ptr::null_mut();        let pointer = unsafe { cotton_open(config.as_ptr(), &mut error) };        let error = OwnedString(error);        if pointer.is_null() {            return Err(Error::Open(error.take()?));        }        Ok(Self(pointer))    }    pub(crate) fn call(&self, method: &str, request: &str) -> Result<String> {        let method = c_string(method)?;        let request = c_string(request)?;        OwnedString(unsafe { cotton_call(self.0, method.as_ptr(), request.as_ptr()) }).take()    }}impl Drop for Core {    fn drop(&mut self) {        unsafe { cotton_close(self.0) };    }}#[cfg(test)]#[path = "native_tests.rs"]mod tests;