ifsc 0.1.1

A fast offline directory for Indian bank branches and IFSCs
Documentation
use core::fmt;

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
/// A branch-level payment rail reported by Razorpay.
pub enum BranchRail {
    /// National Electronic Funds Transfer.
    Neft,
    /// Real-time gross settlement.
    Rtgs,
    /// Immediate Payment Service.
    Imps,
    /// Unified Payments Interface.
    Upi,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
/// The set of payment rails reported for a branch.
pub struct BranchRails(pub(crate) u8);

impl BranchRails {
    /// Returns whether Razorpay reports the specified rail.
    pub const fn contains(self, rail: BranchRail) -> bool {
        self.0 & bit(rail) != 0
    }
    /// Returns whether no rails are reported.
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }
    /// Returns the number of reported rails.
    pub const fn len(self) -> usize {
        self.0.count_ones() as usize
    }
    /// Iterates over reported rails in NEFT, RTGS, IMPS, and UPI order.
    pub fn iter(self) -> BranchRailIter {
        BranchRailIter {
            rails: self,
            index: 0,
        }
    }
}
impl IntoIterator for BranchRails {
    type Item = BranchRail;
    type IntoIter = BranchRailIter;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}
/// An iterator over branch-level payment rails.
pub struct BranchRailIter {
    rails: BranchRails,
    index: u8,
}
impl Iterator for BranchRailIter {
    type Item = BranchRail;
    fn next(&mut self) -> Option<Self::Item> {
        while self.index < 4 {
            let rail = [
                BranchRail::Neft,
                BranchRail::Rtgs,
                BranchRail::Imps,
                BranchRail::Upi,
            ][self.index as usize];
            self.index += 1;
            if self.rails.contains(rail) {
                return Some(rail);
            }
        }
        None
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = (self.index..4)
            .filter(|i| {
                self.rails.contains(
                    [
                        BranchRail::Neft,
                        BranchRail::Rtgs,
                        BranchRail::Imps,
                        BranchRail::Upi,
                    ][*i as usize],
                )
            })
            .count();
        (remaining, Some(remaining))
    }
}
impl ExactSizeIterator for BranchRailIter {}
impl core::iter::FusedIterator for BranchRailIter {}
const fn bit(rail: BranchRail) -> u8 {
    match rail {
        BranchRail::Imps => 1,
        BranchRail::Rtgs => 2,
        BranchRail::Neft => 4,
        BranchRail::Upi => 8,
    }
}

#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// A canonical ISO 3166-2 subdivision code for India.
pub struct IsoSubdivision(pub(crate) [u8; 5]);
impl IsoSubdivision {
    /// Returns the canonical subdivision code.
    pub fn as_str(&self) -> &str {
        core::str::from_utf8(&self.0).expect("ISO subdivision invariant")
    }
    /// Parses an Indian ISO 3166-2 subdivision code.
    ///
    /// This function enforces a 64-byte input bound, trims surrounding ASCII
    /// whitespace, and normalizes ASCII letters to uppercase.
    pub fn parse(input: &str) -> crate::Result<Self> {
        if input.len() > 64 {
            return Err(crate::Error::new(crate::ErrorKind::TooLong));
        }
        let input = input.trim_matches(|c: char| c.is_ascii_whitespace());
        if input.len() != 5
            || !input.is_ascii()
            || !input[..2].eq_ignore_ascii_case("IN")
            || input.as_bytes()[2] != b'-'
            || !input[3..].bytes().all(|b| b.is_ascii_alphanumeric())
        {
            return Err(crate::Error::new(crate::ErrorKind::InvalidIsoSubdivision));
        }
        let mut bytes = [0; 5];
        bytes.copy_from_slice(input.as_bytes());
        bytes.make_ascii_uppercase();
        Ok(Self(bytes))
    }
    /// Parses only the canonical uppercase form without normalization.
    pub fn parse_strict(input: &str) -> crate::Result<Self> {
        let value = Self::parse(input)?;
        if value.as_str() == input {
            Ok(value)
        } else {
            Err(crate::Error::new(crate::ErrorKind::NotCanonical))
        }
    }
}
impl AsRef<str> for IsoSubdivision {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}
impl fmt::Display for IsoSubdivision {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}
impl fmt::Debug for IsoSubdivision {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("IsoSubdivision")
            .field(&self.as_str())
            .finish()
    }
}
impl core::str::FromStr for IsoSubdivision {
    type Err = crate::Error;

    fn from_str(input: &str) -> crate::Result<Self> {
        Self::parse(input)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for IsoSubdivision {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for IsoSubdivision {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = <std::borrow::Cow<'de, str> as serde::Deserialize>::deserialize(deserializer)?;
        Self::parse_strict(&value).map_err(serde::de::Error::custom)
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
/// An immutable branch record in the bundled snapshot.
pub struct Branch(pub(crate) u32);

impl Branch {
    fn row(self) -> crate::snapshot::BranchView {
        crate::snapshot::branch(self.0).expect("valid branch handle")
    }
    /// Returns the branch IFSC.
    pub fn ifsc(self) -> crate::Ifsc {
        self.row().ifsc()
    }
    /// Returns the routing prefix encoded in the IFSC.
    pub fn routing_code(self) -> crate::RoutingCode {
        self.ifsc().routing_code()
    }
    /// Returns Razorpay's reported bank name.
    pub fn reported_bank_name(self) -> Option<&'static str> {
        self.row().text(0)
    }
    /// Returns Razorpay's branch name.
    pub fn name(self) -> &'static str {
        self.row().text(1).expect("generated branch name")
    }
    /// Returns the reported centre.
    pub fn centre(self) -> &'static str {
        self.row().text(2).expect("generated branch centre")
    }
    /// Returns the reported district.
    pub fn district(self) -> &'static str {
        self.row().text(3).expect("generated branch district")
    }
    /// Returns the reported state.
    pub fn state(self) -> Option<&'static str> {
        self.row().text(4)
    }
    /// Returns the reported address.
    pub fn address(self) -> &'static str {
        self.row().text(5).expect("generated branch address")
    }
    /// Returns the reported contact text.
    pub fn contact(self) -> Option<&'static str> {
        self.row().text(6)
    }
    /// Returns the reported city.
    pub fn city(self) -> &'static str {
        self.row().text(7).expect("generated branch city")
    }
    /// Returns the reported ISO subdivision.
    pub fn iso_subdivision(self) -> Option<IsoSubdivision> {
        self.row()
            .text(8)
            .map(|value| IsoSubdivision::parse_strict(value).expect("generated subdivision"))
    }
    /// Returns the reported MICR text.
    pub fn micr(self) -> Option<&'static str> {
        self.row().text(9)
    }
    /// Returns the reported SWIFT text.
    pub fn swift(self) -> Option<&'static str> {
        self.row().text(10)
    }
    /// Returns all branch-level rails reported by Razorpay.
    pub fn reported_rails(self) -> BranchRails {
        BranchRails(self.row().flags())
    }
    /// Returns whether Razorpay reports one branch-level rail.
    pub fn reports(self, rail: BranchRail) -> bool {
        self.reported_rails().contains(rail)
    }
    /// Resolves the IFSC routing prefix through the bank-name directory.
    ///
    /// The result identifies the routing bank. It can differ from the bank
    /// reported on the branch or from a mapped sub-member institution.
    pub fn routing_bank(self) -> Option<crate::Bank> {
        crate::BankCode(self.routing_code().0).bank()
    }
    /// Returns the exact Razorpay sub-member mapping, if present.
    pub fn exact_sublet(self) -> Option<crate::SubletMatch> {
        crate::directory().exact_sublet(self.ifsc())
    }
    /// Iterates over matching custom sub-member prefixes.
    pub fn custom_sublets(self) -> crate::CustomSubletMatches {
        crate::directory().custom_sublets(self.ifsc())
    }
}