sepa 0.8.0

SEPA payment utilities for all five EPC payment schemes: SCT, SCT Inst, SDD Core, SDD B2B and One-Leg Out Instant (OCT Inst). Builds pain.001, pain.008, pain.007 and camt.055; parses pain.002 (incl. Verification of Payee), camt.029 and camt.052/053/054. IBAN, BIC, Creditor Identifier and ISO 11649 RF reference validation, structured addresses, EPC field rules and charset transliteration. Output is XSD-validated in CI against the ISO schemas and the German GBIC 5 subsets. No I/O, no async, no f64 in monetary arithmetic.
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//! Postal addresses — ISO 20022 `PstlAdr`.
//!
//! A payer's or payee's address is optional in the SEPA schemes, and most
//! domestic batches never carry one. It becomes unavoidable when a bank asks
//! for it: sanction screening, payments touching a non-EEA party, and any
//! channel that has already moved to the 2025 rulebooks.
//!
//! ## Structured, hybrid, unstructured
//!
//! ISO 20022 lets an address be written three ways, and the EPC is retiring
//! one of them:
//!
//! | Form | Shape | Status |
//! |---|---|---|
//! | **Structured** | dedicated elements only — `StrtNm`, `BldgNb`, `PstCd`, `TwnNm`, `Ctry` | preferred |
//! | **Hybrid** | `TwnNm` + `Ctry` plus up to two free-text `AdrLine`s | permitted |
//! | **Unstructured** | `AdrLine` only, nothing parsable | being retired — no end-date currently in force |
//!
//! ## Which form to send
//!
//! Send structured, or hybrid where you must. Both are accepted today and stay
//! accepted: the EPC is retiring only the free-text-only form, and **no
//! end-date is currently in force** — 22 November 2026 was moved to 15 November
//! 2026, and that was withdrawn on 9 September 2026 with a replacement due.
//! Migrate anyway; the direction of travel has never changed.
//!
//! What binds regardless of the date: an address is optional, but `TwnNm` and
//! `Ctry` are mandatory *whenever one is present*. That is what
//! [`PostalAddress::new`] takes.
//!
//! If all you have is free-text lines, you have no address to build here —
//! **omit it**, which every SEPA schema permits. Do not invent a town to get
//! past the constructor: it travels to the bank as though the counterparty had
//! supplied it.
//!
//! This type therefore **cannot represent an unstructured address**: [`new`]
//! takes the town and the country, so the only reachable forms are the two that
//! are durably accepted. That is the same treatment [`Iban`](crate::Iban) and
//! [`IsoDate`](crate::IsoDate) get — the invalid state is unconstructible
//! rather than caught late.
//!
//! [`new`]: PostalAddress::new
//!
//! ## Which elements
//!
//! ISO 20022 grew the type over time: `pain.001.001.03` and `pain.008.001.02`
//! use `PostalAddress6`, while `pain.001.001.09` and `pain.008.001.08` use
//! `PostalAddress24`, which adds `BldgNm`, `Flr`, `PstBx`, `Room`, `TwnLctnNm`
//! and `DstrctNm`. Only the elements common to both are exposed here, so one
//! address value is valid against every schema this crate emits — and those
//! extras are outside the EPC's own address guidance anyway.
//!
//! The legacy Deutsche Kreditwirtschaft schemas are the exception: their
//! `PostalAddressSEPA` type holds nothing but `Ctry` and two address lines, so
//! a structured address is unrepresentable there and the builders reject it
//! with [`ValidationError::UnsupportedBySchema`].
//!
//! ## Examples
//!
//! ```
//! use sepa::address::{AddressFormat, PostalAddress};
//!
//! // Structured — the form to aim for.
//! let structured = PostalAddress::new("Berlin", "DE")?
//!     .street("Unter den Linden")
//!     .building_number("77")
//!     .post_code("10117");
//! assert_eq!(structured.format(), AddressFormat::Structured);
//!
//! // Hybrid — the leftovers stay in an address line.
//! let hybrid = PostalAddress::new("Berlin", "DE")?.line("Unter den Linden 77");
//! assert_eq!(hybrid.format(), AddressFormat::Hybrid);
//!
//! // A country that is not a country is refused at construction.
//! assert!(PostalAddress::new("Atlantis", "ZZ").is_err());
//! # Ok::<(), sepa::address::AddressError>(())
//! ```

use crate::country::is_country_code;
use crate::validate::{CharsetPolicy, ValidationError, check_text, max_text_len};
use crate::xml_util::write_escaped;

// ── limits ────────────────────────────────────────────────────────────────────

/// Every text-bearing `PstlAdr` element this crate emits, with its ISO 20022
/// path.
///
/// One list, used by the validator and by the test that requires
/// [`max_text_len`] to bound every one of them. Adding an element to the writer
/// without adding it here leaves its text unchecked on the wire.
const ADDRESS_ELEMENTS: [(&str, &str); 8] = [
    ("Dept", "PstlAdr/Dept"),
    ("SubDept", "PstlAdr/SubDept"),
    ("StrtNm", "PstlAdr/StrtNm"),
    ("BldgNb", "PstlAdr/BldgNb"),
    ("PstCd", "PstlAdr/PstCd"),
    ("TwnNm", "PstlAdr/TwnNm"),
    ("CtrySubDvsn", "PstlAdr/CtrySubDvsn"),
    ("AdrLine", "PstlAdr/AdrLine"),
];

/// The ISO 20022 path for a `PstlAdr` element name.
fn address_field(element: &str) -> &'static str {
    ADDRESS_ELEMENTS
        .iter()
        .find(|(name, _)| *name == element)
        .map_or("PstlAdr/AdrLine", |(_, path)| *path)
}

/// Maximum number of `AdrLine` elements the EPC permits.
///
/// The XSD allows seven; the EPC address guidance allows two, and a hybrid
/// address is defined in terms of that pair.
pub const MAX_ADDRESS_LINES: usize = 2;

// ── error ─────────────────────────────────────────────────────────────────────

/// Error returned when a postal address cannot be constructed.
///
/// Only the two facts that make an address structurally impossible live here.
/// Length and character-set violations are [`ValidationError`]s raised by
/// `build()`, alongside every other field rule, because transliteration can
/// change a length after the value was supplied.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum AddressError {
    /// The town name was empty or blank.
    ///
    /// `TwnNm` is mandatory whenever an address is present — see the
    /// [module docs](self).
    #[error("PstlAdr/TwnNm must not be empty")]
    EmptyTown,

    /// The country code is not an ISO 3166-1 alpha-2 country.
    #[error("PstlAdr/Ctry {code:?} is not an ISO 3166-1 alpha-2 country")]
    UnknownCountry {
        /// The two-letter code that was rejected.
        code: String,
    },
}

// ── AddressFormat ─────────────────────────────────────────────────────────────

/// Which of the ISO 20022 address forms an address is written in.
///
/// There is deliberately no `Unstructured` variant: [`PostalAddress`] requires
/// a town and a country, so the free-text-only form the EPC is retiring is not
/// constructible. See the [module docs](self).
///
/// This set is closed on purpose — a `match` over it needs no wildcard arm.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AddressFormat {
    /// Dedicated elements only — no `AdrLine`.
    Structured,
    /// Dedicated elements plus one or two free-text `AdrLine`s.
    Hybrid,
}

// ── PostalAddress ─────────────────────────────────────────────────────────────

/// An ISO 20022 `PstlAdr`, in structured or hybrid form.
///
/// Build one with [`PostalAddress::new`] and chain the optional elements. Only
/// the elements common to `PostalAddress6` and `PostalAddress24` are exposed,
/// so the same value is valid against every ISO schema this crate emits.
///
/// # Examples
///
/// ```
/// use sepa::PostalAddress;
///
/// let address = PostalAddress::new("Berlin", "DE")?
///     .street("Unter den Linden")
///     .building_number("77")
///     .post_code("10117");
///
/// assert_eq!(address.town_name(), "Berlin");
/// assert_eq!(address.country(), "DE");
/// # Ok::<(), sepa::address::AddressError>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PostalAddress {
    department: Option<String>,
    sub_department: Option<String>,
    street: Option<String>,
    building_number: Option<String>,
    post_code: Option<String>,
    town_name: String,
    country_subdivision: Option<String>,
    country: String,
    lines: Vec<String>,
}

impl PostalAddress {
    /// An address in `town`, in `country`.
    ///
    /// Both are required. `TwnNm` and `Ctry` are mandatory whenever a SEPA
    /// address is present at all, so an address carrying neither is not a form
    /// this crate will emit — see the [module docs](self). `country` is an
    /// ISO 3166-1 alpha-2 code and is upper-cased.
    ///
    /// # Errors
    ///
    /// [`AddressError::EmptyTown`] for a blank town, or
    /// [`AddressError::UnknownCountry`] when `country` is not a country — the
    /// XSD's `CountryCode` type accepts any two letters, and `ZZ` addresses
    /// nowhere.
    ///
    /// # Examples
    ///
    /// ```
    /// use sepa::PostalAddress;
    ///
    /// assert_eq!(PostalAddress::new("Wien", "at")?.country(), "AT");
    /// assert!(PostalAddress::new("", "DE").is_err());
    /// assert!(PostalAddress::new("Atlantis", "ZZ").is_err());
    /// # Ok::<(), sepa::address::AddressError>(())
    /// ```
    pub fn new(town: impl Into<String>, country: &str) -> Result<Self, AddressError> {
        let town_name = town.into();
        if town_name.trim().is_empty() {
            return Err(AddressError::EmptyTown);
        }
        if !is_country_code(country) {
            return Err(AddressError::UnknownCountry {
                code: country.to_owned(),
            });
        }
        Ok(Self {
            department: None,
            sub_department: None,
            street: None,
            building_number: None,
            post_code: None,
            town_name,
            country_subdivision: None,
            country: country.to_ascii_uppercase(),
            lines: Vec::new(),
        })
    }

    /// Set `StrtNm` — the street name, without the number.
    #[must_use]
    pub fn street(mut self, street: impl Into<String>) -> Self {
        self.street = Some(street.into());
        self
    }

    /// Set `BldgNb` — the building number, without the street.
    #[must_use]
    pub fn building_number(mut self, number: impl Into<String>) -> Self {
        self.building_number = Some(number.into());
        self
    }

    /// Set `PstCd` — the postal code.
    #[must_use]
    pub fn post_code(mut self, code: impl Into<String>) -> Self {
        self.post_code = Some(code.into());
        self
    }

    /// Set `CtrySubDvsn` — state, province or canton.
    #[must_use]
    pub fn country_subdivision(mut self, subdivision: impl Into<String>) -> Self {
        self.country_subdivision = Some(subdivision.into());
        self
    }

    /// Set `Dept` — the department within the organisation.
    #[must_use]
    pub fn department(mut self, department: impl Into<String>) -> Self {
        self.department = Some(department.into());
        self
    }

    /// Set `SubDept` — the sub-department within the department.
    #[must_use]
    pub fn sub_department(mut self, sub_department: impl Into<String>) -> Self {
        self.sub_department = Some(sub_department.into());
        self
    }

    /// Append an `AdrLine`, making the address hybrid.
    ///
    /// Use this only for what the structured elements cannot hold. At most
    /// [`MAX_ADDRESS_LINES`] are permitted; a third is rejected by `build()`
    /// rather than silently dropped.
    #[must_use]
    pub fn line(mut self, line: impl Into<String>) -> Self {
        self.lines.push(line.into());
        self
    }

    /// The town name (`TwnNm`).
    #[must_use]
    pub fn town_name(&self) -> &str {
        &self.town_name
    }

    /// The ISO 3166-1 alpha-2 country code (`Ctry`), upper-cased.
    #[must_use]
    pub fn country(&self) -> &str {
        &self.country
    }

    /// The street name (`StrtNm`), if set.
    #[must_use]
    pub fn street_name(&self) -> Option<&str> {
        self.street.as_deref()
    }

    /// The free-text address lines (`AdrLine`), in order.
    #[must_use]
    pub fn lines(&self) -> &[String] {
        &self.lines
    }

    /// Whether this address is written structured or hybrid.
    ///
    /// # Examples
    ///
    /// ```
    /// use sepa::address::{AddressFormat, PostalAddress};
    ///
    /// let a = PostalAddress::new("Berlin", "DE")?.street("Hauptstrasse");
    /// assert_eq!(a.format(), AddressFormat::Structured);
    /// assert_eq!(a.line("2. OG").format(), AddressFormat::Hybrid);
    /// # Ok::<(), sepa::address::AddressError>(())
    /// ```
    #[must_use]
    pub fn format(&self) -> AddressFormat {
        if self.lines.is_empty() {
            AddressFormat::Structured
        } else {
            AddressFormat::Hybrid
        }
    }

    /// Validate against the ISO 20022 length limits and the EPC line cap.
    ///
    /// Field paths in the returned error are relative to the address
    /// (`PstlAdr/StrtNm`); the [`Location`](crate::Location) on the enclosing
    /// [`BuildError`](crate::BuildError) says which group or transaction — and
    /// hence which party — it belongs to.
    ///
    /// # Errors
    ///
    /// [`ValidationError::TooLong`] for an element over its `Max*Text` bound,
    /// [`ValidationError::Empty`] for a blank one, or
    /// [`ValidationError::InvalidCharacter`] under
    /// [`CharsetPolicy::Strict`].
    pub fn validate(&self, charset: CharsetPolicy) -> Result<(), ValidationError> {
        // Lengths are checked after transliteration, since `Straße` grows a
        // character on its way to `Strasse`, and the bound comes from
        // `max_text_len` rather than from a constant repeated here — one table,
        // so a limit cannot be right in the validator and wrong in the docs.
        let check = |element: &'static str, value: &str| -> Result<(), ValidationError> {
            let field = address_field(element);
            // The bound comes from `validate::max_text_len` and from nowhere
            // else: a limit written at the call site is a limit the next call
            // site forgets. `ADDRESS_ELEMENTS` and the test below make the
            // lookup total for every element this writer emits, so the `0`
            // fallback is unreachable and fails loudly rather than inventing a
            // plausible 70 if it ever stops being.
            let max = max_text_len(Some("PstlAdr"), element).unwrap_or(0);
            check_text(field, &charset.apply(field, value)?, max)
        };

        check("TwnNm", &self.town_name)?;
        for (element, value) in [
            ("Dept", &self.department),
            ("SubDept", &self.sub_department),
            ("StrtNm", &self.street),
            ("BldgNb", &self.building_number),
            ("PstCd", &self.post_code),
            ("CtrySubDvsn", &self.country_subdivision),
        ] {
            if let Some(value) = value {
                check(element, value)?;
            }
        }

        if self.lines.len() > MAX_ADDRESS_LINES {
            return Err(ValidationError::TooMany {
                field: "PstlAdr/AdrLine",
                max: MAX_ADDRESS_LINES,
                actual: self.lines.len(),
            });
        }
        for line in &self.lines {
            check("AdrLine", line)?;
        }
        Ok(())
    }

    /// Write `<PstlAdr>…</PstlAdr>` in XSD sequence order, unindented.
    ///
    /// The order is the one `PostalAddress6` and `PostalAddress24` share, so a
    /// single writer serves every ISO schema this crate emits.
    pub(crate) fn write_xml<W: std::fmt::Write>(
        &self,
        w: &mut W,
        charset: CharsetPolicy,
    ) -> std::fmt::Result {
        fn element<W: std::fmt::Write>(
            w: &mut W,
            tag: &'static str,
            value: &str,
            charset: CharsetPolicy,
        ) -> std::fmt::Result {
            write!(w, "<{tag}>")?;
            write_escaped(w, &charset.render(value))?;
            write!(w, "</{tag}>")
        }

        w.write_str("<PstlAdr>")?;
        for (tag, value) in [
            ("Dept", &self.department),
            ("SubDept", &self.sub_department),
            ("StrtNm", &self.street),
            ("BldgNb", &self.building_number),
            ("PstCd", &self.post_code),
        ] {
            if let Some(value) = value {
                element(w, tag, value, charset)?;
            }
        }
        element(w, "TwnNm", &self.town_name, charset)?;
        if let Some(subdivision) = &self.country_subdivision {
            element(w, "CtrySubDvsn", subdivision, charset)?;
        }
        // `Ctry` is validated at construction and is two ASCII letters, so it
        // needs neither escaping nor transliteration.
        write!(w, "<Ctry>{}</Ctry>", self.country)?;
        for line in &self.lines {
            element(w, "AdrLine", line, charset)?;
        }
        w.write_str("</PstlAdr>")
    }
}

// ── tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    #[test]
    fn every_address_element_this_crate_emits_has_a_bound() {
        // The length table must explain every element this writer emits, so an
        // element cannot gain a writer and silently
        // inherit a plausible-looking default.
        for (element, field) in super::ADDRESS_ELEMENTS {
            assert!(
                crate::validate::max_text_len(Some("PstlAdr"), element).is_some(),
                "{field}: no bound in validate::max_text_len"
            );
            assert_eq!(super::address_field(element), field);
        }
    }

    use super::{AddressError, AddressFormat, PostalAddress};
    use crate::validate::{CharsetPolicy, ValidationError};

    fn render(a: &PostalAddress) -> String {
        let mut out = String::new();
        a.write_xml(&mut out, CharsetPolicy::default()).unwrap();
        out
    }

    #[test]
    fn a_town_and_a_country_are_required_at_construction() {
        // The Nov 2026 rule, expressed as a type: an unstructured address is
        // not something this crate can be asked to emit.
        assert_eq!(PostalAddress::new("", "DE"), Err(AddressError::EmptyTown));
        assert_eq!(
            PostalAddress::new("   ", "DE"),
            Err(AddressError::EmptyTown)
        );
        assert_eq!(
            PostalAddress::new("Atlantis", "ZZ"),
            Err(AddressError::UnknownCountry {
                code: "ZZ".to_owned()
            })
        );
        // The XSD pattern is `[A-Z]{2}` and would accept both of these.
        assert!(PostalAddress::new("Nowhere", "QQ").is_err());
        assert!(PostalAddress::new("Berlin", "DEU").is_err());
    }

    #[test]
    fn the_country_code_is_normalised() {
        assert_eq!(PostalAddress::new("Wien", "at").unwrap().country(), "AT");
    }

    #[test]
    fn format_reports_structured_versus_hybrid() {
        let structured = PostalAddress::new("Berlin", "DE")
            .unwrap()
            .street("Unter den Linden")
            .building_number("77")
            .post_code("10117");
        assert_eq!(structured.format(), AddressFormat::Structured);
        assert_eq!(
            structured.clone().line("2. OG").format(),
            AddressFormat::Hybrid
        );
    }

    #[test]
    fn elements_are_written_in_xsd_sequence_order() {
        // PostalAddress6 and PostalAddress24 agree on this order, which is why
        // one writer covers every ISO schema.
        let xml = render(
            &PostalAddress::new("Berlin", "DE")
                .unwrap()
                .department("Buchhaltung")
                .sub_department("Kreditoren")
                .street("Unter den Linden")
                .building_number("77")
                .post_code("10117")
                .country_subdivision("BE")
                .line("Aufgang C"),
        );
        assert_eq!(
            xml,
            "<PstlAdr><Dept>Buchhaltung</Dept><SubDept>Kreditoren</SubDept>\
             <StrtNm>Unter den Linden</StrtNm><BldgNb>77</BldgNb><PstCd>10117</PstCd>\
             <TwnNm>Berlin</TwnNm><CtrySubDvsn>BE</CtrySubDvsn><Ctry>DE</Ctry>\
             <AdrLine>Aufgang C</AdrLine></PstlAdr>"
        );
    }

    #[test]
    fn the_minimal_address_is_town_and_country() {
        assert_eq!(
            render(&PostalAddress::new("Berlin", "DE").unwrap()),
            "<PstlAdr><TwnNm>Berlin</TwnNm><Ctry>DE</Ctry></PstlAdr>"
        );
    }

    #[test]
    fn text_is_transliterated_and_escaped() {
        let xml = render(
            &PostalAddress::new("München", "DE")
                .unwrap()
                .street("Straße & Weg"),
        );
        assert!(xml.contains("<StrtNm>Strasse + Weg</StrtNm>"));
        assert!(xml.contains("<TwnNm>Muenchen</TwnNm>"));
    }

    #[test]
    fn lengths_are_the_iso_maximums_and_are_measured_after_transliteration() {
        let policy = CharsetPolicy::default();
        let at = |a: PostalAddress| a.validate(policy);

        assert!(at(PostalAddress::new("A".repeat(35), "DE").unwrap()).is_ok());
        assert!(matches!(
            at(PostalAddress::new("A".repeat(36), "DE").unwrap()),
            Err(ValidationError::TooLong {
                field: "PstlAdr/TwnNm",
                max: 35,
                ..
            })
        ));
        assert!(matches!(
            at(PostalAddress::new("Berlin", "DE")
                .unwrap()
                .street("A".repeat(71))),
            Err(ValidationError::TooLong {
                field: "PstlAdr/StrtNm",
                max: 70,
                ..
            })
        ));
        assert!(matches!(
            at(PostalAddress::new("Berlin", "DE")
                .unwrap()
                .building_number("7".repeat(17))),
            Err(ValidationError::TooLong {
                field: "PstlAdr/BldgNb",
                max: 16,
                ..
            })
        ));

        // 35 'ü' is 35 characters but 70 in the German style — the limit binds
        // on the transliterated value, which is what the bank receives.
        assert!(matches!(
            at(PostalAddress::new("ü".repeat(35), "DE").unwrap()),
            Err(ValidationError::TooLong {
                max: 35,
                actual: 70,
                ..
            })
        ));
        assert!(at(PostalAddress::new("ü".repeat(17), "DE").unwrap()).is_ok());
    }

    #[test]
    fn a_third_address_line_is_rejected_rather_than_dropped() {
        let policy = CharsetPolicy::default();
        let two = PostalAddress::new("Berlin", "DE")
            .unwrap()
            .line("one")
            .line("two");
        assert!(two.validate(policy).is_ok());
        assert_eq!(
            two.line("three").validate(policy),
            Err(ValidationError::TooMany {
                field: "PstlAdr/AdrLine",
                max: 2,
                actual: 3,
            })
        );
    }

    #[test]
    fn a_blank_element_is_rejected() {
        assert!(matches!(
            PostalAddress::new("Berlin", "DE")
                .unwrap()
                .street("   ")
                .validate(CharsetPolicy::default()),
            Err(ValidationError::Empty {
                field: "PstlAdr/StrtNm"
            })
        ));
    }

    #[test]
    fn strict_charset_policy_rejects_rather_than_rewrites() {
        assert!(matches!(
            PostalAddress::new("München", "DE")
                .unwrap()
                .validate(CharsetPolicy::Strict),
            Err(ValidationError::InvalidCharacter {
                field: "PstlAdr/TwnNm",
                ch: 'ü'
            })
        ));
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_round_trips() {
        let a = PostalAddress::new("Berlin", "DE")
            .unwrap()
            .street("Unter den Linden")
            .line("Aufgang C");
        let json = serde_json::to_string(&a).unwrap();
        assert_eq!(serde_json::from_str::<PostalAddress>(&json).unwrap(), a);
    }
}