ifsc 0.1.1

A fast offline directory for Indian bank branches and IFSCs
Documentation
mod bank;
mod branch;
mod layout;
mod sublet;

use std::sync::OnceLock;

use layout::*;

pub(crate) use bank::{
    BankNameView, BankView, bank_name, bank_name_count, bank_profile, bank_profile_count,
    find_bank_name, find_bank_profile,
};
pub(crate) use branch::{BranchView, branch, branch_count, find_branch, routing_range};
pub(crate) use sublet::{
    custom_sublet, custom_sublet_count, exact_sublet_count, find_exact_sublet,
};

static BYTES: &[u8] = include_bytes!("snapshot/directory.bin");
static SNAPSHOT: OnceLock<Snapshot> = OnceLock::new();

pub(super) fn snapshot() -> &'static Snapshot {
    SNAPSHOT.get_or_init(|| Snapshot::parse(BYTES).expect("bundled IFSC snapshot is valid"))
}

pub(super) struct Snapshot {
    bytes: &'static [u8],
    pub(super) branches: Section,
    pub(super) banks: Section,
    pub(super) names: Section,
    pub(super) sublets: Section,
    pub(super) custom_sublets: Section,
    strings_offset: u64,
    strings_len: u32,
}

#[derive(Clone, Copy)]
pub(super) struct Section {
    offset: u64,
    pub(super) count: u32,
    record_bytes: usize,
}

impl Snapshot {
    fn parse(bytes: &'static [u8]) -> Option<Self> {
        (bytes.len() >= HEADER_LEN as usize).then_some(())?;
        (bytes.get(..8)? == MAGIC).then_some(())?;
        (read_u32(bytes, VERSION_OFFSET) == VERSION).then_some(())?;
        (read_u32(bytes, HEADER_LEN_OFFSET) == HEADER_LEN).then_some(())?;
        (read_u64(bytes, FILE_LEN_OFFSET) == bytes.len() as u64).then_some(())?;

        let snapshot = Self {
            bytes,
            branches: Section::new(
                read_u64(bytes, BRANCHES_OFFSET),
                read_u32(bytes, BRANCH_COUNT_OFFSET),
                BRANCH_SIZE,
            ),
            banks: Section::new(
                read_u64(bytes, BANKS_OFFSET),
                read_u32(bytes, BANK_COUNT_OFFSET),
                BANK_SIZE,
            ),
            names: Section::new(
                read_u64(bytes, BANK_NAMES_OFFSET),
                read_u32(bytes, BANK_NAME_COUNT_OFFSET),
                BANK_NAME_SIZE,
            ),
            sublets: Section::new(
                read_u64(bytes, EXACT_SUBLETS_OFFSET),
                read_u32(bytes, EXACT_SUBLET_COUNT_OFFSET),
                EXACT_SUBLET_SIZE,
            ),
            custom_sublets: Section::new(
                read_u64(bytes, CUSTOM_SUBLETS_OFFSET),
                read_u32(bytes, CUSTOM_SUBLET_COUNT_OFFSET),
                CUSTOM_SUBLET_SIZE,
            ),
            strings_offset: read_u64(bytes, STRINGS_OFFSET),
            strings_len: read_u32(bytes, STRINGS_LEN_OFFSET),
        };
        snapshot.validate().then_some(snapshot)
    }

    fn validate(&self) -> bool {
        let sections = [
            self.branches,
            self.banks,
            self.names,
            self.sublets,
            self.custom_sublets,
        ];
        let starts = [
            u64::from(HEADER_LEN),
            self.branches.offset,
            self.banks.offset,
            self.names.offset,
            self.sublets.offset,
            self.custom_sublets.offset,
            self.strings_offset,
        ];
        starts.windows(2).all(|pair| pair[0] <= pair[1])
            && sections.iter().all(|section| {
                section
                    .end()
                    .is_some_and(|end| end <= self.bytes.len() as u64)
            })
            && self.branches.end() == Some(self.banks.offset)
            && self.banks.end() == Some(self.names.offset)
            && self.names.end() == Some(self.sublets.offset)
            && self.sublets.end() == Some(self.custom_sublets.offset)
            && self.custom_sublets.end() == Some(self.strings_offset)
            && self.strings_offset.checked_add(u64::from(self.strings_len))
                == Some(self.bytes.len() as u64)
    }

    pub(super) fn record(&self, section: Section, index: u32) -> Option<&'static [u8]> {
        let offset = usize::try_from(section.offset)
            .ok()?
            .checked_add(index as usize * section.record_bytes)?;
        self.bytes.get(offset..offset + section.record_bytes)
    }

    pub(super) fn text(&self, bytes: &[u8], offset: usize) -> Option<&'static str> {
        let packed = read_u32(bytes, offset);
        if packed == u32::MAX {
            return None;
        }
        // References pack a one-byte length with a 24-bit string-pool offset.
        let length = (packed >> 24) as usize;
        let relative = (packed & 0x00ff_ffff) as usize;
        let start = usize::try_from(self.strings_offset)
            .ok()?
            .checked_add(relative)?;
        core::str::from_utf8(self.bytes.get(start..start.checked_add(length)?)?).ok()
    }

    fn identity(&self, offset: usize, length: usize) -> &'static str {
        core::str::from_utf8(
            self.bytes
                .get(offset..offset + length)
                .expect("checked snapshot header"),
        )
        .expect("generated snapshot identity is UTF-8")
        .trim_end_matches('\0')
    }
}

impl Section {
    const fn new(offset: u64, count: u32, record_bytes: usize) -> Self {
        Self {
            offset,
            count,
            record_bytes,
        }
    }

    fn end(self) -> Option<u64> {
        self.offset
            .checked_add(u64::from(self.count).checked_mul(self.record_bytes as u64)?)
    }
}

pub(crate) fn razorpay_release() -> &'static str {
    snapshot().identity(RELEASE_OFFSET, RELEASE_LEN)
}

pub(crate) fn razorpay_commit() -> &'static str {
    snapshot().identity(COMMIT_OFFSET, COMMIT_LEN)
}

pub(crate) fn rbi_update_date() -> &'static str {
    snapshot().identity(RBI_DATE_OFFSET, RBI_DATE_LEN)
}

pub(super) fn search(
    mut high: u32,
    mut compare: impl FnMut(u32) -> core::cmp::Ordering,
) -> Option<u32> {
    let mut low = 0;
    while low < high {
        let middle = low + (high - low) / 2;
        match compare(middle) {
            core::cmp::Ordering::Less => low = middle + 1,
            core::cmp::Ordering::Greater => high = middle,
            core::cmp::Ordering::Equal => return Some(middle),
        }
    }
    None
}

pub(super) fn lower_bound(mut high: u32, mut is_less: impl FnMut(u32) -> bool) -> u32 {
    let mut low = 0;
    while low < high {
        let middle = low + (high - low) / 2;
        if is_less(middle) {
            low = middle + 1;
        } else {
            high = middle;
        }
    }
    low
}

fn read_u32(bytes: &[u8], offset: usize) -> u32 {
    u32::from_le_bytes(bytes[offset..offset + 4].try_into().expect("checked bytes"))
}

fn read_u64(bytes: &[u8], offset: usize) -> u64 {
    u64::from_le_bytes(
        bytes[offset..offset + 8]
            .try_into()
            .expect("checked header"),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    fn empty_snapshot() -> Vec<u8> {
        let mut bytes = vec![0; HEADER_LEN as usize];
        bytes[..8].copy_from_slice(MAGIC);
        bytes[VERSION_OFFSET..VERSION_OFFSET + 4].copy_from_slice(&VERSION.to_le_bytes());
        bytes[HEADER_LEN_OFFSET..HEADER_LEN_OFFSET + 4].copy_from_slice(&HEADER_LEN.to_le_bytes());
        for offset in [
            BRANCHES_OFFSET,
            BANKS_OFFSET,
            BANK_NAMES_OFFSET,
            EXACT_SUBLETS_OFFSET,
            CUSTOM_SUBLETS_OFFSET,
            STRINGS_OFFSET,
            FILE_LEN_OFFSET,
        ] {
            bytes[offset..offset + 8].copy_from_slice(&u64::from(HEADER_LEN).to_le_bytes());
        }
        bytes
    }

    #[test]
    fn rejects_short_and_corrupt_headers() {
        assert!(Snapshot::parse(b"IFSCDB01").is_none());
        let mut bytes = empty_snapshot();
        bytes[0] ^= 0xff;
        assert!(Snapshot::parse(Box::leak(bytes.into_boxed_slice())).is_none());
    }

    #[test]
    fn rejects_truncated_and_misordered_sections() {
        let mut truncated = empty_snapshot();
        truncated.pop();
        assert!(Snapshot::parse(Box::leak(truncated.into_boxed_slice())).is_none());
        let mut bytes = empty_snapshot();
        bytes[BANKS_OFFSET..BANKS_OFFSET + 8].copy_from_slice(&0_u64.to_le_bytes());
        assert!(Snapshot::parse(Box::leak(bytes.into_boxed_slice())).is_none());
    }
}