prost/
message.rs

1#[cfg(not(feature = "std"))]
2use alloc::boxed::Box;
3#[cfg(not(feature = "std"))]
4use alloc::vec::Vec;
5
6use core::fmt::Debug;
7
8use bytes::{Buf, BufMut};
9
10use crate::encoding::varint::{encode_varint, encoded_len_varint};
11use crate::encoding::wire_type::WireType;
12use crate::encoding::{decode_key, message, DecodeContext};
13use crate::DecodeError;
14use crate::EncodeError;
15
16/// A Protocol Buffers message.
17pub trait Message: Debug + Send + Sync {
18    /// Encodes the message to a buffer.
19    ///
20    /// This method will panic if the buffer has insufficient capacity.
21    ///
22    /// Meant to be used only by `Message` implementations.
23    #[doc(hidden)]
24    fn encode_raw(&self, buf: &mut impl BufMut)
25    where
26        Self: Sized;
27
28    /// Decodes a field from a buffer, and merges it into `self`.
29    ///
30    /// Meant to be used only by `Message` implementations.
31    #[doc(hidden)]
32    fn merge_field(
33        &mut self,
34        tag: u32,
35        wire_type: WireType,
36        buf: &mut impl Buf,
37        ctx: DecodeContext,
38    ) -> Result<(), DecodeError>
39    where
40        Self: Sized;
41
42    /// Returns the encoded length of the message without a length delimiter.
43    fn encoded_len(&self) -> usize;
44
45    /// Encodes the message to a buffer.
46    ///
47    /// An error will be returned if the buffer does not have sufficient capacity.
48    fn encode(&self, buf: &mut impl BufMut) -> Result<(), EncodeError>
49    where
50        Self: Sized,
51    {
52        let required = self.encoded_len();
53        let remaining = buf.remaining_mut();
54        if required > remaining {
55            return Err(EncodeError::new(required, remaining));
56        }
57
58        self.encode_raw(buf);
59        Ok(())
60    }
61
62    /// Encodes the message to a newly allocated buffer.
63    fn encode_to_vec(&self) -> Vec<u8>
64    where
65        Self: Sized,
66    {
67        let mut buf = Vec::with_capacity(self.encoded_len());
68
69        self.encode_raw(&mut buf);
70        buf
71    }
72
73    /// Encodes the message with a length-delimiter to a buffer.
74    ///
75    /// An error will be returned if the buffer does not have sufficient capacity.
76    fn encode_length_delimited(&self, buf: &mut impl BufMut) -> Result<(), EncodeError>
77    where
78        Self: Sized,
79    {
80        let len = self.encoded_len();
81        let required = len + encoded_len_varint(len as u64);
82        let remaining = buf.remaining_mut();
83        if required > remaining {
84            return Err(EncodeError::new(required, remaining));
85        }
86        encode_varint(len as u64, buf);
87        self.encode_raw(buf);
88        Ok(())
89    }
90
91    /// Encodes the message with a length-delimiter to a newly allocated buffer.
92    fn encode_length_delimited_to_vec(&self) -> Vec<u8>
93    where
94        Self: Sized,
95    {
96        let len = self.encoded_len();
97        let mut buf = Vec::with_capacity(len + encoded_len_varint(len as u64));
98
99        encode_varint(len as u64, &mut buf);
100        self.encode_raw(&mut buf);
101        buf
102    }
103
104    /// Decodes an instance of the message from a buffer.
105    ///
106    /// The entire buffer will be consumed.
107    fn decode(mut buf: impl Buf) -> Result<Self, DecodeError>
108    where
109        Self: Default,
110    {
111        let mut message = Self::default();
112        Self::merge(&mut message, &mut buf).map(|_| message)
113    }
114
115    /// Decodes a length-delimited instance of the message from the buffer.
116    fn decode_length_delimited(buf: impl Buf) -> Result<Self, DecodeError>
117    where
118        Self: Default,
119    {
120        let mut message = Self::default();
121        message.merge_length_delimited(buf)?;
122        Ok(message)
123    }
124
125    /// Decodes an instance of the message from a buffer, and merges it into `self`.
126    ///
127    /// The entire buffer will be consumed.
128    fn merge(&mut self, mut buf: impl Buf) -> Result<(), DecodeError>
129    where
130        Self: Sized,
131    {
132        let ctx = DecodeContext::default();
133        while buf.has_remaining() {
134            let (tag, wire_type) = decode_key(&mut buf)?;
135            self.merge_field(tag, wire_type, &mut buf, ctx.clone())?;
136        }
137        Ok(())
138    }
139
140    /// Decodes a length-delimited instance of the message from buffer, and
141    /// merges it into `self`.
142    fn merge_length_delimited(&mut self, mut buf: impl Buf) -> Result<(), DecodeError>
143    where
144        Self: Sized,
145    {
146        message::merge(
147            WireType::LengthDelimited,
148            self,
149            &mut buf,
150            DecodeContext::default(),
151        )
152    }
153
154    /// Clears the message, resetting all fields to their default.
155    fn clear(&mut self);
156}
157
158impl<M> Message for Box<M>
159where
160    M: Message,
161{
162    fn encode_raw(&self, buf: &mut impl BufMut) {
163        (**self).encode_raw(buf)
164    }
165    fn merge_field(
166        &mut self,
167        tag: u32,
168        wire_type: WireType,
169        buf: &mut impl Buf,
170        ctx: DecodeContext,
171    ) -> Result<(), DecodeError> {
172        (**self).merge_field(tag, wire_type, buf, ctx)
173    }
174    fn encoded_len(&self) -> usize {
175        (**self).encoded_len()
176    }
177    fn clear(&mut self) {
178        (**self).clear()
179    }
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185
186    const _MESSAGE_IS_OBJECT_SAFE: Option<&dyn Message> = None;
187}