willow_encoding/
error.rs

1use core::{fmt::Display, fmt::Formatter, num::TryFromIntError};
2use either::Either;
3use std::error::Error;
4use ufotofu::common::errors::OverwriteFullSliceError;
5
6/// Everything that can go wrong when decoding a value.
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum DecodeError<ProducerError> {
9    /// The producer of the bytes to be decoded errored somehow.
10    Producer(ProducerError),
11    /// The bytes produced by the producer cannot be decoded into anything meaningful.
12    InvalidInput,
13    /// Tried to use a u64 as a usize when the current compilation target's usize is not big enough.
14    U64DoesNotFitUsize,
15}
16
17impl<F, E> From<OverwriteFullSliceError<F, E>> for DecodeError<E> {
18    fn from(value: OverwriteFullSliceError<F, E>) -> Self {
19        match value.reason {
20            Either::Left(_) => DecodeError::InvalidInput,
21            Either::Right(err) => DecodeError::Producer(err),
22        }
23    }
24}
25
26impl<ProducerError> From<TryFromIntError> for DecodeError<ProducerError> {
27    fn from(_: TryFromIntError) -> Self {
28        DecodeError::U64DoesNotFitUsize
29    }
30}
31
32impl<E> Error for DecodeError<E>
33where
34    E: 'static + Error,
35{
36    fn source(&self) -> Option<&(dyn Error + 'static)> {
37        match self {
38            DecodeError::Producer(err) => Some(err),
39            DecodeError::InvalidInput => None,
40            DecodeError::U64DoesNotFitUsize => None,
41        }
42    }
43}
44
45impl<E> Display for DecodeError<E> {
46    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
47        match self {
48            DecodeError::Producer(_) => {
49                write!(f, "The underlying producer encountered an error",)
50            }
51            DecodeError::InvalidInput => {
52                write!(f, "Decoding failed due to receiving invalid input",)
53            }
54            DecodeError::U64DoesNotFitUsize => {
55                write!(f, "Tried (and failed) to decode a u64 to a 32-bit usize",)
56            }
57        }
58    }
59}