use std::str::FromStr;
use crate::country::is_country_code;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum BicPattern {
Alphanumeric,
LettersOnly,
}
impl BicPattern {
#[must_use]
pub const fn as_xsd_pattern(self) -> &'static str {
match self {
Self::Alphanumeric => "[A-Z0-9]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3}){0,1}",
Self::LettersOnly => "[A-Z]{6}[A-Z2-9][A-NP-Z0-9]([A-Z0-9]{3}){0,1}",
}
}
fn admits(self, bic: &str) -> bool {
let bytes = bic.as_bytes();
let at = |i: usize| bytes.get(i).copied().unwrap_or(0);
match self {
Self::Alphanumeric => true,
Self::LettersOnly => {
(0..6).all(|i| at(i).is_ascii_uppercase())
&& matches!(at(6), b'A'..=b'Z' | b'2'..=b'9')
&& (at(7).is_ascii_digit() || (at(7).is_ascii_uppercase() && at(7) != b'O'))
}
}
}
}
impl std::fmt::Display for BicPattern {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_xsd_pattern())
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Bic(String);
impl Bic {
#[inline]
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[inline]
#[must_use]
pub fn institution_code(&self) -> &str {
&self.0[..4]
}
#[inline]
#[must_use]
pub fn country_code(&self) -> &str {
&self.0[4..6]
}
#[inline]
#[must_use]
pub fn location_code(&self) -> &str {
&self.0[6..8]
}
#[inline]
#[must_use]
pub fn branch_code(&self) -> Option<&str> {
if self.0.len() == 11 {
Some(&self.0[8..])
} else {
None
}
}
#[inline]
#[must_use]
pub fn is_test(&self) -> bool {
self.location_suffix() == Some(b'0')
}
#[inline]
#[must_use]
pub fn is_passive(&self) -> bool {
self.location_suffix() == Some(b'1')
}
#[inline]
fn location_suffix(&self) -> Option<u8> {
self.0.as_bytes().get(7).copied()
}
#[inline]
#[must_use]
pub fn is_primary_office(&self) -> bool {
matches!(self.branch_code(), None | Some("XXX"))
}
#[inline]
#[must_use]
pub fn fits(&self, pattern: BicPattern) -> bool {
pattern.admits(&self.0)
}
}
impl std::fmt::Display for Bic {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl AsRef<str> for Bic {
fn as_ref(&self) -> &str {
&self.0
}
}
impl std::ops::Deref for Bic {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl std::borrow::Borrow<str> for Bic {
fn borrow(&self) -> &str {
&self.0
}
}
impl From<Bic> for String {
fn from(bic: Bic) -> Self {
bic.0
}
}
impl FromStr for Bic {
type Err = BicError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
validate_bic(s)
}
}
impl TryFrom<&str> for Bic {
type Error = BicError;
fn try_from(s: &str) -> Result<Self, Self::Error> {
validate_bic(s)
}
}
impl TryFrom<String> for Bic {
type Error = BicError;
fn try_from(s: String) -> Result<Self, Self::Error> {
validate_bic(&s)
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for Bic {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(self.as_str())
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Bic {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
validate_bic(&s).map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum BicError {
#[error("BIC length {len} is invalid — must be 8 or 11 characters")]
InvalidLength {
len: usize,
},
#[error("BIC contains invalid character {ch:?} at position {pos}")]
InvalidCharacter {
ch: char,
pos: usize,
},
#[error("BIC country code {code:?} is not an ISO 3166-1 alpha-2 country")]
UnknownCountryCode {
code: String,
},
#[error("\"NOTPROVIDED\" is an EPC placeholder, not a valid BIC — use Option<Bic> with None")]
Placeholder,
}
#[must_use = "ignoring a validated BIC loses the result"]
pub fn validate_bic(raw: &str) -> Result<Bic, BicError> {
let upper: String = raw
.chars()
.filter(|c| !c.is_whitespace())
.map(|c| c.to_ascii_uppercase())
.collect();
if upper == "NOTPROVIDED" {
return Err(BicError::Placeholder);
}
let len = upper.chars().count();
if len != 8 && len != 11 {
return Err(BicError::InvalidLength { len });
}
for (pos, ch) in upper.chars().enumerate() {
let ok = match pos {
4 | 5 => ch.is_ascii_uppercase(),
_ => ch.is_ascii_uppercase() || ch.is_ascii_digit(),
};
if !ok {
return Err(BicError::InvalidCharacter { ch, pos });
}
}
let country = &upper[4..6];
if !is_country_code(country) {
return Err(BicError::UnknownCountryCode {
code: country.to_owned(),
});
}
Ok(Bic(upper))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cobadeff_8_char() {
let bic = validate_bic("COBADEFF").unwrap();
assert_eq!(bic.institution_code(), "COBA");
assert_eq!(bic.country_code(), "DE");
assert_eq!(bic.location_code(), "FF");
assert!(bic.branch_code().is_none());
}
#[test]
fn cobadeffxxx_11_char() {
let bic = validate_bic("COBADEFFXXX").unwrap();
assert_eq!(bic.branch_code(), Some("XXX"));
}
#[test]
fn lowercase_and_spacing_are_normalised() {
assert!(validate_bic("cobadeff").is_ok());
assert_eq!(
validate_bic("COBA DE FF XXX").unwrap().as_str(),
"COBADEFFXXX"
);
assert_eq!(validate_bic(" cobadeff\n").unwrap().as_str(), "COBADEFF");
}
#[test]
fn too_short() {
assert!(matches!(
validate_bic("COBA").unwrap_err(),
BicError::InvalidLength { len: 4 }
));
}
#[test]
fn too_long() {
assert!(matches!(
validate_bic("COBADEFFXXXX").unwrap_err(),
BicError::InvalidLength { len: 12 }
));
}
#[test]
fn not_provided_is_placeholder_error() {
assert!(matches!(
validate_bic("NOTPROVIDED").unwrap_err(),
BicError::Placeholder
));
}
#[test]
fn an_alphanumeric_business_party_prefix_is_accepted() {
for b in ["E097AEXX", "WG11US335AB", "C0BADEFF"] {
let bic = validate_bic(b).unwrap_or_else(|e| panic!("{b} must validate: {e}"));
assert!(bic.fits(BicPattern::Alphanumeric));
assert!(
!bic.fits(BicPattern::LettersOnly),
"{b} has a digit in the prefix, so no pre-2019 schema can hold it"
);
}
}
#[test]
fn the_legacy_pattern_keeps_the_pre_2019_suffix_restrictions() {
for narrow in ["DEUTDE0B", "DEUTDE1B", "DEUTDEFO"] {
let bic = validate_bic(narrow).unwrap();
assert!(
bic.fits(BicPattern::Alphanumeric),
"{narrow} is a valid BIC today"
);
assert!(
!bic.fits(BicPattern::LettersOnly),
"{narrow} must not be written into a pre-2019 schema"
);
}
for wide in ["DEUTDEF0", "DEUTDEF2", "COBADEFFXXX"] {
assert!(validate_bic(wide).unwrap().fits(BicPattern::LettersOnly));
}
}
#[test]
fn each_pattern_reports_the_xsd_it_came_from() {
assert_eq!(
BicPattern::Alphanumeric.as_xsd_pattern(),
"[A-Z0-9]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3}){0,1}"
);
assert_eq!(
BicPattern::LettersOnly.as_xsd_pattern(),
"[A-Z]{6}[A-Z2-9][A-NP-Z0-9]([A-Z0-9]{3}){0,1}"
);
}
#[test]
fn the_country_code_must_be_a_real_country() {
assert!(matches!(
validate_bic("COBAZZFF").unwrap_err(),
BicError::UnknownCountryCode { .. }
));
assert!(matches!(
validate_bic("COBAQQFFXXX").unwrap_err(),
BicError::UnknownCountryCode { .. }
));
assert!(validate_bic("NCBKXKPRXXX").is_ok());
}
#[test]
fn test_bic_is_marked_by_second_location_character() {
assert!(validate_bic("DEUTDEF0").unwrap().is_test());
assert!(!validate_bic("COBADEFF").unwrap().is_test());
}
#[test]
fn passive_participant_flag() {
assert!(validate_bic("DEUTDEF1").unwrap().is_passive());
assert!(!validate_bic("COBADEFF").unwrap().is_passive());
}
#[test]
fn primary_office_detection() {
assert!(validate_bic("COBADEFF").unwrap().is_primary_office());
assert!(validate_bic("COBADEFFXXX").unwrap().is_primary_office());
assert!(!validate_bic("COBADEFF123").unwrap().is_primary_office());
}
#[test]
fn country_code_must_be_letters() {
assert!(matches!(
validate_bic("COBA1EFF").unwrap_err(),
BicError::InvalidCharacter { ch: '1', pos: 4 }
));
}
#[test]
fn real_world_sepa_bics_are_accepted() {
for b in [
"COBADEFFXXX", "DEUTDEFF", "PBNKDEFF", "GENODEF1S04", "ABNANL2A", "BNPAFRPP", "UNCRITMM", "CRESCHZZ80A", ] {
assert!(validate_bic(b).is_ok(), "{b} must validate");
}
}
#[test]
fn sspkdehhxxx() {
assert!(validate_bic("SSPKDEHHXXX").is_ok());
}
#[test]
fn from_str() {
let bic: Bic = "COBADEFF".parse().unwrap();
assert_eq!(bic.as_str(), "COBADEFF");
}
#[test]
fn try_from_str() {
assert!(Bic::try_from("COBADEFF").is_ok());
assert!(Bic::try_from("BAD").is_err());
}
#[test]
fn into_string() {
let bic = validate_bic("COBADEFF").unwrap();
let s: String = bic.into();
assert_eq!(s, "COBADEFF");
}
#[test]
fn ord() {
let a = validate_bic("COBADEFF").unwrap();
let b = validate_bic("DEUTDEDB").unwrap();
assert!(a < b);
}
#[test]
fn deref_to_str() {
let bic = validate_bic("COBADEFF").unwrap();
assert_eq!(bic.len(), 8); }
#[cfg(feature = "serde")]
#[test]
fn serde_roundtrip() {
let bic = validate_bic("COBADEFFXXX").unwrap();
let json = serde_json::to_string(&bic).unwrap();
assert_eq!(json, r#""COBADEFFXXX""#);
let back: Bic = serde_json::from_str(&json).unwrap();
assert_eq!(back, bic);
}
#[cfg(feature = "serde")]
#[test]
fn serde_invalid_rejected() {
let result: Result<Bic, _> = serde_json::from_str(r#""NOTPROVIDED""#);
assert!(result.is_err());
}
}