Skip to main content

rings_node/extension/ext/
envelope.rs

1#![warn(missing_docs)]
2//! Wire envelope — the namespaced message carried over the P2P transport.
3
4use bytes::Bytes;
5use serde::Deserialize;
6use serde::Serialize;
7
8use crate::error::Error;
9use crate::error::Result;
10
11/// Namespaced message envelope carried over the P2P transport (bincode), in place of
12/// the old closed `BackendMessage` enum. `payload` is opaque to the core.
13#[derive(Clone, Debug, Serialize, Deserialize)]
14pub struct Envelope {
15    /// Protocol namespace this payload belongs to.
16    pub namespace: String,
17    /// Opaque protocol payload; the inner codec is the protocol's own business.
18    pub payload: Bytes,
19}
20
21impl Envelope {
22    /// Build an envelope.
23    pub fn new(namespace: impl Into<String>, payload: Bytes) -> Self {
24        Self {
25            namespace: namespace.into(),
26            payload,
27        }
28    }
29
30    /// Encode for the P2P transport. `encode : Envelope → [u8]`.
31    pub fn encode(&self) -> Result<Vec<u8>> {
32        bincode::serialize(self).map_err(|_| Error::EncodeError)
33    }
34
35    /// Decode from the P2P transport. `decode : [u8] ⇀ Envelope` (partial).
36    pub fn decode(bytes: &[u8]) -> Result<Self> {
37        bincode::deserialize(bytes).map_err(|_| Error::DecodeError)
38    }
39}