did_tz/
prefix.rs

1use core::fmt;
2use std::str::FromStr;
3
4#[derive(Debug, thiserror::Error)]
5#[error("invalid prefix `{0}`")]
6pub struct InvalidPrefix(String);
7
8#[derive(Debug, thiserror::Error)]
9pub enum PrefixError {
10    #[error(transparent)]
11    Invalid(InvalidPrefix),
12
13    #[error("missing prefix")]
14    Missing,
15}
16
17#[derive(Clone, Copy, Debug)]
18pub enum Prefix {
19    TZ1,
20    TZ2,
21    TZ3,
22    KT1,
23}
24
25impl Prefix {
26    pub fn from_address(address: &str) -> Result<Self, PrefixError> {
27        match address.get(..3) {
28            Some(prefix) => Self::from_str(prefix).map_err(PrefixError::Invalid),
29            None => Err(PrefixError::Missing),
30        }
31    }
32
33    pub fn as_str(&self) -> &'static str {
34        match self {
35            Self::TZ1 => "tz1",
36            Self::TZ2 => "tz2",
37            Self::TZ3 => "tz3",
38            Self::KT1 => "KT1",
39        }
40    }
41}
42
43impl FromStr for Prefix {
44    type Err = InvalidPrefix;
45
46    fn from_str(s: &str) -> Result<Self, Self::Err> {
47        Ok(match s {
48            "tz1" => Prefix::TZ1,
49            "tz2" => Prefix::TZ2,
50            "tz3" => Prefix::TZ3,
51            "KT1" => Prefix::KT1,
52            s => return Err(InvalidPrefix(s.to_owned())),
53        })
54    }
55}
56
57impl fmt::Display for Prefix {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        self.as_str().fmt(f)
60    }
61}