prost/
message.rs

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