ss58_registry/
address_format.rs1use super::*;
17
18#[derive(Copy, Clone, PartialEq, Eq, Debug)]
20pub struct Ss58AddressFormat {
21 prefix: u16,
22}
23
24impl Ss58AddressFormat {
27 #[inline]
29 pub fn custom(prefix: u16) -> Self {
30 Ss58AddressFormat { prefix }
31 }
32
33 pub const fn prefix(&self) -> u16 {
35 self.prefix
36 }
37
38 pub fn all_names() -> &'static [&'static str] {
40 &ALL_SS58_ADDRESS_FORMAT_NAMES
41 }
42
43 pub fn all() -> &'static [Ss58AddressFormatRegistry] {
45 &ALL_SS58_ADDRESS_FORMATS
46 }
47}
48
49#[cfg(feature = "std")]
51impl std::fmt::Display for Ss58AddressFormat {
52 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
53 if let Ok(lookup) =
54 PREFIX_TO_INDEX.binary_search_by_key(&self.prefix, |(prefix, _)| *prefix)
55 {
56 let (_, idx) = PREFIX_TO_INDEX[lookup];
57 write!(f, "{}", ALL_SS58_ADDRESS_FORMAT_NAMES[idx])
58 } else {
59 write!(f, "{}", self.prefix)
60 }
61 }
62}
63
64pub const fn from_address_format(x: Ss58AddressFormat) -> u16 {
66 x.prefix
67}
68
69impl From<Ss58AddressFormatRegistry> for Ss58AddressFormat {
70 fn from(x: Ss58AddressFormatRegistry) -> Ss58AddressFormat {
71 Ss58AddressFormat { prefix: x as u16 }
72 }
73}
74
75impl From<u8> for Ss58AddressFormat {
76 #[inline]
77 fn from(x: u8) -> Ss58AddressFormat {
78 Ss58AddressFormat::from(u16::from(x))
79 }
80}
81
82impl From<Ss58AddressFormat> for u16 {
83 #[inline]
84 fn from(x: Ss58AddressFormat) -> u16 {
85 from_address_format(x)
86 }
87}
88
89impl From<u16> for Ss58AddressFormat {
90 #[inline]
91 fn from(prefix: u16) -> Ss58AddressFormat {
92 Ss58AddressFormat { prefix }
93 }
94}
95
96impl<'a> TryFrom<&'a str> for Ss58AddressFormat {
97 type Error = ParseError;
98
99 fn try_from(x: &'a str) -> Result<Ss58AddressFormat, Self::Error> {
100 Ss58AddressFormatRegistry::try_from(x).map(|a| a.into())
101 }
102}
103
104impl<'a> TryFrom<&'a str> for Ss58AddressFormatRegistry {
105 type Error = ParseError;
106
107 fn try_from(x: &'a str) -> Result<Ss58AddressFormatRegistry, Self::Error> {
108 ALL_SS58_ADDRESS_FORMAT_NAMES
109 .into_iter()
110 .position(|n| n.eq_ignore_ascii_case(x))
111 .map(|lookup| ALL_SS58_ADDRESS_FORMATS[lookup])
112 .ok_or(ParseError)
113 }
114}
115
116#[cfg(feature = "std")]
117impl From<Ss58AddressFormat> for String {
118 fn from(x: Ss58AddressFormat) -> String {
119 x.to_string()
120 }
121}
122
123#[cfg(feature = "std")]
124impl std::str::FromStr for Ss58AddressFormatRegistry {
125 type Err = ParseError;
126
127 fn from_str(data: &str) -> Result<Self, Self::Err> {
128 TryFrom::try_from(data)
129 }
130}