ifsc 0.1.1

A fast offline directory for Indian bank branches and IFSCs
Documentation
use crate::{Branch, BranchRail};

#[derive(Clone)]
pub(super) enum BranchFilter {
    All,
    Micr(String),
    Swift(String),
    Rail(BranchRail),
}

impl BranchFilter {
    fn matches(&self, branch: Branch) -> bool {
        match self {
            Self::All => true,
            Self::Micr(value) => branch.micr() == Some(value.as_str()),
            Self::Swift(value) => branch.swift() == Some(value.as_str()),
            Self::Rail(rail) => branch.reports(*rail),
        }
    }
}

/// An iterator over branches, optionally constrained by a directory filter.
#[derive(Clone)]
pub struct Branches {
    cursor: u32,
    end: u32,
    filter: BranchFilter,
}

impl Branches {
    pub(super) fn all() -> Self {
        Self {
            cursor: 0,
            end: crate::snapshot::branch_count(),
            filter: BranchFilter::All,
        }
    }

    pub(super) fn filtered(filter: BranchFilter) -> Self {
        Self {
            filter,
            ..Self::all()
        }
    }

    pub(super) fn range(range: core::ops::Range<u32>) -> Self {
        Self {
            cursor: range.start,
            end: range.end,
            filter: BranchFilter::All,
        }
    }
}

impl Iterator for Branches {
    type Item = Branch;

    fn next(&mut self) -> Option<Branch> {
        while self.cursor < self.end {
            let branch = Branch(self.cursor);
            self.cursor += 1;
            if self.filter.matches(branch) {
                return Some(branch);
            }
        }
        None
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = (self.end - self.cursor) as usize;
        if matches!(self.filter, BranchFilter::All) {
            (remaining, Some(remaining))
        } else {
            (0, Some(remaining))
        }
    }
}

impl core::iter::FusedIterator for Branches {}