use std::{fmt, str::FromStr};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use thiserror::Error;
use crate::util::canonical_iban;
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Iban(String);
impl Iban {
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for Iban {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Debug, Error)]
#[error(transparent)]
pub struct ParseIbanError(#[from] ::iban::ParseIbanError);
impl FromStr for Iban {
type Err = ParseIbanError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
use ::iban::IbanLike as _;
let validated: ::iban::Iban = canonical_iban(s).parse()?;
Ok(Self(validated.electronic_str().to_owned()))
}
}
impl Serialize for Iban {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.0)
}
}
impl<'de> Deserialize<'de> for Iban {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
s.parse().map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parsing_canonicalizes_formatting() {
let iban: Iban = " de44 5001 0517 5407 3249 31 ".parse().unwrap();
assert_eq!(iban.as_str(), "DE44500105175407324931");
assert_eq!(iban.to_string(), "DE44500105175407324931");
}
#[test]
fn invalid_ibans_are_rejected() {
for invalid in [
"DE70000000000000000099",
"0",
"0000000000",
"0100433182",
"",
] {
assert!(invalid.parse::<Iban>().is_err());
}
}
}