prost/
message.rs

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