asn1_codecs/per/
error.rs

1//! APER Codec Errors
2//!
3use std::fmt::Display;
4
5#[derive(Debug)]
6pub struct Error {
7    /// `ErrorCause` can be used to take actions based on the cause.
8    pub cause: ErrorCause,
9    msg: String,
10    context: Vec<String>,
11}
12
13#[derive(Debug)]
14pub enum ErrorCause {
15    /// Remaining Buffer is too short to decode
16    BufferTooShort,
17
18    /// Alignment Error during decode
19    InvalidAlignment,
20
21    /// Encoding of value is not currently supported
22    EncodeNotSupported,
23
24    /// Decoding of value is not currently supported
25    DecodeNotSupported,
26
27    /// Generic Error during Encode or Decode
28    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 {}