pem/
errors.rs

1// Copyright 2017 Jonathan Creekmore
2//
3// Licensed under the MIT license <LICENSE.md or
4// http://opensource.org/licenses/MIT>. This file may not be
5// copied, modified, or distributed except according to those terms.
6use core::fmt;
7
8#[cfg(any(feature = "std", test))]
9use std::error::Error;
10
11#[cfg(not(any(feature = "std", test)))]
12use alloc::string::String;
13
14/// The `pem` error type.
15#[derive(Debug, Eq, PartialEq)]
16#[allow(missing_docs)]
17pub enum PemError {
18    MismatchedTags(String, String),
19    MalformedFraming,
20    MissingBeginTag,
21    MissingEndTag,
22    MissingData,
23    InvalidData(::base64::DecodeError),
24    InvalidHeader(String),
25    NotUtf8(::core::str::Utf8Error),
26}
27
28impl fmt::Display for PemError {
29    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
30        match self {
31            PemError::MismatchedTags(b, e) => {
32                write!(f, "mismatching BEGIN (\"{b}\") and END (\"{e}\") tags")
33            }
34            PemError::MalformedFraming => write!(f, "malformedframing"),
35            PemError::MissingBeginTag => write!(f, "missing BEGIN tag"),
36            PemError::MissingEndTag => write!(f, "missing END tag"),
37            PemError::MissingData => write!(f, "missing data"),
38            PemError::InvalidData(e) => write!(f, "invalid data: {e}"),
39            PemError::InvalidHeader(hdr) => write!(f, "invalid header: {hdr}"),
40            PemError::NotUtf8(e) => write!(f, "invalid utf-8 value: {e}"),
41        }
42    }
43}
44
45#[cfg(any(feature = "std", test))]
46impl Error for PemError {
47    fn source(&self) -> Option<&(dyn Error + 'static)> {
48        match self {
49            // Errors originating from other libraries.
50            PemError::InvalidData(e) => Some(e),
51            PemError::NotUtf8(e) => Some(e),
52            // Errors directly originating from `pem-rs`.
53            _ => None,
54        }
55    }
56}
57
58/// The `pem` result type.
59pub type Result<T> = ::core::result::Result<T, PemError>;
60
61#[allow(missing_docs)]
62#[macro_export]
63macro_rules! ensure {
64    ($cond:expr, $err:expr) => {
65        if !$cond {
66            return Err($err);
67        }
68    };
69}