fcplug_rclib/
protobuf.rs

1use std::fmt::Debug;
2
3use protobuf::{Message, ProtobufError};
4
5use crate::{abi, ABIResult, Buffer, FFIResult};
6use crate::abi::{ABIMessage, ABIRequest, ABIResponse, LeakBuffer, OriginType};
7
8#[inline]
9pub fn callback<'a, A, R, F>(_ffi_method_name: &'static str, f: F, args: &'a Buffer) -> FFIResult
10    where A: Message,
11          R: Message,
12          F: Fn(A) -> ABIResult<R> {
13    abi::callback::<'a, PbMessage<A>, PbMessage<R>, _>(_ffi_method_name, |req| {
14        f(req.0).map(PbMessage)
15    }, args)
16}
17
18#[derive(Debug)]
19pub struct PbMessage<T: Message>(T);
20
21impl<T: Message> PbMessage<T> {
22    pub fn new(v: T) -> Self {
23        Self(v)
24    }
25}
26
27impl<'a, T: Message> ABIRequest<'a> for PbMessage<T> {
28    type DecodeError = ProtobufError;
29
30    fn try_from_bytes(buf: &'a [u8]) -> Result<Self, Self::DecodeError> where Self: Sized {
31        T::parse_from_bytes(buf).map(PbMessage)
32    }
33}
34
35impl<T: Message> ABIResponse for PbMessage<T> {
36    type EncodeError = ProtobufError;
37    const ORIGIN_TYPE_FOR_FREE: OriginType = OriginType::Vec;
38
39    fn try_into_buffer(self) -> Result<LeakBuffer, Self::EncodeError> {
40        self.0.write_to_bytes().map(|v| LeakBuffer::from_vec(v))
41    }
42}
43
44impl<'a, T: Message> ABIMessage<'a> for PbMessage<T> {}