remote_trait_object/
service.rs

1pub mod export_import;
2pub mod handle;
3pub mod id;
4mod null;
5pub mod serde_support;
6
7use crate::forwarder::ServiceObjectId;
8use crate::port::Port;
9use std::sync::Weak;
10
11pub use handle::Handle;
12pub use null::{create_null_service, NullService};
13pub type MethodId = u32;
14
15/// Exporter sides's interface to the service object. This will be implemented
16/// by each service trait's unique wrapper in the macro
17pub trait Dispatch: Send + Sync {
18    fn dispatch_and_call(&self, method: MethodId, args: &[u8]) -> Vec<u8>;
19}
20
21impl<F> Dispatch for F
22where
23    F: Fn(MethodId, &[u8]) -> Vec<u8> + Send + Sync,
24{
25    fn dispatch_and_call(&self, method: MethodId, args: &[u8]) -> Vec<u8> {
26        self(method, args)
27    }
28}
29
30/// The `Service` trait is a marker that is used as a supertrait for a service trait,
31/// indicating that the trait is for a service.
32///
33/// It is bound to `Send` and `Sync`, and that's all.
34/// Please put this as a supertrait for every service trait, and implement it
35/// for all concrete service implementers.
36///
37/**
38## Example
39```
40use remote_trait_object::*;
41
42#[service]
43pub trait Piano: Service {
44    fn play(&mut self);
45}
46
47struct Steinway;
48impl Service for Steinway {}
49impl Piano for Steinway {
50    fn play(&mut self) {
51        println!("Do Re Mi");
52    }
53}
54```
55**/
56pub trait Service: Send + Sync {}
57
58/// A serde de/serialization format that will be used for a service.
59pub trait SerdeFormat {
60    #[allow(clippy::result_unit_err)]
61    fn to_vec<S: serde::Serialize>(s: &S) -> Result<Vec<u8>, ()>;
62    #[allow(clippy::result_unit_err)]
63    fn from_slice<D: serde::de::DeserializeOwned>(data: &[u8]) -> Result<D, ()>;
64}
65
66/// In most case the format isn't important because the users won't see the raw data directly anyway.
67/// Thus we provide a default format for the macro.
68pub struct Cbor;
69
70impl SerdeFormat for Cbor {
71    fn to_vec<S: serde::Serialize>(s: &S) -> Result<Vec<u8>, ()> {
72        serde_cbor::to_vec(s).map_err(|_| ())
73    }
74
75    fn from_slice<D: serde::de::DeserializeOwned>(data: &[u8]) -> Result<D, ()> {
76        serde_cbor::from_slice(data).map_err(|_| ())
77    }
78}