protobuf/
message.rs

1use std::io::Read;
2use std::io::Write;
3
4use crate::coded_output_stream::with::WithCodedOutputStream;
5use crate::error::ProtobufError;
6use crate::wire_format::check_message_size;
7use crate::CodedInputStream;
8use crate::CodedOutputStream;
9use crate::SpecialFields;
10use crate::UnknownFields;
11
12/// Trait which is implemented by all generated message.
13///
14/// Note, by default all generated messages also implement [`MessageFull`](crate::MessageFull)
15/// trait which provides access to reflection and features which depend on reflection
16/// (text format and JSON serialization).
17pub trait Message: Default + Clone + Send + Sync + Sized + PartialEq + 'static {
18    /// Message name as specified in `.proto` file.
19    ///
20    /// Message name can be accessed using
21    /// [`MessageFull::descriptor`](crate::MessageFull::descriptor),
22    /// but when lite runtime is requested, this field can be used.
23    const NAME: &'static str;
24
25    /// True iff all required fields are initialized.
26    /// Always returns `true` for protobuf 3.
27    fn is_initialized(&self) -> bool;
28
29    /// Update this message object with fields read from given stream.
30    fn merge_from(&mut self, is: &mut CodedInputStream) -> crate::Result<()>;
31
32    /// Parse message from stream.
33    fn parse_from(is: &mut CodedInputStream) -> crate::Result<Self> {
34        let mut r: Self = Message::new();
35        r.merge_from(is)?;
36        r.check_initialized()?;
37        Ok(r)
38    }
39
40    /// Write message to the stream.
41    ///
42    /// Sizes of this messages and nested messages must be cached
43    /// by calling `compute_size` prior to this call.
44    fn write_to_with_cached_sizes(&self, os: &mut CodedOutputStream) -> crate::Result<()>;
45
46    /// Compute and cache size of this message and all nested messages.
47    ///
48    /// Note if the computation overflows u32, the cached size is stored truncated.
49    fn compute_size(&self) -> u64;
50
51    /// Get size previously computed by `compute_size`.
52    ///
53    /// Note if message size exceeds u32, the cached size is stored truncated.
54    fn cached_size(&self) -> u32 {
55        self.special_fields().cached_size().get()
56    }
57
58    /// Write the message to the stream.
59    ///
60    /// Results in error if message is not fully initialized.
61    fn write_to(&self, os: &mut CodedOutputStream) -> crate::Result<()> {
62        self.check_initialized()?;
63
64        // cache sizes
65        let size = self.compute_size();
66        let size = check_message_size(size)?;
67        os.reserve_additional(size as u32, Self::NAME)?;
68        self.write_to_with_cached_sizes(os)?;
69
70        Ok(())
71    }
72
73    /// Write the message to the stream prepending the message with message length
74    /// encoded as varint.
75    fn write_length_delimited_to(&self, os: &mut CodedOutputStream) -> crate::Result<()> {
76        let size = self.compute_size();
77        let size = check_message_size(size)?;
78
79        os.reserve_additional_for_length_delimited(size, Self::NAME)?;
80
81        os.write_raw_varint32(size)?;
82
83        let written = os.total_bytes_written();
84
85        self.write_to_with_cached_sizes(os)?;
86
87        // Self-check.
88        assert_eq!(
89            written + size as u64,
90            os.total_bytes_written(),
91            "Expected to write {}, actually wrote {}",
92            size,
93            os.total_bytes_written() - written
94        );
95
96        Ok(())
97    }
98
99    /// Write the message to the vec, prepend the message with message length
100    /// encoded as varint.
101    fn write_length_delimited_to_vec(&self, vec: &mut Vec<u8>) -> crate::Result<()> {
102        let mut os = CodedOutputStream::vec(vec);
103        self.write_length_delimited_to(&mut os)?;
104        os.flush()?;
105        Ok(())
106    }
107
108    /// Update this message object with fields read from given stream.
109    fn merge_from_bytes(&mut self, bytes: &[u8]) -> crate::Result<()> {
110        let mut is = CodedInputStream::from_bytes(bytes);
111        self.merge_from(&mut is)
112    }
113
114    /// Parse message from reader.
115    /// Parse stops on EOF or when error encountered.
116    fn parse_from_reader(reader: &mut dyn Read) -> crate::Result<Self> {
117        let mut is = CodedInputStream::new(reader);
118        let r = Message::parse_from(&mut is)?;
119        is.check_eof()?;
120        Ok(r)
121    }
122
123    /// Parse message from byte array.
124    fn parse_from_bytes(bytes: &[u8]) -> crate::Result<Self> {
125        let mut is = CodedInputStream::from_bytes(bytes);
126        let r = Message::parse_from(&mut is)?;
127        is.check_eof()?;
128        Ok(r)
129    }
130
131    /// Parse message from `Bytes` object.
132    /// Resulting message may share references to the passed bytes object.
133    #[cfg(feature = "bytes")]
134    fn parse_from_tokio_bytes(bytes: &bytes::Bytes) -> crate::Result<Self> {
135        let mut is = CodedInputStream::from_tokio_bytes(bytes);
136        let r = Self::parse_from(&mut is)?;
137        is.check_eof()?;
138        Ok(r)
139    }
140
141    /// Check if all required fields of this object are initialized.
142    fn check_initialized(&self) -> crate::Result<()> {
143        if !self.is_initialized() {
144            Err(ProtobufError::MessageNotInitialized(Self::NAME.to_owned()).into())
145        } else {
146            Ok(())
147        }
148    }
149
150    /// Write the message to the writer.
151    fn write_to_writer(&self, w: &mut dyn Write) -> crate::Result<()> {
152        w.with_coded_output_stream(|os| self.write_to(os))
153    }
154
155    /// Write the message to bytes vec.
156    fn write_to_vec(&self, v: &mut Vec<u8>) -> crate::Result<()> {
157        v.with_coded_output_stream(|os| self.write_to(os))
158    }
159
160    /// Write the message to bytes vec.
161    ///
162    /// > **Note**: You can use [`Message::parse_from_bytes`]
163    /// to do the reverse.
164    fn write_to_bytes(&self) -> crate::Result<Vec<u8>> {
165        self.check_initialized()?;
166
167        let size = self.compute_size() as usize;
168        let mut v = Vec::with_capacity(size);
169        let mut os = CodedOutputStream::vec(&mut v);
170        self.write_to_with_cached_sizes(&mut os)?;
171        os.flush()?;
172        drop(os);
173        Ok(v)
174    }
175
176    /// Write the message to the writer, prepend the message with message length
177    /// encoded as varint.
178    fn write_length_delimited_to_writer(&self, w: &mut dyn Write) -> crate::Result<()> {
179        w.with_coded_output_stream(|os| self.write_length_delimited_to(os))
180    }
181
182    /// Write the message to the bytes vec, prepend the message with message length
183    /// encoded as varint.
184    fn write_length_delimited_to_bytes(&self) -> crate::Result<Vec<u8>> {
185        let mut v = Vec::new();
186        v.with_coded_output_stream(|os| self.write_length_delimited_to(os))?;
187        Ok(v)
188    }
189
190    /// Special fields (unknown fields and cached size).
191    fn special_fields(&self) -> &SpecialFields;
192    /// Special fields (unknown fields and cached size).
193    fn mut_special_fields(&mut self) -> &mut SpecialFields;
194
195    /// Get a reference to unknown fields.
196    fn unknown_fields(&self) -> &UnknownFields {
197        &self.special_fields().unknown_fields()
198    }
199    /// Get a mutable reference to unknown fields.
200    fn mut_unknown_fields(&mut self) -> &mut UnknownFields {
201        self.mut_special_fields().mut_unknown_fields()
202    }
203
204    /// Create an empty message object.
205    ///
206    /// ```
207    /// # use protobuf::MessageFull;
208    /// # fn foo<MyMessage: MessageFull>() {
209    /// let m = MyMessage::new();
210    /// # }
211    /// ```
212    fn new() -> Self;
213
214    /// Reset all fields.
215    fn clear(&mut self) {
216        *self = Self::new();
217    }
218
219    /// Return a pointer to default immutable message with static lifetime.
220    ///
221    /// ```
222    /// # use protobuf::MessageFull;
223    /// # fn foo<MyMessage: MessageFull>() {
224    /// let m: &MyMessage = MyMessage::default_instance();
225    /// # }
226    /// ```
227    fn default_instance() -> &'static Self;
228}