ibc_types_domain_type/
lib.rs

1//! Provides a marker type capturing the relationship between a domain type and a protobuf type.
2#![no_std]
3// Requires nightly.
4#![cfg_attr(docsrs, feature(doc_auto_cfg))]
5
6extern crate alloc;
7#[cfg(any(test, feature = "std"))]
8extern crate std;
9
10mod prelude;
11use prelude::*;
12
13/// A marker type that captures the relationships between a domain type (`Self`) and a protobuf type (`Self::Proto`).
14pub trait DomainType
15where
16    Self: Clone + Sized + TryFrom<Self::Proto>,
17    Self::Proto: prost::Message + prost::Name + Default + From<Self> + Send + Sync + 'static,
18    <Self as TryFrom<Self::Proto>>::Error: Into<anyhow::Error> + Send + Sync + 'static,
19{
20    type Proto;
21
22    /// Encode this domain type to a byte vector, via proto type `P`.
23    fn encode_to_vec(&self) -> Vec<u8> {
24        use prost::Message;
25        self.to_proto().encode_to_vec()
26    }
27
28    /// Convert this domain type to the associated proto type.
29    ///
30    /// This uses the `From` impl internally, so it works exactly
31    /// like `.into()`, but does not require type inference.
32    fn to_proto(&self) -> Self::Proto {
33        Self::Proto::from(self.clone())
34    }
35
36    /// Decode this domain type from a byte buffer, via proto type `P`.
37    fn decode<B: bytes::Buf>(buf: B) -> Result<Self, anyhow::Error> {
38        <Self::Proto as prost::Message>::decode(buf)
39            .map_err(anyhow::Error::msg)?
40            .try_into()
41            .map_err(Into::into)
42    }
43}