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
use std::convert::Infallible;
use std::error::Error;
use std::marker::PhantomData;
use std::sync::Arc;
use crate::{ToForeignTraitObject, TraitObject};
use super::null_ptr_error;
use super::{FromForeign, InputType, ReturnType, ToForeign};
pub struct ArcMarshaler<T: ?Sized>(PhantomData<T>);
impl<T: ?Sized> InputType for ArcMarshaler<T> {
type Foreign = *const T;
type ForeignTraitObject = ();
}
impl<T: ?Sized> ReturnType for ArcMarshaler<T> {
type Foreign = *const T;
type ForeignTraitObject = TraitObject<T>;
fn foreign_default() -> Self::Foreign {
panic!("Unrepresentable!");
}
}
impl<T: ?Sized> ToForeign<Arc<T>, *const T> for ArcMarshaler<T> {
type Error = Infallible;
#[inline(always)]
fn to_foreign(local: Arc<T>) -> Result<*const T, Self::Error> {
log::debug!(
"<ArcMarshaler<{ty}> as ToForeign<{ty}, {o}>>::to_foreign",
ty = std::any::type_name::<T>(),
o = "*const c_void"
);
Ok(Arc::into_raw(local))
}
}
impl<T: ?Sized> FromForeign<*const T, Arc<T>> for ArcMarshaler<T> {
type Error = Box<dyn Error>;
#[inline(always)]
unsafe fn from_foreign(foreign: *const T) -> Result<Arc<T>, Self::Error> {
log::debug!(
"<ArcMarshaler<{ty}> as FromForeign<*const std::ffi::c_void, T>>::from_foreign({:?})",
foreign,
ty = std::any::type_name::<T>()
);
if foreign.is_null() {
return Err(null_ptr_error());
}
Ok(Arc::from_raw(foreign as *const _))
}
}
impl<T: ?Sized> ToForeign<Result<Arc<T>, Box<dyn Error>>, *const T> for ArcMarshaler<T> {
type Error = Box<dyn Error>;
#[inline(always)]
fn to_foreign(local: Result<Arc<T>, Box<dyn Error>>) -> Result<*const T, Self::Error> {
local.and_then(|x| Ok(Arc::into_raw(x) as *const _))
}
}