1use std::fmt::Display;
4
5#[derive(Debug)]
6pub struct Error {
7 pub cause: ErrorCause,
9 msg: String,
10 context: Vec<String>,
11}
12
13#[derive(Debug)]
14pub enum ErrorCause {
15 BufferTooShort,
17
18 InvalidAlignment,
20
21 EncodeNotSupported,
23
24 DecodeNotSupported,
26
27 Generic,
29}
30
31impl Error {
32 pub fn new<T: AsRef<str> + Display>(cause: ErrorCause, msg: T) -> Self {
33 Error {
34 cause,
35 msg: msg.to_string(),
36 context: Vec::new(),
37 }
38 }
39 pub fn push_context(&mut self, context_elem: &str) {
40 self.context.push(context_elem.to_string());
41 }
42}
43impl std::fmt::Display for Error {
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 if self.context.is_empty() {
46 write!(f, "cause: {}, msg: {}", self.cause, self.msg)
47 } else {
48 write!(
49 f,
50 "cause: {}, msg: [{}]:{}",
51 self.cause,
52 self.context.join("."),
53 self.msg
54 )
55 }
56 }
57}
58
59impl std::fmt::Display for ErrorCause {
60 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61 std::fmt::Debug::fmt(self, f)
62 }
63}
64
65impl std::error::Error for Error {}