Skip to main content

azalea_codec/
error.rs

1use std::{
2    backtrace::{Backtrace, BacktraceStatus},
3    borrow::Cow,
4    convert::Infallible,
5    fmt::Debug,
6    io,
7};
8
9use thiserror::Error;
10
11use crate::number::Number;
12
13pub type ReadResult<T> = std::result::Result<T, ReadError>;
14pub type WriteResult<T> = std::result::Result<T, WriteError>;
15
16#[derive(Debug, Clone)]
17pub enum ReadErrorKind {
18    Unimplemented,
19    UnknownKey(Box<str>),
20    MissingKey(&'static str),
21    NoVariantsMatched(Box<[(&'static str, ReadError)]>),
22    WhileReadingKey(Cow<'static, str>, Box<ReadErrorKind>),
23    NumberTooBig(Number),
24    Custom(Box<str>),
25}
26
27#[derive(Error)]
28#[error("{kind:?}")]
29pub struct ReadError {
30    pub kind: ReadErrorKind,
31    pub backtrace: Backtrace,
32}
33impl ReadError {
34    pub fn unimplemented() -> Self {
35        ReadErrorKind::Unimplemented.into()
36    }
37    pub fn unknown_key(name: impl Into<Box<str>>) -> Self {
38        ReadErrorKind::UnknownKey(name.into()).into()
39    }
40    pub fn missing_key(name: &'static str) -> Self {
41        ReadErrorKind::MissingKey(name).into()
42    }
43    pub fn no_variants_matched(errors: impl Into<Box<[(&'static str, ReadError)]>>) -> Self {
44        ReadErrorKind::NoVariantsMatched(errors.into()).into()
45    }
46    pub fn number_too_big(n: Number) -> Self {
47        ReadErrorKind::NumberTooBig(n).into()
48    }
49    pub fn custom(message: impl Into<Box<str>>) -> Self {
50        ReadErrorKind::Custom(message.into()).into()
51    }
52
53    pub fn while_reading_key(mut self, key: impl Into<Cow<'static, str>>) -> Self {
54        self.kind = ReadErrorKind::WhileReadingKey(key.into(), Box::new(self.kind));
55        self
56    }
57}
58impl ReadErrorKind {
59    fn relevance(&self) -> usize {
60        match self {
61            ReadErrorKind::NoVariantsMatched(items) => items
62                .iter()
63                .map(|i| i.1.kind.relevance() + 1)
64                .max()
65                .unwrap_or_default(),
66            ReadErrorKind::WhileReadingKey(_, e) => e.relevance() + 1,
67            ReadErrorKind::MissingKey(_) => 1,
68            _ => 10,
69        }
70    }
71}
72impl From<ReadErrorKind> for ReadError {
73    fn from(kind: ReadErrorKind) -> Self {
74        Self {
75            kind,
76            backtrace: Backtrace::capture(),
77        }
78    }
79}
80impl From<Infallible> for ReadError {
81    fn from(_: Infallible) -> Self {
82        unreachable!()
83    }
84}
85impl Clone for ReadError {
86    fn clone(&self) -> Self {
87        Self {
88            kind: self.kind.clone(),
89            backtrace: Backtrace::capture(),
90        }
91    }
92}
93
94impl Debug for ReadError {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        let mut pretty = Vec::new();
97        let mut cur_kind = self.kind.clone();
98        loop {
99            cur_kind = match cur_kind {
100                ReadErrorKind::NoVariantsMatched(items) => {
101                    let most_relevant_item = items
102                        .iter()
103                        // rev to make sure we get the first one if there's a tie
104                        .rev()
105                        .max_by_key(|i| i.1.kind.relevance())
106                        .unwrap()
107                        .clone();
108                    pretty.push(most_relevant_item.0.to_owned());
109                    most_relevant_item.1.kind
110                }
111                ReadErrorKind::WhileReadingKey(k, e) => {
112                    pretty.push(k.to_string());
113                    *e
114                }
115                k => {
116                    pretty.push(format!("{k:?}"));
117                    break;
118                }
119            };
120        }
121
122        f.write_str("azalea_codec::error::ReadError: ")?;
123        f.write_str(&pretty.join(" -> "))?;
124        if self.backtrace.status() == BacktraceStatus::Captured {
125            f.write_str(&format!("\n\x1b[90m{}\x1b[m", self.backtrace))?;
126        }
127        Ok(())
128    }
129}
130impl From<ReadError> for io::Error {
131    fn from(error: ReadError) -> Self {
132        io::Error::other(error)
133    }
134}
135
136#[derive(Debug, Clone)]
137pub enum WriteErrorKind {
138    Unimplemented,
139    NumberTooBig(u64),
140    Custom(Box<str>),
141}
142#[derive(Debug, Error)]
143#[error("{kind:?}")]
144pub struct WriteError {
145    pub kind: WriteErrorKind,
146    pub backtrace: Backtrace,
147}
148impl WriteError {
149    pub fn unimplemented() -> Self {
150        WriteErrorKind::Unimplemented.into()
151    }
152    pub fn number_too_big(n: u64) -> Self {
153        WriteErrorKind::NumberTooBig(n).into()
154    }
155    pub fn custom(message: impl Into<Box<str>>) -> Self {
156        WriteErrorKind::Custom(message.into()).into()
157    }
158}
159impl From<WriteErrorKind> for WriteError {
160    fn from(kind: WriteErrorKind) -> Self {
161        Self {
162            kind,
163            backtrace: Backtrace::capture(),
164        }
165    }
166}
167impl From<Infallible> for WriteError {
168    fn from(_: Infallible) -> Self {
169        unreachable!()
170    }
171}
172impl Clone for WriteError {
173    fn clone(&self) -> Self {
174        Self {
175            kind: self.kind.clone(),
176            backtrace: Backtrace::capture(),
177        }
178    }
179}
180impl From<WriteError> for io::Error {
181    fn from(error: WriteError) -> Self {
182        io::Error::other(error)
183    }
184}