iban-tools

Tools / code generators for IBAN validation
Log | Files | Refs

codegen_rs.py (5015B)


      1 #!/usr/bin/env python3
      2 
      3 import json
      4 
      5 with open("registry.json", "r") as json_file:
      6     registry = json.load(json_file)
      7 
      8 rust = """/*
      9   This file is part of TALER
     10   Copyright (C) 2025 Taler Systems SA
     11 
     12   TALER is free software; you can redistribute it and/or modify it under the
     13   terms of the GNU Affero General Public License as published by the Free Software
     14   Foundation; either version 3, or (at your option) any later version.
     15 
     16   TALER is distributed in the hope that it will be useful, but WITHOUT ANY
     17   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     18   A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
     19 
     20   You should have received a copy of the GNU Affero General Public License along with
     21   TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     22 */
     23 
     24 use std::fmt::Display;
     25 
     26 use IbanC::*;
     27 use Country::*;
     28 
     29 /// IBAN ASCII characters rules
     30 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
     31 pub enum IbanC {
     32     /// Digits (0-9)
     33     N,
     34     /// Uppercase (A-Z)
     35     A,
     36     /// Digits or uppercase (0-9 & A-Z)
     37     C,
     38 }
     39 
     40 impl IbanC {
     41     /// Check whether every byte matches this IBAN character rule
     42     pub fn check(self, iban_ascii: &[u8]) -> bool {
     43         match self {
     44             Self::N => iban_ascii.iter().all(u8::is_ascii_digit),
     45             Self::A => iban_ascii.iter().all(u8::is_ascii_uppercase),
     46             Self::C => iban_ascii
     47                 .iter()
     48                 .all(|b| b.is_ascii_digit() || b.is_ascii_uppercase()),
     49         }
     50     }
     51 }
     52 
     53 /// An IBAN pattern, an array of characters rules over a number of character
     54 pub type Pattern = &'static [(u8, IbanC)];
     55 
     56 #[derive(Debug)]
     57 pub enum PatternErr {
     58     Len(u8, usize),
     59     Malformed,
     60 }
     61 """
     62 
     63 
     64 def gen_match(name, return_type, match):
     65     global rust
     66     rust += f"pub const fn {name}(self) -> {return_type} {{\nmatch self {{\n"
     67     for r in registry:
     68         rust += f"{r['code']} => {match(r)},\n"
     69     rust += "}\n}\n\n"
     70 
     71 
     72 def gen_range(name):
     73     def fmt_range(r):
     74         (start, end) = r[name + "_range"] or [0, 0]
     75         return f"{start}..{end}"
     76 
     77     gen_match(f"{name}_id", "core::ops::Range<usize>", fmt_range)
     78 
     79 
     80 def gen_pattern(name):
     81     def fmt_pattern(r):
     82         pattern = r[name + "_rules"] or []
     83         fmt = "&["
     84         for repetition, char in pattern:
     85             fmt += f"({repetition}, {char.upper()}),"
     86         return fmt + "]"
     87 
     88     gen_match(f"{name}_pattern", "Pattern", fmt_pattern)
     89 
     90 
     91 rust += "#[derive(Debug, Clone, Copy, PartialEq, Eq)]\n"
     92 rust += "pub enum Country {\n"
     93 for r in registry:
     94     rust += f"    {r['code']},\n"
     95 rust += "}\n\n"
     96 rust += "impl Country {\n"
     97 rust += "pub fn from_iso(country: &str) -> Option<Self> {\n"
     98 rust += "    match country {\n"
     99 for r in registry:
    100     rust += f'"{r["code"]}" => Some({r["code"]}),\n'
    101 rust += "        _ => None,\n"
    102 rust += "    }\n"
    103 rust += "}\n\n"
    104 gen_match("iso", "&'static str", lambda r: f'"{r["code"]}"')
    105 gen_match("iso_bytes", "&'static [u8; 2]", lambda r: f'b"{r["code"]}"')
    106 gen_match("iban_len", "usize", lambda r: f"{r['iban_len']}")
    107 rust += "pub const fn bban_len(self) -> usize {\n"
    108 rust += "    self.iban_len() - 4\n"
    109 rust += "}\n\n"
    110 gen_range("bank")
    111 gen_range("branch")
    112 gen_pattern("bban")
    113 gen_pattern("bank")
    114 gen_pattern("branch")
    115 rust += "}\n\n"
    116 
    117 rust += """
    118 impl Display for Country {
    119     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    120         f.write_str(self.iso())
    121     }
    122 }
    123 
    124 /// Generate random ASCII string following an IBAN pattern rules
    125 pub fn rng_pattern(out: &mut [u8], pattern: Pattern) {
    126     let mut cursor = 0;
    127     for (len, rule) in pattern {
    128         let alphabet = match rule {
    129             IbanC::C => "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
    130             IbanC::N => "0123456789",
    131             IbanC::A => "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
    132         };
    133         for b in &mut out[cursor..cursor + *len as usize] {
    134             *b = *fastrand::choice(alphabet.as_bytes()).unwrap();
    135         }
    136         cursor += *len as usize
    137     }
    138 }
    139 
    140 /// Validate an IBAN slice against a pattern
    141 pub fn check_pattern(iban_ascii: &[u8], pattern: Pattern) -> Result<(), PatternErr> {
    142     let pattern_len: u8 = pattern.iter().map(|(len, _)| *len as u8).sum();
    143     if iban_ascii.len() != pattern_len as usize {
    144         return Err(PatternErr::Len(pattern_len, iban_ascii.len()));
    145     }
    146     let mut cursor = 0;
    147     for (repetition, char) in pattern {
    148         if !char.check(&iban_ascii[cursor..cursor + *repetition as usize]) {
    149             return Err(PatternErr::Malformed);
    150         }
    151         cursor += *repetition as usize;
    152     }
    153     Ok(())
    154 }
    155 
    156 """
    157 rust += "#[cfg(test)]\n"
    158 rust += f"pub const VALID_IBAN: [(&str, Option<&str>); {len(registry)}] = [\n"
    159 for r in registry:
    160     rust += f'("{r["iban_example"]}", '
    161     bban = r["bban_example"]
    162     if bban is None:
    163         rust += "None"
    164     else:
    165         bban = "".join(filter(str.isalnum, bban))
    166         rust += f'Some("{bban}")'
    167     rust += "),\n"
    168 rust += "]\n;"
    169 
    170 with open("registry.rs", "w") as rs_file:
    171     rs_file.write(rust)