rust_iso9362 0.1.0

ISO 9362 (Business Identifier Code, also known as the SWIFT/BIC code) defines a standard format for identifying business parties – in particular banks and financial institutions – in financial transactions. This crate parses, validates and decomposes BIC codes into their component parts.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! # rust_iso9362
//!
//! ISO 9362 defines the **Business Identifier Code** (BIC), more commonly known
//! as the *SWIFT code*. Unlike ISO 3166 (a finite, enumerable list of country
//! codes) a BIC is defined by its *structure*, so this crate is a parser /
//! validator rather than a static dataset.
//!
//! A BIC is 8 or 11 characters long and is composed of four parts:
//!
//! | Position | Part                       | Length | Charset    |
//! |----------|----------------------------|--------|------------|
//! | 1–4      | Business party prefix      | 4      | `A-Z`      |
//! | 5–6      | Country code (ISO 3166-1)  | 2      | `A-Z`      |
//! | 7–8      | Business party suffix      | 2      | `A-Z0-9`   |
//! | 9–11     | Branch code (optional)     | 3      | `A-Z0-9`   |
//!
//! The *business party prefix* is also called the institution / bank code and
//! the *business party suffix* the location code.
//!
//! # Sample code
//! ```
//! let bic = rust_iso9362::parse("DEUTDEFF500").unwrap();
//! assert_eq!(bic.business_party_prefix(), "DEUT");
//! assert_eq!(bic.country_code(), "DE");
//! assert_eq!(bic.business_party_suffix(), "FF");
//! assert_eq!(bic.branch_code(), Some("500"));
//! assert_eq!(bic.bic8(), "DEUTDEFF");
//!
//! // 8-character BICs identify the primary office
//! let bic = rust_iso9362::parse("DEUTDEFF").unwrap();
//! assert_eq!(bic.branch_code(), None);
//! assert!(bic.is_primary_office());
//! assert_eq!(bic.bic11(), "DEUTDEFFXXX");
//!
//! assert!(rust_iso9362::is_valid("DEUTDEFF"));
//! assert!(!rust_iso9362::is_valid("123"));
//! ```

use std::fmt;

#[cfg(all(direct_wasm, target_arch = "wasm32"))]
use wasm_bindgen::prelude::*;

#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// The error returned when a string is not a valid ISO 9362 BIC.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ParseError {
    /// The code is not 8 or 11 characters long (carries the actual length).
    InvalidLength(usize),
    /// The code contains a non-ASCII character.
    NonAscii,
    /// Positions 1–4 (business party prefix) are not all letters.
    InvalidBusinessPartyPrefix,
    /// Positions 5–6 (country code) are not all letters.
    InvalidCountryCode,
    /// Positions 7–8 (business party suffix) are not all alphanumeric.
    InvalidBusinessPartySuffix,
    /// Positions 9–11 (branch code) are not all alphanumeric.
    InvalidBranchCode,
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ParseError::InvalidLength(n) => {
                write!(f, "invalid BIC length {n}: expected 8 or 11 characters")
            }
            ParseError::NonAscii => write!(f, "BIC contains a non-ASCII character"),
            ParseError::InvalidBusinessPartyPrefix => {
                write!(f, "invalid business party prefix: positions 1-4 must be letters")
            }
            ParseError::InvalidCountryCode => {
                write!(f, "invalid country code: positions 5-6 must be letters")
            }
            ParseError::InvalidBusinessPartySuffix => {
                write!(f, "invalid business party suffix: positions 7-8 must be alphanumeric")
            }
            ParseError::InvalidBranchCode => {
                write!(f, "invalid branch code: positions 9-11 must be alphanumeric")
            }
        }
    }
}

impl std::error::Error for ParseError {}

/// A parsed, validated ISO 9362 Business Identifier Code.
///
/// The canonical (upper-cased) code is stored internally; the individual
/// component parts are exposed through accessor methods.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct BIC {
    code: String,
}

impl BIC {
    /// Parse and validate a BIC string, returning the structured [`BIC`].
    ///
    /// Input is upper-cased before validation, so lower-case codes are accepted.
    ///
    /// ```
    /// let bic = rust_iso9362::BIC::parse("nedszajj").unwrap();
    /// assert_eq!(bic.code(), "NEDSZAJJ");
    /// assert_eq!(bic.country_code(), "ZA");
    /// ```
    pub fn parse(input: &str) -> Result<BIC, ParseError> {
        let code = input.to_ascii_uppercase();

        if !code.is_ascii() {
            return Err(ParseError::NonAscii);
        }

        let b = code.as_bytes();
        if b.len() != 8 && b.len() != 11 {
            return Err(ParseError::InvalidLength(b.len()));
        }

        if !b[0..4].iter().all(u8::is_ascii_alphabetic) {
            return Err(ParseError::InvalidBusinessPartyPrefix);
        }
        if !b[4..6].iter().all(u8::is_ascii_alphabetic) {
            return Err(ParseError::InvalidCountryCode);
        }
        if !b[6..8].iter().all(u8::is_ascii_alphanumeric) {
            return Err(ParseError::InvalidBusinessPartySuffix);
        }
        if b.len() == 11 && !b[8..11].iter().all(u8::is_ascii_alphanumeric) {
            return Err(ParseError::InvalidBranchCode);
        }

        Ok(BIC { code })
    }

    /// The full canonical (upper-cased) BIC, 8 or 11 characters.
    pub fn code(&self) -> &str {
        &self.code
    }

    /// Positions 1–4: the business party prefix (a.k.a. institution / bank code).
    pub fn business_party_prefix(&self) -> &str {
        &self.code[0..4]
    }

    /// Alias for [`BIC::business_party_prefix`].
    pub fn bank_code(&self) -> &str {
        self.business_party_prefix()
    }

    /// Positions 5–6: the ISO 3166-1 alpha-2 country code.
    pub fn country_code(&self) -> &str {
        &self.code[4..6]
    }

    /// Positions 7–8: the business party suffix (a.k.a. location code).
    pub fn business_party_suffix(&self) -> &str {
        &self.code[6..8]
    }

    /// Alias for [`BIC::business_party_suffix`].
    pub fn location_code(&self) -> &str {
        self.business_party_suffix()
    }

    /// Positions 9–11: the branch code, or `None` for an 8-character BIC.
    pub fn branch_code(&self) -> Option<&str> {
        if self.code.len() == 11 {
            Some(&self.code[8..11])
        } else {
            None
        }
    }

    /// The 8-character "head office" form (positions 1–8) of the BIC.
    pub fn bic8(&self) -> &str {
        &self.code[0..8]
    }

    /// The 11-character form of the BIC; an absent branch code is rendered as
    /// the primary-office placeholder `XXX`.
    pub fn bic11(&self) -> String {
        match self.branch_code() {
            Some(_) => self.code.clone(),
            None => format!("{}XXX", self.code),
        }
    }

    /// Whether this BIC refers to the primary office: either an 8-character BIC
    /// or one whose branch code is the placeholder `XXX`.
    pub fn is_primary_office(&self) -> bool {
        matches!(self.branch_code(), None | Some("XXX"))
    }

    /// Whether this is a test & training BIC (the 8th character is `0`).
    pub fn is_test_bic(&self) -> bool {
        self.code.as_bytes()[7] == b'0'
    }

    /// Whether the institution is a passive SWIFT participant (the 8th
    /// character is `1`).
    pub fn is_passive(&self) -> bool {
        self.code.as_bytes()[7] == b'1'
    }

    /// Resolve the embedded ISO 3166-1 country via the `rust_iso3166` crate.
    ///
    /// Returns `None` if the (syntactically valid) country code is not an
    /// assigned ISO 3166-1 alpha-2 code. Requires the `iso3166` feature.
    #[cfg(feature = "iso3166")]
    pub fn country(&self) -> Option<rust_iso3166::CountryCode> {
        rust_iso3166::from_alpha2(self.country_code())
    }
}

#[cfg(all(direct_wasm, target_arch = "wasm32"))]
#[wasm_bindgen]
impl BIC {
    #[wasm_bindgen(getter, js_name = code)]
    pub fn code_js(&self) -> String {
        self.code.clone()
    }

    #[wasm_bindgen(getter, js_name = businessPartyPrefix)]
    pub fn business_party_prefix_js(&self) -> String {
        self.business_party_prefix().into()
    }

    #[wasm_bindgen(getter, js_name = countryCode)]
    pub fn country_code_js(&self) -> String {
        self.country_code().into()
    }

    #[wasm_bindgen(getter, js_name = businessPartySuffix)]
    pub fn business_party_suffix_js(&self) -> String {
        self.business_party_suffix().into()
    }

    #[wasm_bindgen(getter, js_name = branchCode)]
    pub fn branch_code_js(&self) -> Option<String> {
        self.branch_code().map(Into::into)
    }

    #[wasm_bindgen(js_name = bic11)]
    pub fn bic11_js(&self) -> String {
        self.bic11()
    }

    #[wasm_bindgen(getter, js_name = isPrimaryOffice)]
    pub fn is_primary_office_js(&self) -> bool {
        self.is_primary_office()
    }
}

impl fmt::Display for BIC {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.code)
    }
}

impl std::str::FromStr for BIC {
    type Err = ParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        BIC::parse(s)
    }
}

#[cfg(feature = "serde")]
impl Serialize for BIC {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.code)
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for BIC {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::Error;
        let s = String::deserialize(deserializer)?;
        BIC::parse(&s).map_err(|e| D::Error::custom(format!("invalid BIC '{s}': {e}")))
    }
}

/// Parse and validate a BIC string, returning the structured [`BIC`].
///
/// ```
/// let bic = rust_iso9362::parse("DEUTDEFF").unwrap();
/// assert_eq!(bic.business_party_prefix(), "DEUT");
/// ```
#[cfg_attr(all(direct_wasm, target_arch = "wasm32"), wasm_bindgen)]
pub fn parse(input: &str) -> Option<BIC> {
    BIC::parse(input).ok()
}

/// Returns `true` if the given string is a syntactically valid ISO 9362 BIC.
///
/// ```
/// assert!(rust_iso9362::is_valid("DEUTDEFF500"));
/// assert!(!rust_iso9362::is_valid("DEUTDE")); // too short
/// ```
#[cfg_attr(all(direct_wasm, target_arch = "wasm32"), wasm_bindgen)]
pub fn is_valid(input: &str) -> bool {
    BIC::parse(input).is_ok()
}

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

    #[test]
    fn parses_11_char_bic() {
        let bic = BIC::parse("DEUTDEFF500").unwrap();
        assert_eq!(bic.code(), "DEUTDEFF500");
        assert_eq!(bic.business_party_prefix(), "DEUT");
        assert_eq!(bic.bank_code(), "DEUT");
        assert_eq!(bic.country_code(), "DE");
        assert_eq!(bic.business_party_suffix(), "FF");
        assert_eq!(bic.location_code(), "FF");
        assert_eq!(bic.branch_code(), Some("500"));
        assert_eq!(bic.bic8(), "DEUTDEFF");
        assert_eq!(bic.bic11(), "DEUTDEFF500");
        assert!(!bic.is_primary_office());
    }

    #[test]
    fn parses_8_char_bic() {
        let bic = BIC::parse("DEUTDEFF").unwrap();
        assert_eq!(bic.branch_code(), None);
        assert_eq!(bic.bic8(), "DEUTDEFF");
        assert_eq!(bic.bic11(), "DEUTDEFFXXX");
        assert!(bic.is_primary_office());
    }

    #[test]
    fn primary_office_branch_xxx() {
        let bic = BIC::parse("NEDSZAJJXXX").unwrap();
        assert_eq!(bic.branch_code(), Some("XXX"));
        assert!(bic.is_primary_office());
    }

    #[test]
    fn lowercase_is_normalised() {
        let bic = BIC::parse("deutdeff500").unwrap();
        assert_eq!(bic.code(), "DEUTDEFF500");
    }

    #[test]
    fn test_and_passive_flags() {
        assert!(BIC::parse("DEUTDEF0").unwrap().is_test_bic());
        assert!(BIC::parse("DEUTDEF1").unwrap().is_passive());
        assert!(!BIC::parse("DEUTDEFF").unwrap().is_test_bic());
        assert!(!BIC::parse("DEUTDEFF").unwrap().is_passive());
    }

    #[test]
    fn from_str_and_display() {
        let bic: BIC = "DEUTDEFF500".parse().unwrap();
        assert_eq!(bic.to_string(), "DEUTDEFF500");
    }

    #[test]
    fn rejects_bad_input() {
        assert_eq!(BIC::parse("DEUTDE").unwrap_err(), ParseError::InvalidLength(6));
        assert_eq!(BIC::parse("DEUTDEFF5000").unwrap_err(), ParseError::InvalidLength(12));
        assert_eq!(
            BIC::parse("1EUTDEFF").unwrap_err(),
            ParseError::InvalidBusinessPartyPrefix
        );
        assert_eq!(
            BIC::parse("DEUT1EFF").unwrap_err(),
            ParseError::InvalidCountryCode
        );
        assert_eq!(
            BIC::parse("DEUTDE-F").unwrap_err(),
            ParseError::InvalidBusinessPartySuffix
        );
        assert_eq!(
            BIC::parse("DEUTDEFF5-0").unwrap_err(),
            ParseError::InvalidBranchCode
        );
        assert_eq!(BIC::parse("DEUTDÉFF").unwrap_err(), ParseError::NonAscii);
    }

    #[test]
    fn free_functions() {
        assert!(is_valid("DEUTDEFF500"));
        assert!(!is_valid("nope"));
        assert!(parse("DEUTDEFF").is_some());
        assert!(parse("nope").is_none());
    }

    #[cfg(feature = "iso3166")]
    #[test]
    fn resolves_country() {
        let bic = BIC::parse("DEUTDEFF").unwrap();
        assert_eq!(bic.country().unwrap().alpha3, "DEU");
        // ZZ is syntactically valid but not an assigned country code.
        assert!(BIC::parse("DEUTZZFF").unwrap().country().is_none());
    }
}