currency.rs (5684B)
1 use core::{fmt, str::FromStr}; 2 3 /// Immutable supported code/exponent data contract. No runtime update is implied. 4 pub const CURRENCY_REGISTRY_ID: &str = "radroots.currency_registry.v1"; 5 /// SHA256 of the complete attributed source data used by this registry. 6 pub const CURRENCY_REGISTRY_SHA256: &str = 7 "60d8282b2d7ddc27929b097d4de9e76a900a64f1de4a5aa7a4cb3308b55b82d0"; 8 9 const DATA: &str = include_str!("../data/currency_registry_v1.csv"); 10 11 /// Number of supported currencies/funds in the fixed registry. 12 pub const SUPPORTED_CURRENCY_COUNT: usize = { 13 let bytes = DATA.as_bytes(); 14 let mut position = 0; 15 let mut count = 0; 16 let mut previous = [0_u8; 3]; 17 while position < bytes.len() { 18 if bytes[position] == b'#' { 19 while position < bytes.len() && bytes[position] != b'\n' { 20 position += 1; 21 } 22 assert!(position < bytes.len(), "unterminated registry attribution"); 23 position += 1; 24 continue; 25 } 26 assert!(position + 6 <= bytes.len(), "truncated currency row"); 27 let code = [bytes[position], bytes[position + 1], bytes[position + 2]]; 28 assert!( 29 code[0].is_ascii_uppercase() 30 && code[1].is_ascii_uppercase() 31 && code[2].is_ascii_uppercase(), 32 "noncanonical registry code" 33 ); 34 assert!( 35 bytes[position + 3] == b',' 36 && bytes[position + 4] >= b'0' 37 && bytes[position + 4] <= b'4' 38 && bytes[position + 5] == b'\n', 39 "invalid registry exponent or row" 40 ); 41 assert!( 42 count == 0 43 || code[0] > previous[0] 44 || (code[0] == previous[0] && code[1] > previous[1]) 45 || (code[0] == previous[0] && code[1] == previous[1] && code[2] > previous[2]), 46 "unsorted or duplicate registry code" 47 ); 48 previous = code; 49 count += 1; 50 position += 6; 51 } 52 assert!(count == 165, "registry v1 membership changed"); 53 count 54 }; 55 56 /// A validated supported currency/fund and its exact minor-unit exponent. 57 /// 58 /// This represents the fixed registry, without exchange, cash/display rounding, 59 /// payment or present-day legal-tender claims. 60 #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] 61 pub struct Currency { 62 code: &'static str, 63 exponent: u8, 64 } 65 66 /// Input-free currency admission failure; no fallback exponent is inferred. 67 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 68 #[non_exhaustive] 69 pub enum CurrencyError { 70 /// The code is not exactly three uppercase ASCII letters. 71 InvalidFormat, 72 /// The code has no supported numeric exponent in this fixed registry. 73 UnsupportedCode, 74 } 75 76 impl Currency { 77 /// Admits exactly a supported uppercase ASCII code without allocation. 78 pub fn from_code(code: &str) -> Result<Self, CurrencyError> { 79 if code.len() != 3 || !code.bytes().all(|byte| byte.is_ascii_uppercase()) { 80 return Err(CurrencyError::InvalidFormat); 81 } 82 Self::supported() 83 .find(|currency| currency.code == code) 84 .ok_or(CurrencyError::UnsupportedCode) 85 } 86 87 /// Iterates the fixed supported registry in canonical code order. 88 pub fn supported() -> impl Iterator<Item = Self> + Clone { 89 DATA.lines() 90 .filter(|line| !line.starts_with('#')) 91 .map(|line| { 92 // The compile-time data check proves every non-comment row is 93 // six ASCII bytes, including its newline, with an exponent 0-4. 94 Self { 95 code: &line[..3], 96 exponent: line.as_bytes()[4] - b'0', 97 } 98 }) 99 } 100 101 /// Returns the canonical supported three-letter code. 102 pub const fn code(self) -> &'static str { 103 self.code 104 } 105 106 /// Returns the fixed exponent; this is not a presentation-rounding rule. 107 pub const fn exponent(self) -> u8 { 108 self.exponent 109 } 110 } 111 112 impl FromStr for Currency { 113 type Err = CurrencyError; 114 fn from_str(value: &str) -> Result<Self, Self::Err> { 115 Self::from_code(value) 116 } 117 } 118 119 impl fmt::Debug for Currency { 120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 121 f.write_str("Currency(<validated>)") 122 } 123 } 124 125 impl fmt::Display for CurrencyError { 126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 127 f.write_str(match self { 128 Self::InvalidFormat => "invalid currency code format", 129 Self::UnsupportedCode => "unsupported currency code", 130 }) 131 } 132 } 133 134 impl core::error::Error for CurrencyError {} 135 136 #[cfg(feature = "serde")] 137 mod serde_impl { 138 use super::Currency; 139 use core::fmt; 140 use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; 141 142 impl Serialize for Currency { 143 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { 144 serializer.serialize_str(self.code()) 145 } 146 } 147 148 impl<'de> Deserialize<'de> for Currency { 149 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { 150 struct Visitor; 151 impl de::Visitor<'_> for Visitor { 152 type Value = Currency; 153 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 154 f.write_str("a supported uppercase currency code") 155 } 156 fn visit_str<E: de::Error>(self, value: &str) -> Result<Currency, E> { 157 Currency::from_code(value).map_err(E::custom) 158 } 159 } 160 deserializer.deserialize_str(Visitor) 161 } 162 } 163 }