Skip to main content

payjp_types/
currency.rs

1#![allow(missing_docs)]
2use serde::Serialize;
3
4#[derive(Copy, Clone, Debug, Eq, Serialize, PartialEq, Hash, Default, miniserde::Deserialize)]
5#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
6pub enum Currency {
7    #[serde(rename = "jpy")]
8    JPY, // Japanese Yen
9    #[serde(rename = "usd")]
10    #[default]
11    USD, // United States Dollar
12}
13
14impl std::fmt::Display for Currency {
15    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16        write!(f, "{}", format!("{:?}", self).to_ascii_lowercase())
17    }
18}
19
20impl std::str::FromStr for Currency {
21    type Err = ParseCurrencyError;
22    fn from_str(s: &str) -> Result<Self, Self::Err> {
23        match s {
24            "jpy" => Ok(Currency::JPY),
25            "usd" => Ok(Currency::USD),
26            _ => Err(ParseCurrencyError(())),
27        }
28    }
29}
30
31#[derive(Debug)]
32pub struct ParseCurrencyError(/* private */ ());
33
34impl std::fmt::Display for ParseCurrencyError {
35    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        #[allow(deprecated)]
37        fmt.write_str(::std::error::Error::description(self))
38    }
39}
40
41impl std::error::Error for ParseCurrencyError {
42    fn description(&self) -> &str {
43        "unknown currency code"
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50    #[test]
51    fn debug_currency() {
52        assert_eq!(format!("{:?}", Currency::USD), "USD");
53    }
54
55    #[test]
56    fn display_currency() {
57        assert_eq!(format!("{}", Currency::USD), "usd");
58    }
59
60    #[test]
61    fn serialize_currency() {
62        assert_eq!(serde_json::to_string(&Currency::USD).unwrap(), "\"usd\"");
63    }
64
65    #[test]
66    fn deserialize_currency() {
67        assert_eq!(miniserde::json::from_str::<Currency>("\"usd\"").unwrap(), Currency::USD);
68    }
69}