yasna/reader/
error.rs

1// Copyright 2016 Masaki Hara
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9#[cfg(feature = "std")]
10use std::{error::Error, io};
11use core::fmt::{self, Display};
12
13#[derive(Debug, Clone, Copy, Eq, PartialEq)]
14pub struct ASN1Error {
15    kind: ASN1ErrorKind,
16}
17#[derive(Debug, Clone, Copy, Eq, PartialEq)]
18pub enum ASN1ErrorKind {
19    Eof, Extra, IntegerOverflow, StackOverflow, Invalid,
20}
21
22pub type ASN1Result<T> = Result<T, ASN1Error>;
23
24impl ASN1Error {
25    pub fn new(kind: ASN1ErrorKind) -> Self {
26        ASN1Error {
27            kind,
28        }
29    }
30
31    pub fn kind(&self) -> ASN1ErrorKind {
32        self.kind
33    }
34}
35
36impl Display for ASN1Error {
37    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
38        write!(f, "{:?}", self)?;
39        return Ok(());
40    }
41}
42
43#[cfg(feature = "std")]
44impl Error for ASN1Error {
45    fn description(&self) -> &str {
46        match self.kind {
47            ASN1ErrorKind::Eof => "End of file",
48            ASN1ErrorKind::Extra => "Extra data in file",
49            ASN1ErrorKind::IntegerOverflow => "Integer overflow",
50            ASN1ErrorKind::StackOverflow => "Stack overflow",
51            ASN1ErrorKind::Invalid => "Invalid data",
52        }
53    }
54}
55
56#[cfg(feature = "std")]
57impl From<ASN1Error> for io::Error {
58    fn from(e: ASN1Error) -> Self {
59        return io::Error::new(io::ErrorKind::InvalidData, e);
60    }
61}