ifsc 0.1.1

A fast offline directory for Indian bank branches and IFSCs
Documentation
use crate::{Error, ErrorKind, Result};
use core::{fmt, str::FromStr};

#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// A canonical 11-character Indian Financial System Code.
pub struct Ifsc(pub(crate) [u8; 11]);

#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// The four-character routing prefix encoded in an IFSC.
pub struct RoutingCode(pub(crate) [u8; 4]);

#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// A four-character code used by Razorpay's bank and sub-member records.
pub struct BankCode(pub(crate) [u8; 4]);

/// Parses an IFSC after enforcing a 64-byte input bound.
///
/// This function trims surrounding ASCII whitespace and normalizes ASCII
/// letters to uppercase. It does not remove interior separators or
/// whitespace.
pub fn parse(input: &str) -> Result<Ifsc> {
    if input.len() > 64 {
        return Err(Error::new(ErrorKind::TooLong));
    }
    let input = input.trim_matches(|c: char| c.is_ascii_whitespace());
    if input.len() != 11 || !input.is_ascii() {
        return Err(Error::new(ErrorKind::InvalidIfsc));
    }
    let mut bytes = [0; 11];
    bytes.copy_from_slice(input.as_bytes());
    bytes.make_ascii_uppercase();
    validate_ifsc(bytes)
        .then_some(Ifsc(bytes))
        .ok_or(Error::new(ErrorKind::InvalidIfsc))
}
/// Parses an IFSC that is already in canonical uppercase form.
///
/// Strict parsing does not trim whitespace or normalize letter case.
pub fn parse_strict(input: &str) -> Result<Ifsc> {
    let value = parse(input)?;
    if value.as_str() == input {
        Ok(value)
    } else {
        Err(Error::new(ErrorKind::NotCanonical))
    }
}
const fn validate_ifsc(bytes: [u8; 11]) -> bool {
    bytes[0].is_ascii_uppercase()
        && bytes[1].is_ascii_uppercase()
        && bytes[2].is_ascii_uppercase()
        && bytes[3].is_ascii_uppercase()
        && bytes[4] == b'0'
        && bytes[5].is_ascii_alphanumeric()
        && bytes[6].is_ascii_alphanumeric()
        && bytes[7].is_ascii_alphanumeric()
        && bytes[8].is_ascii_alphanumeric()
        && bytes[9].is_ascii_alphanumeric()
        && bytes[10].is_ascii_alphanumeric()
}

impl Ifsc {
    /// Returns the canonical IFSC text.
    pub fn as_str(&self) -> &str {
        core::str::from_utf8(&self.0).expect("IFSC invariant")
    }
    /// Returns the four-character routing prefix.
    pub const fn routing_code(self) -> RoutingCode {
        RoutingCode([self.0[0], self.0[1], self.0[2], self.0[3]])
    }
    /// Looks up this code in the bundled Razorpay snapshot.
    pub fn branch(self) -> Option<crate::Branch> {
        crate::lookup(self)
    }
    /// Returns whether this code occurs in the bundled snapshot.
    pub fn is_listed(self) -> bool {
        self.branch().is_some()
    }
}

macro_rules! code_impl {
    ($ty:ident, $kind:ident, $valid:expr) => {
        impl $ty {
            /// Parses a four-character code after enforcing a 64-byte input bound.
            ///
            /// This function trims surrounding ASCII whitespace and normalizes ASCII
            /// letters to uppercase.
            pub fn parse(input: &str) -> Result<Self> {
                if input.len() > 64 {
                    return Err(Error::new(ErrorKind::TooLong));
                }
                let input = input.trim_matches(|c: char| c.is_ascii_whitespace());
                if input.len() != 4 || !input.bytes().all($valid) {
                    return Err(Error::new(ErrorKind::$kind));
                }
                let mut bytes = [0; 4];
                bytes.copy_from_slice(input.as_bytes());
                bytes.make_ascii_uppercase();
                Ok(Self(bytes))
            }
            /// Parses a canonical four-character uppercase code without normalization.
            pub fn parse_strict(input: &str) -> Result<Self> {
                let value = Self::parse(input)?;
                if value.as_str() == input {
                    Ok(value)
                } else {
                    Err(Error::new(ErrorKind::NotCanonical))
                }
            }
            /// Returns the canonical four-character code.
            pub fn as_str(&self) -> &str {
                core::str::from_utf8(&self.0).expect("code invariant")
            }
        }
    };
}
code_impl!(RoutingCode, InvalidRoutingCode, |byte: u8| byte
    .is_ascii_alphabetic());
code_impl!(BankCode, InvalidBankCode, |byte: u8| byte
    .is_ascii_alphanumeric());

impl RoutingCode {
    /// Iterates over listed branches that use this routing code.
    pub fn branches(self) -> crate::Branches {
        crate::directory().branches_for_routing_code(self)
    }
}

impl BankCode {
    /// Returns the Razorpay bank-name entry for this code.
    pub fn bank(self) -> Option<crate::Bank> {
        crate::directory().bank(self)
    }
    /// Returns the Razorpay bank profile for this code.
    pub fn profile(self) -> Option<crate::BankProfile> {
        crate::directory().bank_profile(self)
    }
}

macro_rules! traits {
    ($ty:ident, $parse:path) => {
        impl AsRef<str> for $ty {
            fn as_ref(&self) -> &str {
                self.as_str()
            }
        }
        impl fmt::Display for $ty {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(self.as_str())
            }
        }
        impl fmt::Debug for $ty {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.debug_tuple(stringify!($ty))
                    .field(&self.as_str())
                    .finish()
            }
        }
        impl FromStr for $ty {
            type Err = Error;
            fn from_str(input: &str) -> Result<Self> {
                $parse(input)
            }
        }
    };
}
traits!(Ifsc, parse);
traits!(RoutingCode, RoutingCode::parse);
traits!(BankCode, BankCode::parse);

#[cfg(feature = "serde")]
mod serde_impl {
    use super::*;
    macro_rules! serde_id {
        ($ty:ident, $parse:path) => {
            impl serde::Serialize for $ty {
                fn serialize<S: serde::Serializer>(
                    &self,
                    serializer: S,
                ) -> core::result::Result<S::Ok, S::Error> {
                    serializer.serialize_str(self.as_str())
                }
            }
            impl<'de> serde::Deserialize<'de> for $ty {
                fn deserialize<D: serde::Deserializer<'de>>(
                    deserializer: D,
                ) -> core::result::Result<Self, D::Error> {
                    let value = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
                    $parse(&value).map_err(serde::de::Error::custom)
                }
            }
        };
    }
    serde_id!(Ifsc, parse_strict);
    serde_id!(RoutingCode, RoutingCode::parse_strict);
    serde_id!(BankCode, BankCode::parse_strict);
}