use crate::PluginSession;
use std::error::Error;
use std::hash::{Hash, Hasher};
use std::fmt;
use std::ops::Deref;
use std::sync::Arc;
#[derive(Debug, Clone, Copy)]
pub struct NullHandleError;
impl Error for NullHandleError {}
impl fmt::Display for NullHandleError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("A null session handle was provided.")
}
}
#[derive(Debug, Clone)]
pub struct SessionWrapper<T> {
pub handle: *mut PluginSession,
state: T,
}
impl<T> Hash for SessionWrapper<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.handle.hash(state);
}
}
impl<T> PartialEq for SessionWrapper<T> {
fn eq(&self, other: &Self) -> bool {
self.handle == other.handle
}
}
impl<T> Eq for SessionWrapper<T> {}
impl<T> SessionWrapper<T> {
pub unsafe fn associate(handle: *mut PluginSession, state: T) -> Result<Box<Arc<Self>>, NullHandleError> {
match handle.as_mut() {
Some(x) => {
let mut result = Box::new(Arc::new(Self { handle, state }));
x.plugin_handle = result.as_mut() as *mut Arc<Self> as *mut _;
Ok(result)
}
None => Err(NullHandleError),
}
}
pub unsafe fn from_ptr(handle: *mut PluginSession) -> Result<Arc<Self>, NullHandleError> {
match handle.as_ref() {
Some(x) => Ok(Arc::clone(
(x.plugin_handle as *mut Arc<Self>).as_ref().unwrap()
)),
None => Err(NullHandleError),
}
}
pub fn as_ptr(&self) -> *mut PluginSession {
self.handle
}
}
impl<T> Deref for SessionWrapper<T> {
type Target = T;
fn deref(&self) -> &T {
&self.state
}
}
impl<T> Drop for SessionWrapper<T> {
fn drop(&mut self) {
unsafe {
let refcount = &(*self.handle).ref_;
super::refcount::decrease(refcount);
}
}
}
unsafe impl<T: Sync> Sync for SessionWrapper<T> {}
unsafe impl<T: Send> Send for SessionWrapper<T> {}