quick_protobuf/
message.rs

1//! A module to deserialize a `Message` as defined in a .proto file
2//!
3//! Creates the struct and implements a reader
4
5#[cfg(feature = "std")]
6use std::fs::File;
7#[cfg(feature = "std")]
8use std::io::BufWriter;
9#[cfg(feature = "std")]
10use std::path::Path;
11
12use crate::errors::Result;
13use crate::reader::BytesReader;
14use crate::writer::{Writer, WriterBackend};
15
16/// A trait to handle deserialization based on parsed `Field`s
17pub trait MessageWrite: Sized {
18    /// Writes `Self` into W writer
19    fn write_message<W: WriterBackend>(&self, _: &mut Writer<W>) -> Result<()> {
20        Ok(())
21    }
22
23    /// Computes necessary binary size of self once serialized in protobuf
24    fn get_size(&self) -> usize {
25        0
26    }
27
28    /// Writes self into a file
29    #[cfg(feature = "std")]
30    fn write_file<P: AsRef<Path>>(&self, p: P) -> Result<()> {
31        let file = BufWriter::new(File::create(p)?);
32        let mut writer = Writer::new(file);
33        self.write_message(&mut writer)
34    }
35}
36
37/// A trait to handle deserialization from protocol buffers.
38pub trait MessageRead<'a>: Sized {
39    /// Constructs an instance of `Self` by reading from the given bytes
40    /// via the given reader.
41    ///
42    /// It does NOT read message length first. If you want to read a variable
43    /// length message, use `BytesReader::read_message` directly
44    fn from_reader(r: &mut BytesReader, bytes: &'a [u8]) -> Result<Self>;
45}