1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
use super::PluginSession;
use std::error::Error;
use std::fmt;
use std::ops::Deref;
use std::sync::Arc;
#[derive(Debug)]
pub struct NullHandleError;
impl Error for NullHandleError {
fn description(&self) -> &str {
"A null session handle was provided."
}
}
impl fmt::Display for NullHandleError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.description())
}
}
#[derive(Debug)]
pub struct SessionWrapper<T> {
pub handle: *mut PluginSession,
state: T,
}
impl<T> SessionWrapper<T> {
pub fn associate(handle: *mut PluginSession, state: T) -> Result<Box<Arc<Self>>, NullHandleError> {
unsafe {
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 fn from_ptr<'a>(handle: *mut PluginSession) -> Result<Arc<Self>, NullHandleError> {
unsafe {
match handle.as_ref() {
Some(x) => Ok(Arc::clone(
(x.plugin_handle as *mut Arc<Self>).as_ref().unwrap(),
)),
None => Err(NullHandleError),
}
}
}
}
impl<T> Deref for SessionWrapper<T> {
type Target = T;
fn deref(&self) -> &T {
&self.state
}
}
unsafe impl<T: Sync> Sync for SessionWrapper<T> {}
unsafe impl<T: Send> Send for SessionWrapper<T> {}
#[cfg(test)]
mod tests {
use super::*;
use std::ptr;
#[test]
fn handle_round_trip() {
struct State(i32);
let mut handle = PluginSession {
gateway_handle: ptr::null_mut(),
plugin_handle: ptr::null_mut(),
stopped_bitfield: 0,
__padding: Default::default(),
};
let ptr = &mut handle as *mut _;
let session = SessionWrapper::associate(ptr, State(42)).unwrap();
assert_eq!(session.as_ref() as *const _ as *mut _, handle.plugin_handle);
assert_eq!(SessionWrapper::<State>::from_ptr(ptr).unwrap().state.0, 42);
}
}