use std::sync::Arc;
use crate::error::Result;
pub trait CommunicationChannel: Send + Sync {
fn send_to_guest(&self, message: &[u8]) -> Result<()>;
fn receive_from_guest(&self) -> Result<Vec<u8>>;
fn has_messages(&self) -> bool;
fn close(&self) -> Result<()>;
}
type StringHandlerFunction = Box<dyn Fn(&str) -> Result<String> + Send + Sync + 'static>;
type ByteHandlerFunction = Box<dyn Fn(&[u8]) -> Result<Vec<u8>> + Send + Sync + 'static>;
pub trait RpcChannel: Send + Sync {
fn register_host_function_json(
&mut self,
name: &str,
function: StringHandlerFunction,
) -> Result<()>;
fn call_guest_function_json(
&self,
function_name: &str,
params_json: &str,
) -> Result<String>;
fn register_host_function_msgpack(
&mut self,
name: &str,
function: ByteHandlerFunction,
) -> Result<()>;
fn call_guest_function_msgpack(
&self,
function_name: &str,
params_msgpack: &[u8],
) -> Result<Vec<u8>>;
}
pub trait RpcChannelExt {
fn register_host_function<F, Params, Return>(
&mut self,
name: &str,
function: F,
) -> Result<()>
where
F: Fn(Params) -> Result<Return> + Send + Sync + 'static,
Params: serde::de::DeserializeOwned + 'static,
Return: serde::Serialize + 'static;
fn call_guest_function<Params, Return>(
&self,
function_name: &str,
params: &Params,
) -> Result<Return>
where
Params: serde::Serialize + ?Sized,
Return: serde::de::DeserializeOwned + 'static;
}
impl<T: RpcChannel> RpcChannelExt for T {
fn register_host_function<F, Params, Return>(
&mut self,
name: &str,
function: F,
) -> Result<()>
where
F: Fn(Params) -> Result<Return> + Send + Sync + 'static,
Params: serde::de::DeserializeOwned + 'static,
Return: serde::Serialize + 'static,
{
let wrapped_function = Box::new(move |params_json: &str| -> Result<String> {
let params: Params = serde_json::from_str(params_json)?;
let result = function(params)?;
let result_json = serde_json::to_string(&result)?;
Ok(result_json)
});
self.register_host_function_json(name, wrapped_function)
}
fn call_guest_function<Params, Return>(
&self,
function_name: &str,
params: &Params,
) -> Result<Return>
where
Params: serde::Serialize + ?Sized,
Return: serde::de::DeserializeOwned + 'static,
{
let params_json = serde_json::to_string(params)?;
let result_json = self.call_guest_function_json(function_name, ¶ms_json)?;
let result = serde_json::from_str(&result_json)?;
Ok(result)
}
}
pub trait CommunicationFactory: Send + Sync {
fn create_channel(&self) -> Result<Arc<dyn CommunicationChannel>>;
fn create_rpc_channel(&self) -> Result<Arc<dyn RpcChannel>>;
}
pub mod channels;
pub mod io;
pub mod rpc;
pub mod memory;
pub mod memory_channel;
pub mod streaming;
pub use memory_channel::{MemoryChannel, MemoryRpcChannel, MemoryChannelConfig};
pub use streaming::{StreamingChannel, StreamingInput, StreamingOutput, StreamingChannel2Way,
StreamChunk, StreamingManager, StreamingFactory};