kontochronik 0.4.0

Long-Term archive for account transactions
Documentation
use std::{fmt, str::FromStr};

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use thiserror::Error;

use crate::util::canonical_iban;

/// A validated 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)
    }
}

/// The string is not a valid IBAN.
#[derive(Debug, Error)]
#[error(transparent)]
pub struct ParseIbanError(#[from] ::iban::ParseIbanError);

impl FromStr for Iban {
    type Err = ParseIbanError;

    /// Lenient about formatting (whitespace, case),
    /// strict about content (country format and checksum).
    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() {
        // A broken checksum, placeholders, legacy account numbers.
        for invalid in [
            "DE70000000000000000099",
            "0",
            "0000000000",
            "0100433182",
            "",
        ] {
            assert!(invalid.parse::<Iban>().is_err());
        }
    }
}