Skip to content

Commit

Permalink
using rustc-hash instead of HashMap to improve performance
Browse files Browse the repository at this point in the history
  • Loading branch information
ericqu committed Jan 3, 2025
1 parent 5cc696f commit b1287e1
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
1 change: 1 addition & 0 deletions iban_validation_rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ repository = "https://github.com/ericqu/iban_validation"
description = "Facilitate validation of ibans and selecting Bank_id and Branch_id in Rust."

[dependencies]
rustc-hash = "2.1.0"
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
Expand Down
14 changes: 10 additions & 4 deletions iban_validation_rs/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use rustc_hash::FxHashMap;
use serde_derive::{Deserialize, Serialize};
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::sync::LazyLock;
Expand Down Expand Up @@ -54,18 +54,18 @@ impl fmt::Display for ValidationError {
impl Error for ValidationError {}

/// utility function to load the registry (as json) into a Hashmap
fn convert_to_hashmap(json_str: &str) -> Result<HashMap<[u8; 2], IbanFields>, serde_json::Error> {
fn convert_to_hashmap(json_str: &str) -> Result<FxHashMap<[u8; 2], IbanFields>, serde_json::Error> {
let items: Vec<IbanFields> = serde_json::from_str(json_str)?;

let map: HashMap<[u8; 2], IbanFields> =
let map: FxHashMap<[u8; 2], IbanFields> =
items.into_iter().map(|item| (item.ctry_cd, item)).collect();

Ok(map)
}

/// trigger the loading of the registry once need, and only once.
/// panics if failing as there is no other way forward.
static IB_REG: LazyLock<HashMap<[u8; 2], IbanFields>> = LazyLock::new(|| {
static IB_REG: LazyLock<FxHashMap<[u8; 2], IbanFields>> = LazyLock::new(|| {
convert_to_hashmap(include_str!("../data/iban_definitions.json"))
.expect("Failed parsing JSON data into a HashMap")
});
Expand Down Expand Up @@ -287,6 +287,12 @@ impl<'a> Iban<'a> {
mod tests {
use super::*;

#[test]
fn mini_test() {
let al_test = "DE44500105175407324931";
assert_eq!(validate_iban_str(al_test).unwrap_or(false), true);
}

#[test]
fn al_iban() {
let al_test = "AL47212110090000000235698741";
Expand Down

0 comments on commit b1287e1

Please sign in to comment.