Skip to main content

fints_client/formats/
sepa.rs

1//! IBAN, BIC and the SEPA character sets (DFÜ-Abkommen Anlage 3 V26.11,
2//! section 2.1 "Zeichensatz", section 2.3.1.1 string types).
3//!
4//! The checks reject; they never repair. [`transliterate`] is the one
5//! helper that changes text, for a caller that wants to offer the user a
6//! cleaned version of a rejected text.
7
8use std::fmt;
9
10use crate::types::{Bic, Iban};
11
12/// Why a text, reference, IBAN or BIC is not acceptable for a SEPA order.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14#[non_exhaustive]
15pub enum Invalid {
16    /// Empty, or only spaces (Anlage 3 2.1: text fields must not be blank).
17    Empty,
18    /// Longer than `max` characters.
19    TooLong { max: usize },
20    /// A character outside the allowed set.
21    Character { ch: char },
22    /// A reference that starts or ends with `/` or contains `//`
23    /// (Anlage 3 2.1, footnote 8).
24    Slash,
25    /// Wrong length (IBAN 15..=34, BIC 8 or 11).
26    Length,
27    /// The IBAN does not start with two letters and two check digits.
28    Country,
29    /// The IBAN check digits are wrong (ISO 13616 mod 97).
30    Checksum,
31    /// The BIC is not `[A-Z0-9]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?`.
32    Format,
33}
34
35impl fmt::Display for Invalid {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        match self {
38            Self::Empty => f.write_str("empty"),
39            Self::TooLong { max } => write!(f, "longer than {max} characters"),
40            Self::Character { ch } => write!(f, "character {ch:?} is not allowed"),
41            Self::Slash => f.write_str("must not start or end with '/' or contain '//'"),
42            Self::Length => f.write_str("wrong length"),
43            Self::Country => f.write_str("must start with a country code and two check digits"),
44            Self::Checksum => f.write_str("check digits do not match"),
45            Self::Format => f.write_str("not a BIC (8 or 11 characters, AAAABBCC[DDD])"),
46        }
47    }
48}
49
50impl std::error::Error for Invalid {}
51
52/// Upper-case, without spaces.
53fn compact(s: &str) -> String {
54    s.chars()
55        .filter(|c| !c.is_whitespace())
56        .collect::<String>()
57        .to_ascii_uppercase()
58}
59
60impl Iban {
61    /// Check an IBAN: spaces removed, upper-cased, two letters, two check
62    /// digits, 15..=34 alphanumerics in all, mod 97 = 1 (ISO 13616; Anlage 3
63    /// 2.3.1.1 `IBAN2007Identifier`).
64    ///
65    /// ```
66    /// use fints_client::Iban;
67    /// assert_eq!(Iban::parse("de89 3704 0044 0532 0130 00").unwrap().as_str(),
68    ///            "DE89370400440532013000");
69    /// assert!(Iban::parse("DE88370400440532013000").is_err());
70    /// ```
71    pub fn parse(s: &str) -> Result<Iban, Invalid> {
72        let iban = compact(s);
73        if iban.is_empty() {
74            return Err(Invalid::Empty);
75        }
76        if let Some(ch) = iban.chars().find(|c| !c.is_ascii_alphanumeric()) {
77            return Err(Invalid::Character { ch });
78        }
79        if !(15..=34).contains(&iban.len()) {
80            return Err(Invalid::Length);
81        }
82        let b = iban.as_bytes();
83        if !(b[0].is_ascii_uppercase()
84            && b[1].is_ascii_uppercase()
85            && b[2].is_ascii_digit()
86            && b[3].is_ascii_digit())
87        {
88            return Err(Invalid::Country);
89        }
90        // Move the first four characters to the end, letters A..Z -> 10..35,
91        // and reduce digit by digit.
92        let mut rem: u32 = 0;
93        for &c in b[4..].iter().chain(&b[..4]) {
94            let v = if c.is_ascii_digit() {
95                u32::from(c - b'0')
96            } else {
97                u32::from(c - b'A') + 10
98            };
99            rem = if v >= 10 {
100                (rem * 100 + v) % 97
101            } else {
102                (rem * 10 + v) % 97
103            };
104        }
105        if rem != 1 {
106            return Err(Invalid::Checksum);
107        }
108        Ok(Iban::new(iban))
109    }
110}
111
112impl Bic {
113    /// Check a BIC: spaces removed, upper-cased, 8 or 11 characters of the
114    /// form `[A-Z0-9]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?` (Anlage 3
115    /// 2.3.1.1 `BICFIDec2014Identifier`).
116    ///
117    /// ```
118    /// use fints_client::Bic;
119    /// assert_eq!(Bic::parse("cobadeffxxx").unwrap().as_str(), "COBADEFFXXX");
120    /// assert!(Bic::parse("COBADEF").is_err());
121    /// ```
122    pub fn parse(s: &str) -> Result<Bic, Invalid> {
123        let bic = compact(s);
124        if bic.is_empty() {
125            return Err(Invalid::Empty);
126        }
127        if bic.len() != 8 && bic.len() != 11 {
128            return Err(Invalid::Length);
129        }
130        let ok = bic.bytes().enumerate().all(|(i, c)| match i {
131            4 | 5 => c.is_ascii_uppercase(),
132            _ => c.is_ascii_uppercase() || c.is_ascii_digit(),
133        });
134        if !ok {
135            return Err(Invalid::Format);
136        }
137        Ok(Bic::new(bic))
138    }
139}
140
141/// The EPC basic Latin set (Anlage 3 2.1, first table): `a-z A-Z 0-9` and
142/// `' : ? , - ( + . ) /` and space.
143fn is_basic(c: char) -> bool {
144    c.is_ascii_alphanumeric() || " '():?,-+./".contains(c)
145}
146
147/// A character of the SEPA text set: the basic set plus the characters the
148/// German banks are obliged to accept (Anlage 3 2.1, second table:
149/// `Ä Ö Ü ä ö ü ß & * $ %`).
150pub(crate) fn is_sepa_char(c: char) -> bool {
151    is_basic(c) || "ÄÖÜäöüß&*$%".contains(c)
152}
153
154/// The first character of `s` outside the SEPA text set, if any.
155pub(crate) fn first_invalid_char(s: &str) -> Option<char> {
156    s.chars().find(|&c| !is_sepa_char(c))
157}
158
159/// Whether `s` consists only of SEPA text characters (names, purpose).
160/// The empty string passes; length limits are the caller's.
161pub fn is_sepa_text(s: &str) -> bool {
162    first_invalid_char(s).is_none()
163}
164
165/// Whether `s` is a valid SEPA reference (`MsgId`, `PmtInfId`,
166/// `EndToEndId`): 1..=35 characters of the basic set (Anlage 3 2.3.1.1
167/// `Max35Text`, restricted pattern), not starting or ending with `/` and
168/// without `//` (Anlage 3 2.1, footnote 8).
169pub fn is_sepa_reference(s: &str) -> bool {
170    check_reference(s).is_ok()
171}
172
173/// [`is_sepa_reference`] with the reason.
174pub(crate) fn check_reference(s: &str) -> Result<(), Invalid> {
175    if s.is_empty() {
176        return Err(Invalid::Empty);
177    }
178    if s.chars().count() > 35 {
179        return Err(Invalid::TooLong { max: 35 });
180    }
181    if let Some(ch) = s.chars().find(|&c| !is_basic(c)) {
182        return Err(Invalid::Character { ch });
183    }
184    if s.starts_with('/') || s.ends_with('/') || s.contains("//") {
185        return Err(Invalid::Slash);
186    }
187    Ok(())
188}
189
190/// Replace every character outside the SEPA text set so the result passes
191/// [`is_sepa_text`]: accented Latin letters lose their accent (`é` → `e`,
192/// `Ç` → `C`), ligatures are spelled out (`æ` → `ae`, `Œ` → `OE`), any
193/// whitespace becomes a space, typographic quotes and dashes become `'`
194/// and `-`, everything else becomes `.` (the EPC best practice Anlage 3
195/// 2.1 names for `* $ %`). Characters of the set, umlauts and `ß`
196/// included, are kept. Length is not touched.
197pub fn transliterate(s: &str) -> String {
198    let mut out = String::with_capacity(s.len());
199    for c in s.chars() {
200        if is_sepa_char(c) {
201            out.push(c);
202        } else if c.is_whitespace() {
203            out.push(' ');
204        } else {
205            out.push_str(replacement(c));
206        }
207    }
208    out
209}
210
211fn replacement(c: char) -> &'static str {
212    match c {
213        'À' | 'Á' | 'Â' | 'Ã' | 'Å' | 'Ā' | 'Ă' | 'Ą' => "A",
214        'à' | 'á' | 'â' | 'ã' | 'å' | 'ā' | 'ă' | 'ą' => "a",
215        'Æ' => "AE",
216        'æ' => "ae",
217        'Ç' | 'Ć' | 'Ĉ' | 'Ċ' | 'Č' => "C",
218        'ç' | 'ć' | 'ĉ' | 'ċ' | 'č' => "c",
219        'Ď' | 'Đ' | 'Ð' => "D",
220        'ď' | 'đ' | 'ð' => "d",
221        'È' | 'É' | 'Ê' | 'Ë' | 'Ē' | 'Ĕ' | 'Ė' | 'Ę' | 'Ě' => "E",
222        'è' | 'é' | 'ê' | 'ë' | 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => "e",
223        'Ĝ' | 'Ğ' | 'Ġ' | 'Ģ' => "G",
224        'ĝ' | 'ğ' | 'ġ' | 'ģ' => "g",
225        'Ĥ' | 'Ħ' => "H",
226        'ĥ' | 'ħ' => "h",
227        'Ì' | 'Í' | 'Î' | 'Ï' | 'Ĩ' | 'Ī' | 'Ĭ' | 'Į' | 'İ' => "I",
228        'ì' | 'í' | 'î' | 'ï' | 'ĩ' | 'ī' | 'ĭ' | 'į' | 'ı' => "i",
229        'Ĵ' => "J",
230        'ĵ' => "j",
231        'Ķ' => "K",
232        'ķ' => "k",
233        'Ĺ' | 'Ļ' | 'Ľ' | 'Ŀ' | 'Ł' => "L",
234        'ĺ' | 'ļ' | 'ľ' | 'ŀ' | 'ł' => "l",
235        'Ñ' | 'Ń' | 'Ņ' | 'Ň' => "N",
236        'ñ' | 'ń' | 'ņ' | 'ň' => "n",
237        'Ò' | 'Ó' | 'Ô' | 'Õ' | 'Ø' | 'Ō' | 'Ŏ' | 'Ő' => "O",
238        'ò' | 'ó' | 'ô' | 'õ' | 'ø' | 'ō' | 'ŏ' | 'ő' => "o",
239        'Œ' => "OE",
240        'œ' => "oe",
241        'Ŕ' | 'Ŗ' | 'Ř' => "R",
242        'ŕ' | 'ŗ' | 'ř' => "r",
243        'Ś' | 'Ŝ' | 'Ş' | 'Š' | 'Ș' => "S",
244        'ś' | 'ŝ' | 'ş' | 'š' | 'ș' => "s",
245        'Ţ' | 'Ť' | 'Ŧ' | 'Ț' => "T",
246        'ţ' | 'ť' | 'ŧ' | 'ț' => "t",
247        'Þ' => "TH",
248        'þ' => "th",
249        'Ù' | 'Ú' | 'Û' | 'Ũ' | 'Ū' | 'Ŭ' | 'Ů' | 'Ű' | 'Ų' => "U",
250        'ù' | 'ú' | 'û' | 'ũ' | 'ū' | 'ŭ' | 'ů' | 'ű' | 'ų' => "u",
251        'Ŵ' => "W",
252        'ŵ' => "w",
253        'Ý' | 'Ÿ' | 'Ŷ' => "Y",
254        'ý' | 'ÿ' | 'ŷ' => "y",
255        'Ź' | 'Ż' | 'Ž' => "Z",
256        'ź' | 'ż' | 'ž' => "z",
257        '‘' | '’' | '‚' | '‛' | '`' | '´' | '"' | '“' | '”' | '„' | '«' | '»' => {
258            "'"
259        }
260        '–' | '—' | '‐' | '‑' | '−' | '_' => "-",
261        _ => ".",
262    }
263}
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268
269    #[test]
270    fn iban_valid() {
271        // Synthetic and published example IBANs (ISO 13616 examples).
272        for (input, want) in [
273            ("DE89370400440532013000", "DE89370400440532013000"),
274            ("de89 3704 0044 0532 0130 00", "DE89370400440532013000"),
275            ("  DE02 1203 0000 0000 2020 51 ", "DE02120300000000202051"),
276            ("NO9386011117947", "NO9386011117947"),
277            ("GB29NWBK60161331926819", "GB29NWBK60161331926819"),
278            ("FR1420041010050500013M02606", "FR1420041010050500013M02606"),
279            (
280                "LC55HEMM000100010012001200023015",
281                "LC55HEMM000100010012001200023015",
282            ),
283        ] {
284            assert_eq!(Iban::parse(input).unwrap().as_str(), want, "{input}");
285        }
286    }
287
288    #[test]
289    fn iban_invalid() {
290        for (input, why) in [
291            ("", Invalid::Empty),
292            ("   ", Invalid::Empty),
293            ("DE88370400440532013000", Invalid::Checksum),
294            ("DE89370400440532013001", Invalid::Checksum),
295            ("DE8937040044", Invalid::Length),
296            (
297                "DE89-3704-0044-0532-0130-00",
298                Invalid::Character { ch: '-' },
299            ),
300            ("8989370400440532013000", Invalid::Country),
301            ("DEXX370400440532013000", Invalid::Country),
302            ("DE893704004405320130000000000000000", Invalid::Length),
303        ] {
304            assert_eq!(Iban::parse(input), Err(why), "{input}");
305        }
306    }
307
308    #[test]
309    fn bic() {
310        assert_eq!(Bic::parse("COBADEFF").unwrap().as_str(), "COBADEFF");
311        assert_eq!(Bic::parse("cobadeffxxx").unwrap().as_str(), "COBADEFFXXX");
312        assert_eq!(Bic::parse("BYLA DEM1 001").unwrap().as_str(), "BYLADEM1001");
313        // Digits allowed in the first four places (BICFIDec2014Identifier).
314        assert!(Bic::parse("1234DEFF").is_ok());
315        assert_eq!(Bic::parse(""), Err(Invalid::Empty));
316        assert_eq!(Bic::parse("COBADEF"), Err(Invalid::Length));
317        assert_eq!(Bic::parse("COBADEFFXX"), Err(Invalid::Length));
318        assert_eq!(Bic::parse("COBA1EFF"), Err(Invalid::Format));
319        assert_eq!(Bic::parse("COBADEF-"), Err(Invalid::Format));
320    }
321
322    #[test]
323    fn sepa_text() {
324        assert!(is_sepa_text("Max Mustermann"));
325        assert!(is_sepa_text("Rechnung 2026/11, Kunde: 42 (Rest) +1.00 ?'-"));
326        // Anlage 3 2.1, second table.
327        assert!(is_sepa_text("Müller & Söhne GmbH, Straße, ÄÖÜ äöü ß * $ %"));
328        assert!(is_sepa_text(""));
329        for bad in [
330            "Café", "a_b", "x@y", "#1", "Zoë", "€", "a\tb", "a\nb", "<b>", "\"q\"",
331        ] {
332            assert!(!is_sepa_text(bad), "{bad}");
333        }
334        assert_eq!(first_invalid_char("Café"), Some('é'));
335    }
336
337    #[test]
338    fn sepa_reference() {
339        assert!(is_sepa_reference("NOTPROVIDED"));
340        assert!(is_sepa_reference("RE 2026-11/42 (a) +b?c:d.e,f'g"));
341        assert!(is_sepa_reference(&"A".repeat(35)));
342        assert_eq!(check_reference(""), Err(Invalid::Empty));
343        assert_eq!(
344            check_reference(&"A".repeat(36)),
345            Err(Invalid::TooLong { max: 35 })
346        );
347        assert_eq!(check_reference("/A"), Err(Invalid::Slash));
348        assert_eq!(check_reference("A/"), Err(Invalid::Slash));
349        assert_eq!(check_reference("A//B"), Err(Invalid::Slash));
350        // The extended characters are allowed in text, not in references.
351        assert_eq!(
352            check_reference("Müller"),
353            Err(Invalid::Character { ch: 'ü' })
354        );
355        assert_eq!(check_reference("A&B"), Err(Invalid::Character { ch: '&' }));
356    }
357
358    #[test]
359    fn transliterate_cleans() {
360        assert_eq!(transliterate("Café Zoë Ørsted"), "Cafe Zoe Orsted");
361        assert_eq!(transliterate("Müller & Söhne"), "Müller & Söhne");
362        assert_eq!(transliterate("Œuvre „quoted“ – x"), "OEuvre 'quoted' - x");
363        assert_eq!(transliterate("a\tb\nc"), "a b c");
364        assert_eq!(transliterate("x@y #1 €5"), "x.y .1 .5");
365        for s in ["Ångström Łódź Ærø", "日本", "a_b@c"] {
366            assert!(is_sepa_text(&transliterate(s)), "{s}");
367        }
368    }
369}