use bytes::Bytes;
use serde::Deserialize;
use serde::Serialize;
use crate::error::Error;
use crate::error::Result;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Envelope {
pub namespace: String,
pub payload: Bytes,
}
impl Envelope {
pub fn new(namespace: impl Into<String>, payload: Bytes) -> Self {
Self {
namespace: namespace.into(),
payload,
}
}
pub fn encode(&self) -> Result<Vec<u8>> {
rings_codec::serialize(self).map_err(|_| Error::EncodeError)
}
pub fn decode(bytes: &[u8]) -> Result<Self> {
rings_codec::deserialize(bytes).map_err(|_| Error::DecodeError)
}
pub(crate) fn view(bytes: &[u8]) -> Result<EnvelopeView<'_>> {
match rings_codec::deserialize_prefix(bytes) {
Ok((view, [])) => Ok(view),
Ok(_) | Err(_) => Err(Error::DecodeError),
}
}
pub(crate) fn namespace_prefix(namespace: &str) -> Result<Vec<u8>> {
rings_codec::serialize(&namespace).map_err(|_| Error::EncodeError)
}
}
#[derive(Deserialize)]
pub(crate) struct EnvelopeView<'a> {
pub(crate) namespace: &'a str,
pub(crate) payload: &'a [u8],
}
#[cfg(test)]
mod tests {
use bytes::Bytes;
use super::Envelope;
#[test]
fn test_viewing_an_envelope_reads_what_decoding_reads() {
let envelope = Envelope::new("relay", Bytes::from_static(b"payload"));
let bytes = envelope.encode().expect("an envelope encodes");
let view = Envelope::view(&bytes).expect("an encoded envelope is read in place");
assert_eq!(view.namespace, envelope.namespace);
assert_eq!(view.payload, envelope.payload.as_ref());
assert!(Envelope::view(&bytes[..bytes.len() - 1]).is_err());
}
}