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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
use std::{
    error::Error,
    fmt::{self, Display, Formatter},
};

use base64::DecodeError;

use crate::constants::RATCHET_SIGNIFIER;

/// This type is used to indicate errors that occur interpreting a `Ratchet`
#[derive(Debug)]
pub enum RatchetErr {
    BadLen(usize),
    BadEncoding(String),
    UnknownRelation,
    Decode(DecodeError),
}

/// This type is used to indicate errors that occur when getting a previous version of a `Ratchet`.
#[derive(Debug, PartialEq, Eq)]
pub enum PreviousErr {
    BudgetExceeded,
    EqualRatchets,
    OlderRatchet,
}

impl Display for RatchetErr {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            RatchetErr::BadLen(i) => write!(f, "invalid ratchet length {}", i),
            RatchetErr::BadEncoding(s) => write!(
                f,
                "unsupported ratched encoding: '{}'. only '{}' is supported",
                s, RATCHET_SIGNIFIER
            ),
            RatchetErr::UnknownRelation => write!(f, "cannot relate ratchets"),
            RatchetErr::Decode(e) => write!(f, "{:?}", e),
        }
    }
}

impl Error for RatchetErr {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match *self {
            RatchetErr::Decode(ref e) => Some(e),
            _ => None,
        }
    }
}

impl From<DecodeError> for RatchetErr {
    fn from(err: DecodeError) -> RatchetErr {
        RatchetErr::Decode(err)
    }
}

impl Display for PreviousErr {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match *self {
            PreviousErr::BudgetExceeded => write!(f, "ratchet discrepancy budget exceeded"),
            PreviousErr::EqualRatchets => write!(f, "ratchets are equal"),
            PreviousErr::OlderRatchet => write!(f, "current ratchet is older than given ratchet"),
        }
    }
}