Skip to content

Commit

Permalink
Flush on drop
Browse files Browse the repository at this point in the history
I believe flush must be explicit, and Rust should have a lint to
remind user to call it explicitly.

But while Rust has no such lint, we will flush on drop.

Note that current implementation panics, if flush fails.
  • Loading branch information
stepancheg committed Jun 28, 2018
1 parent 0b17831 commit 0e9cc59
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions protobuf/src/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -855,9 +855,6 @@ impl<'a> CodedOutputStream<'a> {
}

/// `CodedOutputStream` which writes directly to `Vec<u8>`.
///
/// Caller should call `flush` at the end to guarantee vec contains
/// all written data.
pub fn vec(vec: &'a mut Vec<u8>) -> CodedOutputStream<'a> {
CodedOutputStream {
target: OutputTarget::Vec(vec),
Expand Down Expand Up @@ -899,6 +896,11 @@ impl<'a> CodedOutputStream<'a> {
Ok(())
}

/// Flush to buffer to the underlying buffer.
/// Note that `CodedOutputStream` does `flush` in the descructor,
/// however, if `flush` in desctructor fails, then destructor panics
/// and program terminates. So it's advisable to explicitly call flush
/// before destructor.
pub fn flush(&mut self) -> ProtobufResult<()> {
match self.target {
OutputTarget::Bytes => Ok(()),
Expand Down Expand Up @@ -1229,6 +1231,13 @@ impl<'a> Write for CodedOutputStream<'a> {
}
}

impl<'a> Drop for CodedOutputStream<'a> {
fn drop(&mut self) {
// This may panic
CodedOutputStream::flush(self).expect("failed to flush");
}
}


#[cfg(test)]
mod test {
Expand Down

0 comments on commit 0e9cc59

Please sign in to comment.