1#[cfg(not(feature = "std"))]
2use core2::{error::Error as StdError, io};
3#[cfg(feature = "std")]
4use std::{error::Error as StdError, io};
5
6use unsigned_varint::decode;
7
8#[derive(Debug)]
10pub struct Error {
11 kind: Kind,
12}
13
14impl Error {
15 pub(crate) const fn invalid_size(size: u64) -> Self {
16 Self {
17 kind: Kind::InvalidSize(size),
18 }
19 }
20
21 #[cfg(not(feature = "std"))]
22 pub(crate) const fn insufficient_varint_bytes() -> Self {
23 Self {
24 kind: Kind::Varint(decode::Error::Insufficient),
25 }
26 }
27
28 #[cfg(not(feature = "std"))]
29 pub(crate) const fn varint_overflow() -> Self {
30 Self {
31 kind: Kind::Varint(decode::Error::Overflow),
32 }
33 }
34}
35
36impl core::fmt::Display for Error {
37 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
38 self.kind.fmt(f)
39 }
40}
41
42#[derive(Debug)]
43enum Kind {
44 Io(io::Error),
46 InvalidSize(u64),
48 Varint(decode::Error),
50}
51
52#[cfg(feature = "std")]
53pub(crate) fn unsigned_varint_to_multihash_error(err: unsigned_varint::io::ReadError) -> Error {
54 match err {
55 unsigned_varint::io::ReadError::Io(err) => io_to_multihash_error(err),
56 unsigned_varint::io::ReadError::Decode(err) => Error {
57 kind: Kind::Varint(err),
58 },
59 other => io_to_multihash_error(io::Error::new(io::ErrorKind::Other, other)),
60 }
61}
62
63#[cfg(not(feature = "std"))]
64pub(crate) fn unsigned_varint_decode_to_multihash_error(
65 err: unsigned_varint::decode::Error,
66) -> Error {
67 Error {
68 kind: Kind::Varint(err),
69 }
70}
71
72pub(crate) fn io_to_multihash_error(err: io::Error) -> Error {
73 Error {
74 kind: Kind::Io(err),
75 }
76}
77
78impl core::fmt::Display for Kind {
79 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
80 match self {
81 Self::Io(err) => write!(f, "{err}"),
82 Self::InvalidSize(size) => write!(f, "Invalid multihash size {size}."),
83 Self::Varint(err) => write!(f, "{err}"),
84 }
85 }
86}
87
88impl StdError for Error {
89 fn source(&self) -> Option<&(dyn StdError + 'static)> {
90 match &self.kind {
91 Kind::Io(inner) => Some(inner),
92 Kind::InvalidSize(_) => None,
93 Kind::Varint(_) => None, }
95 }
96}