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