zbus/message/
body.rs

1use zvariant::{
2    serialized::{self, Data},
3    Signature, Type,
4};
5
6use crate::{Error, Message, Result};
7
8/// The body of a message.
9///
10/// This contains the bytes and the signature of the body.
11#[derive(Clone, Debug)]
12pub struct Body {
13    data: Data<'static, 'static>,
14    msg: Message,
15}
16
17impl Body {
18    pub(super) fn new(data: Data<'static, 'static>, msg: Message) -> Self {
19        Self { data, msg }
20    }
21
22    /// Deserialize the body using the contained signature.
23    pub fn deserialize<'s, B>(&'s self) -> Result<B>
24    where
25        B: zvariant::DynamicDeserialize<'s>,
26    {
27        let body_sig = self.signature();
28
29        self.data
30            .deserialize_for_dynamic_signature(body_sig)
31            .map_err(Error::from)
32            .map(|b| b.0)
33    }
34
35    /// Deserialize the body (without checking signature matching).
36    pub fn deserialize_unchecked<'d, 'm: 'd, B>(&'m self) -> Result<B>
37    where
38        B: serde::de::Deserialize<'d> + Type,
39    {
40        self.data.deserialize().map_err(Error::from).map(|b| b.0)
41    }
42
43    /// The signature of the body.
44    pub fn signature(&self) -> &Signature {
45        self.msg.quick_fields().signature()
46    }
47
48    /// The length of the body in bytes.
49    pub fn len(&self) -> usize {
50        self.data.len()
51    }
52
53    /// Whether the body is empty.
54    pub fn is_empty(&self) -> bool {
55        self.data.is_empty()
56    }
57
58    /// Get a reference to the underlying byte encoding of the message.
59    pub fn data(&self) -> &serialized::Data<'static, 'static> {
60        &self.data
61    }
62
63    /// Reference to the message this body belongs to.
64    pub fn message(&self) -> &Message {
65        &self.msg
66    }
67}