tafia / quick-protobuf

A rust implementation of protobuf parser
MIT License
452 stars 87 forks source link

feature request: allow direct writing into `WriterBackend` #236

Open dignifiedquire opened 1 year ago

dignifiedquire commented 1 year ago

I have the following situation, a field in my protobuf (when stored in rust) needs encoding to bytes before it can get stored in the protobuf. I would like to avoid the temporary allocation of storing it in a Vec, and directly write it into the WriterBackend.

// Current Code
fn write_message<W: WriterBackend>(&self, w: &mut Writer<W>) -> quick_protobuf::Result<()> {
    let bytes: Vec<u8> = self.foo.to_bytes();
    w.write_with_tag(10, |w| w.write_bytes(&bytes))?;
    // ..
    Ok(())
}
// Code I would like to write
fn write_message<W: WriterBackend>(&self, w: &mut Writer<W>) -> quick_protobuf::Result<()> {
    w.write_with_tag(10, |w| {
        let len = self.foo.encoded_len();
        w.write_varint(len as u64)?;
        self.foo.write(w)?;
        Ok(())
    })?;
    // ..
    Ok(())
}