rings_node/extension/ext/
envelope.rs1use bytes::Bytes;
4use serde::Deserialize;
5use serde::Serialize;
6
7use crate::error::Error;
8use crate::error::Result;
9
10#[derive(Clone, Debug, Serialize, Deserialize)]
13pub struct Envelope {
14 pub namespace: String,
16 pub payload: Bytes,
18}
19
20impl Envelope {
21 pub fn new(namespace: impl Into<String>, payload: Bytes) -> Self {
23 Self {
24 namespace: namespace.into(),
25 payload,
26 }
27 }
28
29 pub fn encode(&self) -> Result<Vec<u8>> {
31 rings_codec::serialize(self).map_err(|_| Error::EncodeError)
32 }
33
34 pub fn decode(bytes: &[u8]) -> Result<Self> {
36 rings_codec::deserialize(bytes).map_err(|_| Error::DecodeError)
37 }
38
39 pub(crate) fn view(bytes: &[u8]) -> Result<EnvelopeView<'_>> {
42 match rings_codec::deserialize_prefix(bytes) {
43 Ok((view, [])) => Ok(view),
44 Ok(_) | Err(_) => Err(Error::DecodeError),
45 }
46 }
47
48 pub(crate) fn namespace_prefix(namespace: &str) -> Result<Vec<u8>> {
52 rings_codec::serialize(&namespace).map_err(|_| Error::EncodeError)
53 }
54}
55
56#[derive(Deserialize)]
64pub(crate) struct EnvelopeView<'a> {
65 pub(crate) namespace: &'a str,
67 pub(crate) payload: &'a [u8],
69}
70
71#[cfg(test)]
72mod tests {
73 use bytes::Bytes;
74
75 use super::Envelope;
76
77 #[test]
79 fn test_viewing_an_envelope_reads_what_decoding_reads() {
80 let envelope = Envelope::new("relay", Bytes::from_static(b"payload"));
81 let bytes = envelope.encode().expect("an envelope encodes");
82 let view = Envelope::view(&bytes).expect("an encoded envelope is read in place");
83 assert_eq!(view.namespace, envelope.namespace);
84 assert_eq!(view.payload, envelope.payload.as_ref());
85 assert!(Envelope::view(&bytes[..bytes.len() - 1]).is_err());
86 }
87}