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
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
use std::error;
use std::fmt;
use std::str::FromStr;
use serde::de::{self,Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// Error type related to the Currency
#[derive(Debug, Clone, PartialEq)]
pub enum CurrencyError {
    InvalidLength,
    InvalidCharacter,
    DeserializationFailed
}

impl fmt::Display for CurrencyError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            CurrencyError::InvalidLength => write!(f, "currency codes must consist of exactly three characters"),
            CurrencyError::InvalidCharacter => write!(f, "currency codes must contain only alphabetic ASCII characters"),
            CurrencyError::DeserializationFailed => write!(f, "currency deserialization failed"),
        }
        
    }
}

/// This is important for other errors to wrap this one.
impl error::Error for CurrencyError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        None
    }
}

impl de::Error for CurrencyError {
    fn custom<T: fmt::Display>(_: T) -> Self {
        CurrencyError::DeserializationFailed
    }
}


/// Special type for currencies
#[derive(Debug, Clone, PartialEq, Copy)]
pub struct Currency {
    iso_code: [char;3],
}

impl fmt::Display for Currency {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}{}{}", self.iso_code[0],self.iso_code[1],self.iso_code[2])
    }
}

/// Transform a string into a Currency
impl FromStr for Currency {
    type Err = CurrencyError;
    fn from_str(curr: &str) -> Result<Currency, CurrencyError> {
        let mut currency =  [' ',' ',' '];
        let mut idx = 0;
        for c in curr.chars() {
            if idx >=3 {
                return Err(CurrencyError::InvalidLength);
            }
            let c = c.to_ascii_uppercase();
            if c.is_ascii_alphabetic() {
                currency[idx] = c.to_ascii_uppercase();
                idx += 1;
            } else {
                return Err(CurrencyError::InvalidCharacter);
            }
        }
        if idx !=3 {
            return Err(CurrencyError::InvalidLength)
        } else {
            Ok(Currency{iso_code: currency })
        }
    }
}


impl Serialize for Currency {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&format!("{}",&self))
    }
}

struct CurrencyVisitor;

impl<'de> Visitor<'de> for CurrencyVisitor {
    type Value = Currency;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a currency code must consist of three alphabetic characters")
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
       match Currency::from_str(value) {
           Ok(val) => Ok(val),
           Err(err) => Err(E::custom(format!("{}", err)))
       }
    
    }
}

impl<'de> Deserialize<'de> for Currency 
{

    fn deserialize<D>(deserializer: D) -> Result<Currency, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_str(CurrencyVisitor)
    }
}



#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn read_write_currency() {
        // valid iso code
        let currency = Currency::from_str("EUR").unwrap();
        assert_eq!(format!("{}",currency), "EUR".to_string());

        // case ignorance
        let currency = Currency::from_str("euR").unwrap();
        assert_eq!(format!("{}",currency), "EUR".to_string());

        // to long
        let currency = Currency::from_str("EURO");
        assert_eq!(currency, Err(CurrencyError::InvalidLength));

        // to short
        let currency = Currency::from_str("EU");
        assert_eq!(currency, Err(CurrencyError::InvalidLength));

        // invalid character1
        let currency = Currency::from_str("éUR");
        assert_eq!(currency, Err(CurrencyError::InvalidCharacter));

        // invalid character2
        let currency = Currency::from_str("EU1");
        assert_eq!(currency, Err(CurrencyError::InvalidCharacter));
    }

    #[test]
    fn deserialize_currency() {
        let input = r#""EUR""#;

        let curr: Currency = serde_json::from_str(input).unwrap();
        assert_eq!(format!("{}",curr), "EUR");
    }
    #[test]
    fn serialize_currency() {
        let curr = Currency{ iso_code: ['E', 'U', 'R'] };
        let json = serde_json::to_string(&curr).unwrap();
        assert_eq!(json, r#""EUR""#);
    }
}