Skip to main content

zencodec_io/
std_source_error.rs

1//! Errors from standard-library byte sources, preserving native I/O causes.
2
3use core::fmt;
4use zencodec::source::SourceError;
5
6/// A source-contract refusal or the original standard-library I/O failure.
7///
8/// The native error retains its kind, OS code and custom payload. Drivers and
9/// [`zencodec::source::ReadAtShim`] preserve this error in their source chain.
10/// A kind does not by itself authorize retry: the source may have consumed input.
11#[derive(Debug)]
12#[non_exhaustive]
13pub enum StdSourceError {
14    /// The requested range violates the source's bounds or buffering contract.
15    Source(SourceError),
16    /// The original filesystem or reader error.
17    Io(std::io::Error),
18    /// Retained input storage could not be reserved before reading.
19    Allocation {
20        /// Total retained payload capacity requested, excluding allocator overhead.
21        requested: usize,
22        /// The allocator's original refusal.
23        source: alloc::collections::TryReserveError,
24    },
25}
26
27impl fmt::Display for StdSourceError {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        match self {
30            Self::Source(error) => error.fmt(f),
31            Self::Io(error) => write!(f, "byte source: {error}"),
32            Self::Allocation { requested, source } => {
33                write!(f, "reserving {requested} retained input bytes: {source}")
34            }
35        }
36    }
37}
38
39impl core::error::Error for StdSourceError {
40    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
41        match self {
42            Self::Source(error) => Some(error),
43            Self::Io(error) => Some(error),
44            Self::Allocation { source, .. } => Some(source),
45        }
46    }
47}
48
49impl From<SourceError> for StdSourceError {
50    fn from(error: SourceError) -> Self {
51        Self::Source(error)
52    }
53}
54
55impl From<std::io::Error> for StdSourceError {
56    fn from(error: std::io::Error) -> Self {
57        Self::Io(error)
58    }
59}