#![forbid(unsafe_code)]
#![doc = include_str!("../README.md")]
use core::{fmt, str::FromStr};
use std::error::Error;
pub const USD: &str = "USD";
pub const EUR: &str = "EUR";
pub const GBP: &str = "GBP";
pub const CAD: &str = "CAD";
pub const AUD: &str = "AUD";
pub const JPY: &str = "JPY";
pub mod prelude {
pub use crate::{AUD, CAD, CurrencyCode, CurrencyCodeError, EUR, GBP, JPY, USD};
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct CurrencyCode(String);
impl CurrencyCode {
pub fn new(value: impl AsRef<str>) -> Result<Self, CurrencyCodeError> {
let value = value.as_ref();
if value.len() != 3 {
return Err(CurrencyCodeError::InvalidLength);
}
if !value.bytes().all(|byte| byte.is_ascii_alphabetic()) {
return Err(CurrencyCodeError::NotAlphabetic);
}
if !value.bytes().all(|byte| byte.is_ascii_uppercase()) {
return Err(CurrencyCodeError::NotUppercase);
}
Ok(Self(value.to_string()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self) -> String {
self.0
}
}
impl AsRef<str> for CurrencyCode {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl fmt::Display for CurrencyCode {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl FromStr for CurrencyCode {
type Err = CurrencyCodeError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
Self::new(value)
}
}
impl TryFrom<&str> for CurrencyCode {
type Error = CurrencyCodeError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::new(value)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CurrencyCodeError {
InvalidLength,
NotAlphabetic,
NotUppercase,
}
impl fmt::Display for CurrencyCodeError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidLength => formatter.write_str("currency code must be exactly 3 letters"),
Self::NotAlphabetic => {
formatter.write_str("currency code must contain only ASCII letters")
},
Self::NotUppercase => formatter.write_str("currency code must be uppercase"),
}
}
}
impl Error for CurrencyCodeError {}
#[cfg(test)]
mod tests {
use super::{AUD, CAD, CurrencyCode, CurrencyCodeError, EUR, GBP, JPY, USD};
#[test]
fn accepts_common_uppercase_codes() -> Result<(), CurrencyCodeError> {
for code in [USD, EUR, GBP, CAD, AUD, JPY] {
let currency = CurrencyCode::new(code)?;
assert_eq!(currency.as_str(), code);
assert_eq!(currency.to_string(), code);
}
Ok(())
}
#[test]
fn rejects_lowercase_codes() {
assert_eq!(
CurrencyCode::new("usd"),
Err(CurrencyCodeError::NotUppercase)
);
}
#[test]
fn rejects_invalid_shapes() {
assert_eq!(
CurrencyCode::new("US"),
Err(CurrencyCodeError::InvalidLength)
);
assert_eq!(
CurrencyCode::new("USDA"),
Err(CurrencyCodeError::InvalidLength)
);
assert_eq!(
CurrencyCode::new("U1D"),
Err(CurrencyCodeError::NotAlphabetic)
);
}
}