Skip to content

Commit ce28ee6

Browse files
committed
feat: add auto_finish to FrameEncoder
Fixes #94
1 parent 006db07 commit ce28ee6

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

src/frame/compress.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,17 @@ impl<W: io::Write> FrameEncoder<W> {
111111
);
112112
}
113113

114+
/// Returns a wrapper around `self` that will finish the stream on drop.
115+
///
116+
/// # Panic
117+
///
118+
/// Panics on drop if an error happens when finishing the stream.
119+
pub fn auto_finish(self) -> AutoFinishEncoder<W> {
120+
AutoFinishEncoder {
121+
encoder: Some(self),
122+
}
123+
}
124+
114125
/// Creates a new Encoder with the specified FrameInfo.
115126
pub fn with_frame_info(frame_info: FrameInfo, wtr: W) -> Self {
116127
FrameEncoder {
@@ -376,6 +387,37 @@ impl<W: io::Write> io::Write for FrameEncoder<W> {
376387
}
377388
}
378389

390+
/// A wrapper around an `FrameEncoder<W>` that finishes the stream on drop.
391+
///
392+
/// This can be created by the [`auto_finish()`] method on the [`FrameEncoder`].
393+
///
394+
/// [`auto_finish()`]: Encoder::auto_finish
395+
/// [`Encoder`]: Encoder
396+
pub struct AutoFinishEncoder<W: Write> {
397+
// We wrap this in an option to take it during drop.
398+
encoder: Option<FrameEncoder<W>>,
399+
}
400+
401+
impl<W: io::Write> Drop for AutoFinishEncoder<W> {
402+
fn drop(&mut self) {
403+
if let Some(mut encoder) = self.encoder.take() {
404+
if let Err(err) = encoder.try_finish() {
405+
panic!("Error when flushing frame on drop {:?} ", err);
406+
}
407+
}
408+
}
409+
}
410+
411+
impl<W: Write> Write for AutoFinishEncoder<W> {
412+
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
413+
self.encoder.as_mut().unwrap().write(buf)
414+
}
415+
416+
fn flush(&mut self) -> io::Result<()> {
417+
self.encoder.as_mut().unwrap().flush()
418+
}
419+
}
420+
379421
impl<W: fmt::Debug + io::Write> fmt::Debug for FrameEncoder<W> {
380422
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
381423
f.debug_struct("FrameEncoder")

0 commit comments

Comments
 (0)