1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use std::{error, fmt, str::Utf8Error};
#[derive(Debug)]
#[non_exhaustive]
pub enum ReadErrorKind {
UnexpectedEof,
Utf8(Utf8Error),
}
impl fmt::Display for ReadErrorKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnexpectedEof => formatter.write_str("reached end of input"),
Self::Utf8(err) => write!(formatter, "{err}"),
}
}
}
impl ReadErrorKind {
pub(crate) fn with_context(self, context: impl Into<String>) -> ReadError {
ReadError {
kind: self,
context: context.into(),
}
}
}
#[derive(Debug)]
pub struct ReadError {
kind: ReadErrorKind,
context: String,
}
impl fmt::Display for ReadError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "failed reading {}: {}", self.context, self.kind)
}
}
impl error::Error for ReadError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match &self.kind {
ReadErrorKind::Utf8(err) => Some(err),
ReadErrorKind::UnexpectedEof => None,
}
}
}