Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add auto_finish to FrameEncoder #95

Merged
merged 1 commit into from Mar 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/frame/compress.rs
Expand Up @@ -111,6 +111,17 @@ impl<W: io::Write> FrameEncoder<W> {
);
}

/// Returns a wrapper around `self` that will finish the stream on drop.
///
/// # Panic
///
/// Panics on drop if an error happens when finishing the stream.
pub fn auto_finish(self) -> AutoFinishEncoder<W> {
AutoFinishEncoder {
encoder: Some(self),
}
}

/// Creates a new Encoder with the specified FrameInfo.
pub fn with_frame_info(frame_info: FrameInfo, wtr: W) -> Self {
FrameEncoder {
Expand Down Expand Up @@ -376,6 +387,37 @@ impl<W: io::Write> io::Write for FrameEncoder<W> {
}
}

/// A wrapper around an `FrameEncoder<W>` that finishes the stream on drop.
///
/// This can be created by the [`auto_finish()`] method on the [`FrameEncoder`].
///
/// [`auto_finish()`]: Encoder::auto_finish
/// [`Encoder`]: Encoder
pub struct AutoFinishEncoder<W: Write> {
// We wrap this in an option to take it during drop.
encoder: Option<FrameEncoder<W>>,
}

impl<W: io::Write> Drop for AutoFinishEncoder<W> {
fn drop(&mut self) {
if let Some(mut encoder) = self.encoder.take() {
if let Err(err) = encoder.try_finish() {
panic!("Error when flushing frame on drop {:?} ", err);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will trigger abort if the thread is already panicking.

Copy link
Owner Author

@PSeitz PSeitz May 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is already covered by a PR here: #100

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, great!

}
}
}
}

impl<W: Write> Write for AutoFinishEncoder<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.encoder.as_mut().unwrap().write(buf)
}

fn flush(&mut self) -> io::Result<()> {
self.encoder.as_mut().unwrap().flush()
}
}

impl<W: fmt::Debug + io::Write> fmt::Debug for FrameEncoder<W> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("FrameEncoder")
Expand Down