orceh 0.1.1

Easier plugin interfaces
Documentation
use std::ffi::c_void;
use std::path::PathBuf;

use thiserror::Error;

pub use orceh_derive::dylib;

pub mod _exports {
    pub use libloading;
}

#[derive(Error, Debug)]
pub enum Error {
    #[error("unable to find library: `{0}`")]
    LibraryNotFound(PathBuf),
    #[error("unable to find symbol `{1}` in `{0}`")]
    SymbolNotFound(PathBuf, String),
}

#[macro_export]
macro_rules! mk_opaque {
    ($vis:vis $name:ident($data:ty)) => {
        #[repr(transparent)]
        $vis struct $name(*mut std::ffi::c_void);

        impl $crate::OpaquePtr for $name {
            type Data = $data;

            fn as_ptr(&self) -> *mut std::ffi::c_void {
                self.0
            }
            fn from_ptr(ptr: *mut std::ffi::c_void) -> Self {
                Self(ptr)
            }
        }
    };
}

pub trait OpaquePtr: Sized {
    type Data;

    fn as_ptr(&self) -> *mut c_void;

    fn from_ptr(ptr: *mut c_void) -> Self;

    fn as_ref(&self) -> &Self::Data { unsafe { &*(self.as_ptr() as *const Self::Data) } }

    fn as_mut(&mut self) -> &mut Self::Data { unsafe { &mut *(self.as_ptr() as *mut Self::Data) } }

    fn from_ref(data: &Self::Data) -> Self {
        Self::from_ptr(std::ptr::from_ref(data) as *mut c_void)
    }

    fn from_mut(data: &mut Self::Data) -> Self {
        Self::from_ptr(std::ptr::from_mut(data) as *mut c_void)
    }

    fn new(data: Self::Data) -> Self {
        Self::from_ptr(Box::into_raw(Box::new(data)) as *mut c_void)
    }

    /// # Safety
    /// Should not be called on a struct that was created with `Self::from_mut` or `Self::from_ref`, only from `Self::new`,
    /// otherwise, if you don't forget the data taken from here, you might create a double drop.
    unsafe fn take(self) -> Option<Self::Data> {
        let ptr = self.as_ptr() as *mut Self::Data;
        if ptr.is_null() {
            return None;
        }

        Some(unsafe { *Box::from_raw(ptr) })
    }
}

#[cfg(test)]
#[path = "../tests/mod.rs"]
mod test;