From 44a109f0415dde32f348af8dfe517b1e1200e1eb Mon Sep 17 00:00:00 2001 From: patrickZWY <154947644+patrickZWY@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:04:24 -0800 Subject: [PATCH] feat(io): preserve encoder writer state on finish failure Co-authored-by: Codex --- bases/src/error.rs | 25 +++- bases/src/io.rs | 75 ++++++++--- tests-integration/tests/contracts/io.rs | 70 ++++++++++- tests-integration/tests/io.rs | 159 ++++++++++++++++++++++-- 4 files changed, 301 insertions(+), 28 deletions(-) diff --git a/bases/src/error.rs b/bases/src/error.rs index 6349663..da29995 100644 --- a/bases/src/error.rs +++ b/bases/src/error.rs @@ -14,6 +14,8 @@ use core::error::Error; use core::fmt; +#[cfg(feature = "std")] +use std::io; /// An encoding error. #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -148,15 +150,23 @@ impl Error for DecodeSliceError { } } -/// A finalization error together with the unchanged encoder or decoder. +/// A finalization error together with the stream that failed to finish. /// /// Inspect [`error`](Self::error) for the cause. For buffer-size errors, /// recover the stream with [`into_inner`](Self::into_inner) and retry with /// a larger output buffer. /// +/// For [`Encoder`](crate::Encoder) and [`Decoder`](crate::Decoder), the +/// recovered stream is unchanged. With the `std` feature, +/// `io::EncoderWriter` preserves any progress made +/// before an I/O error so that retrying finalization resumes from the first +/// unwritten byte. It no longer accepts input, and dropping its error does +/// not retry finalization. See the finalization method for the recovered +/// stream's state and permitted operations. +/// /// Converting this error into [`EncodeError`], [`DecodeError`], or /// [`DecodeSliceError`] discards the stream. This lets callers use `?` when -/// recovery is not needed. +/// recovery is not needed. With `std`, the same applies to `std::io::Error`. /// /// # Examples /// @@ -197,7 +207,7 @@ impl FinishError { &self.error } - /// Recovers the unchanged stream, discarding the error. + /// Recovers the stream, discarding the error. #[must_use] pub fn into_inner(self) -> S { self.stream @@ -209,7 +219,7 @@ impl FinishError { self.error } - /// Returns `(error, stream)`, preserving the unchanged stream state. + /// Returns `(error, stream)`, preserving the stream's state at failure. #[must_use] pub fn into_parts(self) -> (E, S) { (self.error, self.stream) @@ -256,6 +266,13 @@ impl From> for DecodeSliceError { } } +#[cfg(feature = "std")] +impl From> for io::Error { + fn from(error: FinishError) -> Self { + error.into_error() + } +} + #[cfg(test)] mod tests { use core::error::Error; diff --git a/bases/src/io.rs b/bases/src/io.rs index 9332b89..2c5708b 100644 --- a/bases/src/io.rs +++ b/bases/src/io.rs @@ -23,6 +23,7 @@ use crate::Codec; use crate::DecodeSliceError; use crate::Decoder; use crate::Encoder; +use crate::FinishError; use crate::codec::sealed::Profile; const BUF_LEN: usize = 1024; @@ -33,6 +34,8 @@ const MAX_DECODED_QUANTUM: usize = 5; /// Call [`finish`](Self::finish) to emit any buffered incomplete quantum and /// padding while surfacing I/O errors. Dropping the writer without calling /// `finish` performs a best-effort finalization and ignores errors. +/// Once `finish` has been called, recovered adapters reject nonempty writes +/// with [`io::ErrorKind::BrokenPipe`] and must be explicitly finished again. /// /// # Examples /// @@ -53,7 +56,7 @@ pub struct EncoderWriter { output: [u8; BUF_LEN], output_pos: usize, output_len: usize, - finished: bool, + finishing: bool, panicked: bool, } @@ -62,7 +65,7 @@ impl fmt::Debug for EncoderWriter { formatter .debug_struct("EncoderWriter") .field("writer", &self.writer) - .field("finished", &self.finished) + .field("finishing", &self.finishing) .finish_non_exhaustive() } } @@ -77,7 +80,7 @@ impl EncoderWriter { output: [0; BUF_LEN], output_pos: 0, output_len: 0, - finished: false, + finishing: false, panicked: false, } } @@ -107,7 +110,7 @@ impl EncoderWriter { /// padding. #[must_use] pub fn into_inner(mut self) -> W { - self.finished = true; + self.finishing = true; self.writer .take() .expect("encoder writer is present before consumption") @@ -116,13 +119,53 @@ impl EncoderWriter { /// Encodes any remaining buffered input, writes all buffered output, and /// returns the underlying writer. /// + /// On error, [`FinishError::into_inner`] recovers the adapter with its + /// remaining output and write position intact. Retry `finish` to resume + /// writing without duplicating bytes already accepted by the underlying + /// writer. Once finalization starts, nonempty writes fail with + /// [`io::ErrorKind::BrokenPipe`], even if no output was written by `finish`. + /// Dropping the error or recovered adapter does not retry finalization. + /// The underlying writer is still dropped normally. + /// The adapter is stored directly in the error without an extra allocation. + /// + /// This does not call [`flush`](Write::flush) on the underlying writer. + /// /// # Errors /// - /// Returns any I/O error emitted by the underlying writer. - pub fn finish(mut self) -> io::Result { - let result = self.finish_inner(); - self.finished = true; - result?; + /// Returns [`FinishError`] carrying an I/O error from the underlying + /// writer, or [`io::ErrorKind::WriteZero`] if it cannot make progress. + /// + /// # Examples + /// + /// Recover from a destination that has no capacity, then retry with space + /// for the final quantum: + /// + /// ``` + /// use std::io; + /// use std::io::Write; + /// + /// use bases::Base64; + /// + /// let mut output = [0_u8; 4]; + /// let mut empty = []; + /// let mut encoder = Base64::encoder_writer(&mut empty[..]); + /// encoder.write_all(b"f")?; + /// let failure = encoder.finish().unwrap_err(); + /// assert_eq!(failure.error().kind(), io::ErrorKind::WriteZero); + /// + /// let mut encoder = failure.into_inner(); + /// *encoder.get_mut() = &mut output[..]; + /// encoder.finish()?; + /// assert_eq!(&output, b"Zg=="); + /// # Ok::<(), io::Error>(()) + /// ``` + // Preserve the inline adapter for recovery without allocating on failure. + #[allow(clippy::result_large_err)] + pub fn finish(mut self) -> Result> { + self.finishing = true; + if let Err(error) = self.finish_inner() { + return Err(FinishError::new(self, error)); + } Ok(self .writer .take() @@ -130,10 +173,6 @@ impl EncoderWriter { } fn finish_inner(&mut self) -> io::Result<()> { - if self.finished { - return Ok(()); - } - self.flush_encoded()?; if self.encoder.finish_output_len() > 0 { let encoded_len = self @@ -148,7 +187,6 @@ impl EncoderWriter { self.flush_encoded()?; } - self.finished = true; Ok(()) } @@ -192,6 +230,13 @@ impl Write for EncoderWriter { return Ok(0); } + if self.finishing { + return Err(io::Error::new( + io::ErrorKind::BrokenPipe, + "cannot write input after finalization has started", + )); + } + self.flush_encoded()?; let saved_encoder = self.encoder.clone(); @@ -256,7 +301,7 @@ impl Write for EncoderWriter { impl Drop for EncoderWriter { fn drop(&mut self) { - if !self.finished && !self.panicked { + if !self.finishing && !self.panicked { let _ = self.finish_inner(); } } diff --git a/tests-integration/tests/contracts/io.rs b/tests-integration/tests/contracts/io.rs index 2c5850f..5ae06d3 100644 --- a/tests-integration/tests/contracts/io.rs +++ b/tests-integration/tests/contracts/io.rs @@ -28,6 +28,9 @@ struct ChunkedWriter { max_write: usize, interrupt_every: usize, calls: usize, + failure_at: usize, + failures_left: usize, + failure_kind: io::ErrorKind, } impl ChunkedWriter { @@ -37,6 +40,9 @@ impl ChunkedWriter { max_write, interrupt_every, calls: 0, + failure_at: usize::MAX, + failures_left: 0, + failure_kind: io::ErrorKind::WouldBlock, } } } @@ -47,7 +53,18 @@ impl Write for ChunkedWriter { if self.interrupt_every > 0 && self.calls.is_multiple_of(self.interrupt_every) { return Err(io::Error::new(io::ErrorKind::Interrupted, "interrupted")); } - let take = buf.len().min(self.max_write); + let mut take = buf.len().min(self.max_write); + if self.failures_left > 0 { + if self.inner.len() == self.failure_at { + self.failures_left -= 1; + return if self.failure_kind == io::ErrorKind::WriteZero { + Ok(0) + } else { + Err(io::Error::from(self.failure_kind)) + }; + } + take = take.min(self.failure_at - self.inner.len()); + } self.inner.extend_from_slice(&buf[..take]); Ok(take) } @@ -133,6 +150,57 @@ pub fn check(reference: &Encoding) { check::(payload, write_chunk, read_chunk, reference); } } + + check_finish_recovery::(reference); +} + +fn check_finish_recovery(reference: &Encoding) { + let payloads: [&[u8]; 7] = [b"", b"f", b"fo", b"foo", b"foob", b"fooba", b"foobar"]; + for input in payloads { + let expected = reference.encode(input); + for max_write in [1, usize::MAX] { + let initial_len = C::encoder() + .update_output_len(input.len()) + .unwrap() + .min(max_write); + for fail_at in initial_len..expected.len() { + for kind in [io::ErrorKind::WouldBlock, io::ErrorKind::WriteZero] { + let mut writer = EncoderWriter::::new(ChunkedWriter::new(max_write, 3)); + writer.write_all(input).unwrap(); + assert_eq!(writer.get_ref().inner, expected.as_bytes()[..initial_len]); + let inner = writer.get_mut(); + inner.failure_at = fail_at; + inner.failures_left = 2; + inner.failure_kind = kind; + + let Err(failure) = writer.finish() else { + panic!("scripted finalization must fail"); + }; + assert_eq!(failure.error().kind(), kind); + let mut writer = failure.into_inner(); + assert_eq!(writer.get_ref().inner, expected.as_bytes()[..fail_at]); + assert_eq!(writer.write(&[]).unwrap(), 0); + assert_eq!( + writer.write(b"extra").unwrap_err().kind(), + io::ErrorKind::BrokenPipe, + ); + + let Err(failure) = writer.finish() else { + panic!("scripted retry must fail"); + }; + let (error, writer) = failure.into_parts(); + assert_eq!(error.kind(), kind); + assert_eq!(writer.get_ref().inner, expected.as_bytes()[..fail_at]); + assert_eq!( + writer.finish().unwrap().inner, + expected.as_bytes(), + "profile {}", + C::name() + ); + } + } + } + } } #[test] diff --git a/tests-integration/tests/io.rs b/tests-integration/tests/io.rs index 981c362..55e675e 100644 --- a/tests-integration/tests/io.rs +++ b/tests-integration/tests/io.rs @@ -12,9 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::cell::Cell; +use std::error::Error; use std::io; use std::io::Read; use std::io::Write; +use std::panic; +use std::ptr; +use std::rc::Rc; use bases::Base32; use bases::Base64; @@ -62,6 +67,17 @@ fn decoder_reader_repeats_the_finalization_error_at_eof() { struct ScriptedWriter { writes: std::vec::IntoIter>, bytes: Vec, + flushes: usize, +} + +impl ScriptedWriter { + fn new(writes: Vec>) -> Self { + Self { + writes: writes.into_iter(), + bytes: Vec::new(), + flushes: 0, + } + } } impl Write for ScriptedWriter { @@ -72,6 +88,7 @@ impl Write for ScriptedWriter { } fn flush(&mut self) -> io::Result<()> { + self.flushes += 1; Ok(()) } } @@ -79,10 +96,7 @@ impl Write for ScriptedWriter { #[test] fn writer_retries_a_failed_quantum_without_consuming_pending_input() { for failure in [Ok(0), Err(io::Error::from(io::ErrorKind::WouldBlock))] { - let inner = ScriptedWriter { - writes: vec![failure].into_iter(), - bytes: Vec::new(), - }; + let inner = ScriptedWriter::new(vec![failure]); let mut writer = Base64::encoder_writer(inner); assert_eq!(writer.write(b"f").unwrap(), 1); match writer.write(b"oo") { @@ -96,10 +110,7 @@ fn writer_retries_a_failed_quantum_without_consuming_pending_input() { #[test] fn writer_retries_buffered_output_without_duplicating_accepted_input() { - let inner = ScriptedWriter { - writes: vec![Ok(2), Err(io::Error::from(io::ErrorKind::WouldBlock))].into_iter(), - bytes: Vec::new(), - }; + let inner = ScriptedWriter::new(vec![Ok(2), Err(io::Error::from(io::ErrorKind::WouldBlock))]); let mut writer = Base64::encoder_writer(inner); assert_eq!(writer.write(b"foo").unwrap(), 3); assert_eq!( @@ -109,3 +120,135 @@ fn writer_retries_buffered_output_without_duplicating_accepted_input() { assert_eq!(writer.write(b"bar").unwrap(), 3); assert_eq!(writer.finish().unwrap().bytes, b"Zm9vYmFy"); } + +#[test] +fn discarding_finish_recovery_state_does_not_retry_writes() { + for action in [ + "drop error", + "drop adapter", + "into_inner", + "into_error", + "convert", + ] { + let mut inner = + ScriptedWriter::new(vec![Ok(1), Err(io::Error::from(io::ErrorKind::WouldBlock))]); + let mut writer = Base64::encoder_writer(&mut inner); + writer.write_all(b"f").unwrap(); + let Err(failure) = writer.finish() else { + panic!("scripted finalization must fail"); + }; + assert!(ptr::eq( + failure + .source() + .unwrap() + .downcast_ref::() + .unwrap(), + failure.error(), + )); + match action { + "drop error" => drop(failure), + "drop adapter" => drop(failure.into_inner()), + "into_inner" => { + let inner = failure.into_inner().into_inner(); + assert_eq!(inner.bytes, b"Z"); + } + "into_error" => assert_eq!(failure.into_error().kind(), io::ErrorKind::WouldBlock), + "convert" => { + let error = io::Error::from(failure); + assert_eq!(error.kind(), io::ErrorKind::WouldBlock); + } + _ => unreachable!(), + } + // The next write would succeed, so an implicit retry would append bytes. + assert_eq!(inner.bytes, b"Z", "action {action}"); + assert_eq!(inner.flushes, 0); + } +} + +#[test] +fn finish_errors_propagate_as_io_errors_with_borrowed_writers() { + fn finish(writer: EncoderWriter) -> io::Result<()> { + writer.finish()?; + Ok(()) + } + + let mut inner = ScriptedWriter::new(vec![ + Ok(1), + Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "sink refused output", + )), + ]); + let mut writer = Base64::encoder_writer(&mut inner); + writer.write_all(b"f").unwrap(); + let error = finish(writer).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert_eq!(error.to_string(), "sink refused output"); + assert_eq!(inner.bytes, b"Z"); +} + +#[test] +fn recovery_supports_non_send_writers_and_flush_does_not_reopen_input() { + struct LocalWriter<'a> { + inner: &'a mut ScriptedWriter, + flushes: Rc>, + } + + impl Write for LocalWriter<'_> { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.inner.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.flushes.set(self.flushes.get() + 1); + self.inner.flush() + } + } + + let flushes = Rc::new(Cell::new(0)); + let mut inner = + ScriptedWriter::new(vec![Ok(1), Err(io::Error::from(io::ErrorKind::WouldBlock))]); + let mut writer = Base64::encoder_writer(LocalWriter { + inner: &mut inner, + flushes: Rc::clone(&flushes), + }); + writer.write_all(b"f").unwrap(); + let Err(failure) = writer.finish() else { + panic!("scripted finalization must fail"); + }; + let mut writer = failure.into_inner(); + writer.flush().unwrap(); + assert_eq!(flushes.get(), 1); + assert_eq!( + writer.write(b"oo").unwrap_err().kind(), + io::ErrorKind::BrokenPipe + ); + let inner = writer.finish().unwrap(); + assert_eq!(inner.inner.bytes, b"Zg=="); + assert_eq!(flushes.get(), 1); +} + +#[test] +fn finish_does_not_retry_after_the_underlying_writer_panics() { + struct PanickingWriter<'a>(&'a Cell); + + impl Write for PanickingWriter<'_> { + fn write(&mut self, _: &[u8]) -> io::Result { + self.0.set(self.0.get() + 1); + panic!("writer panicked"); + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + + let calls = Cell::new(0); + let result = panic::catch_unwind(panic::AssertUnwindSafe(|| { + let mut writer = Base64::encoder_writer(PanickingWriter(&calls)); + writer.write_all(b"f").unwrap(); + let _ = writer.finish(); + })); + assert!(result.is_err()); + assert_eq!(calls.get(), 1); +}