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
use crate::types::constraints::{Bounded, Size};
use snafu::*;

use alloc::string::ToString;

#[derive(Snafu, Debug)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
    #[snafu(display("invalid length, expected: {expected}; actual: {length}"))]
    InvalidLength {
        length: usize,
        expected: Bounded<usize>,
    },
    #[snafu(display("wrapped der encoding error: {source}"))]
    Der { source: crate::der::enc::Error },
    #[snafu(display("custom error:\n{}", msg))]
    Custom { msg: alloc::string::String },
}

impl Error {
    pub fn check_length(length: usize, expected: &Size) -> Result<(), Self> {
        expected.contains_or_else(&length, || Self::InvalidLength {
            length,
            expected: (**expected),
        })
    }
}

impl crate::enc::Error for Error {
    fn custom<D: core::fmt::Display>(msg: D) -> Self {
        Self::Custom {
            msg: msg.to_string(),
        }
    }
}