1 use std::io::Read; 2 use std::io::Write; 3 4 use crate::coded_output_stream::with::WithCodedOutputStream; 5 use crate::error::ProtobufError; 6 use crate::wire_format::check_message_size; 7 use crate::CodedInputStream; 8 use crate::CodedOutputStream; 9 use crate::SpecialFields; 10 use 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). 17 pub 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. is_initialized(&self) -> bool27 fn is_initialized(&self) -> bool; 28 29 /// Update this message object with fields read from given stream. merge_from(&mut self, is: &mut CodedInputStream) -> crate::Result<()>30 fn merge_from(&mut self, is: &mut CodedInputStream) -> crate::Result<()>; 31 32 /// Parse message from stream. parse_from(is: &mut CodedInputStream) -> crate::Result<Self>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. write_to_with_cached_sizes(&self, os: &mut CodedOutputStream) -> crate::Result<()>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. compute_size(&self) -> u6449 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. cached_size(&self) -> u3254 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. write_to(&self, os: &mut CodedOutputStream) -> crate::Result<()>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. write_length_delimited_to(&self, os: &mut CodedOutputStream) -> crate::Result<()>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. write_length_delimited_to_vec(&self, vec: &mut Vec<u8>) -> crate::Result<()>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. merge_from_bytes(&mut self, bytes: &[u8]) -> crate::Result<()>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. parse_from_reader(reader: &mut dyn Read) -> crate::Result<Self>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. parse_from_bytes(bytes: &[u8]) -> crate::Result<Self>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")] parse_from_tokio_bytes(bytes: &bytes::Bytes) -> crate::Result<Self>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. check_initialized(&self) -> crate::Result<()>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. write_to_writer(&self, w: &mut dyn Write) -> crate::Result<()>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. write_to_vec(&self, v: &mut Vec<u8>) -> crate::Result<()>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. write_to_bytes(&self) -> crate::Result<Vec<u8>>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. write_length_delimited_to_writer(&self, w: &mut dyn Write) -> crate::Result<()>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. write_length_delimited_to_bytes(&self) -> crate::Result<Vec<u8>>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). special_fields(&self) -> &SpecialFields191 fn special_fields(&self) -> &SpecialFields; 192 /// Special fields (unknown fields and cached size). mut_special_fields(&mut self) -> &mut SpecialFields193 fn mut_special_fields(&mut self) -> &mut SpecialFields; 194 195 /// Get a reference to unknown fields. unknown_fields(&self) -> &UnknownFields196 fn unknown_fields(&self) -> &UnknownFields { 197 &self.special_fields().unknown_fields() 198 } 199 /// Get a mutable reference to unknown fields. mut_unknown_fields(&mut self) -> &mut UnknownFields200 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 /// ``` new() -> Self212 fn new() -> Self; 213 214 /// Reset all fields. clear(&mut self)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 /// ``` default_instance() -> &'static Self227 fn default_instance() -> &'static Self; 228 } 229