Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions bases/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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
///
Expand Down Expand Up @@ -197,7 +207,7 @@ impl<S, E> FinishError<S, E> {
&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
Expand All @@ -209,7 +219,7 @@ impl<S, E> FinishError<S, E> {
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)
Expand Down Expand Up @@ -256,6 +266,13 @@ impl<S> From<FinishError<S, DecodeSliceError>> for DecodeSliceError {
}
}

#[cfg(feature = "std")]
impl<S> From<FinishError<S, io::Error>> for io::Error {
fn from(error: FinishError<S, io::Error>) -> Self {
error.into_error()
}
}

#[cfg(test)]
mod tests {
use core::error::Error;
Expand Down
75 changes: 60 additions & 15 deletions bases/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
///
Expand All @@ -53,7 +56,7 @@ pub struct EncoderWriter<C: Codec, W: Write> {
output: [u8; BUF_LEN],
output_pos: usize,
output_len: usize,
finished: bool,
finishing: bool,
panicked: bool,
}

Expand All @@ -62,7 +65,7 @@ impl<C: Codec, W: Write + fmt::Debug> fmt::Debug for EncoderWriter<C, W> {
formatter
.debug_struct("EncoderWriter")
.field("writer", &self.writer)
.field("finished", &self.finished)
.field("finishing", &self.finishing)
.finish_non_exhaustive()
}
}
Expand All @@ -77,7 +80,7 @@ impl<C: Codec, W: Write> EncoderWriter<C, W> {
output: [0; BUF_LEN],
output_pos: 0,
output_len: 0,
finished: false,
finishing: false,
panicked: false,
}
}
Expand Down Expand Up @@ -107,7 +110,7 @@ impl<C: Codec, W: Write> EncoderWriter<C, W> {
/// 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")
Expand All @@ -116,24 +119,60 @@ impl<C: Codec, W: Write> EncoderWriter<C, W> {
/// 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<W> {
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<W, FinishError<Self, io::Error>> {
self.finishing = true;
if let Err(error) = self.finish_inner() {
return Err(FinishError::new(self, error));
}
Ok(self
.writer
.take()
.expect("encoder writer is present before consumption"))
}

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
Expand All @@ -148,7 +187,6 @@ impl<C: Codec, W: Write> EncoderWriter<C, W> {
self.flush_encoded()?;
}

self.finished = true;
Ok(())
}

Expand Down Expand Up @@ -192,6 +230,13 @@ impl<C: Codec, W: Write> Write for EncoderWriter<C, W> {
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();
Expand Down Expand Up @@ -256,7 +301,7 @@ impl<C: Codec, W: Write> Write for EncoderWriter<C, W> {

impl<C: Codec, W: Write> Drop for EncoderWriter<C, W> {
fn drop(&mut self) {
if !self.finished && !self.panicked {
if !self.finishing && !self.panicked {
let _ = self.finish_inner();
}
}
Expand Down
70 changes: 69 additions & 1 deletion tests-integration/tests/contracts/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -37,6 +40,9 @@ impl ChunkedWriter {
max_write,
interrupt_every,
calls: 0,
failure_at: usize::MAX,
failures_left: 0,
failure_kind: io::ErrorKind::WouldBlock,
}
}
}
Expand All @@ -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)
}
Expand Down Expand Up @@ -133,6 +150,57 @@ pub fn check<C: Codec>(reference: &Encoding) {
check::<C>(payload, write_chunk, read_chunk, reference);
}
}

check_finish_recovery::<C>(reference);
}

fn check_finish_recovery<C: Codec>(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::<C, _>::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]
Expand Down
Loading
Loading