sepa 0.5.0

SEPA payment utilities: IBAN validation (ISO 13616 + 89-country registry), BIC validation (ISO 9362), SEPA Creditor Identifier (EPC AT-02), pain.001 SCT + SCT Inst XML builder (pain.001.001.09 / .001.03 / .003.03), pain.008 SDD CORE + B2B XML builder (pain.008.001.08 / .001.02 / .003.02), pain.002 status report parser, camt.052/053/054 parsers, ISO 11649 RF creditor references, EPC field validation and SEPA charset transliteration. Output is XSD-validated in CI. Typed ISO 8601 dates. Zero 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
//! EPC field-level rules for outgoing pain.001 / pain.008 messages.
//!
//! Almost none of these constraints live in the XSD. The published ISO schemas
//! allow amounts of `0`, five decimal places, any ISO 4217 currency, 140-character
//! names and arbitrary Unicode — so a file can validate cleanly against the
//! schema and still be rejected by the bank on ingestion. The rules here come
//! from the EPC Implementation Guidelines and the DK DFÜ-Abkommen, and they are
//! what actually determines whether a batch is accepted.
//!
//! | Field | Rule | Source |
//! |---|---|---|
//! | `MsgId`, `PmtInfId`, `EndToEndId`, `MndtId` | 1–35 chars, no leading/trailing `/`, no `//` | `Max35Text`, EPC230-15 |
//! | `Nm` (any party) | 1–70 chars (XSD permits 140) | EPC IG |
//! | `Ustrd` | 1–140 chars, one occurrence | EPC IG |
//! | `InstdAmt` | 0.01 – 999,999,999.99 EUR, 2 decimals | EPC IG §2.95 |
//! | Batch | at least one transaction | `CdtTrfTxInf`/`DrctDbtTxInf` are `1..n` |
//!
//! Dates are absent from that table on purpose: they are [`IsoDate`] values,
//! validated where they are constructed, so a malformed `ReqdColltnDt` cannot
//! reach a builder in the first place.
//!
//! [`IsoDate`]: crate::IsoDate
//!
//! The amount ceiling is uniform across SCT, SCT Inst, SDD Core and SDD B2B.
//! The old 100,000 EUR SCT Inst cap was removed from the scheme on
//! 5 October 2025 (2025 SCT Inst Rulebook, following Art 5a(6) of the amended
//! SEPA Regulation), so it is deliberately not enforced here — a lower ceiling
//! is now a PSP or user policy limit, not a scheme rule.

use crate::charset::{Transliteration, first_invalid_char, transliterate};

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

/// Maximum length of an ISO 20022 `Max35Text` identifier.
pub const MAX_ID_LEN: usize = 35;
/// Maximum length of a party name (`Nm`) under the EPC guidelines.
pub const MAX_NAME_LEN: usize = 70;
/// Maximum length of unstructured remittance information (`Ustrd`).
pub const MAX_REMITTANCE_LEN: usize = 140;
/// Smallest permitted amount: 0.01 EUR.
pub const MIN_AMOUNT_CT: i64 = 1;
/// Largest permitted amount: 999,999,999.99 EUR.
pub const MAX_AMOUNT_CT: i64 = 99_999_999_999;

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

/// A field-level violation of the EPC rules for a payment batch.
///
/// Every variant names the offending `field` using its ISO 20022 element path,
/// so the message points at the exact element a bank would reject.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ValidationError {
    /// The batch contains no transactions.
    ///
    /// `CdtTrfTxInf` and `DrctDbtTxInf` are both `1..n`, so an empty batch is
    /// not merely useless — it is schema-invalid.
    #[error("batch contains no transactions: at least one is required")]
    EmptyBatch,

    /// A mandatory field was empty or blank.
    #[error("{field} must not be empty")]
    Empty {
        /// ISO 20022 element path of the offending field.
        field: &'static str,
    },

    /// A field exceeded its maximum length.
    #[error("{field} is {actual} characters, exceeding the maximum of {max}")]
    TooLong {
        /// ISO 20022 element path of the offending field.
        field: &'static str,
        /// Maximum permitted length in characters.
        max: usize,
        /// Actual length in characters.
        actual: usize,
    },

    /// A field contained a character outside the SEPA Basic Latin set.
    ///
    /// Only produced under [`CharsetPolicy::Strict`]; the default policy
    /// transliterates instead.
    #[error("{field} contains {ch:?}, which is not in the SEPA character set")]
    InvalidCharacter {
        /// ISO 20022 element path of the offending field.
        field: &'static str,
        /// The first offending character.
        ch: char,
    },

    /// An identifier began or ended with `/`, or contained `//`.
    #[error("{field} must not start or end with '/' nor contain '//' (EPC230-15)")]
    SlashRule {
        /// ISO 20022 element path of the offending field.
        field: &'static str,
    },

    /// An amount fell outside 0.01 – 999,999,999.99 EUR.
    #[error("{field} is {amount_ct} ct, outside the permitted 1 – {MAX_AMOUNT_CT} ct")]
    AmountOutOfRange {
        /// ISO 20022 element path of the offending field.
        field: &'static str,
        /// The rejected amount in cents.
        amount_ct: i64,
    },

    /// The sum of a batch's amounts overflowed `i64`.
    #[error("batch control sum overflows i64")]
    ControlSumOverflow,

    /// The same element was set at both payment-information and transaction
    /// level, where the rules permit one or the other.
    #[error("{field} must be set at either payment-information or transaction level, not both")]
    ConflictingLevels {
        /// The ISO 20022 element name.
        field: &'static str,
    },

    /// The selected schema version cannot carry a requested feature.
    ///
    /// The older schemas are not merely renamed: `pain.001.003.03` has no
    /// `LclInstrm` element at all, so an SCT Instant batch built against it
    /// would be schema-invalid rather than merely unusual.
    #[error("{feature} is not available in {schema}")]
    UnsupportedBySchema {
        /// What the batch asked for, named as its ISO 20022 element.
        feature: &'static str,
        /// The message identifier of the selected schema, e.g. `pain.001.003.03`.
        schema: &'static str,
    },
}

/// Error returned when a schema version cannot be parsed from a string.
///
/// Produced by `CreditTransferSchema::from_str` and
/// `DirectDebitSchema::from_str`, which is how a bank-specific target version
/// gets read out of a configuration file.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("unknown schema {value:?}: expected one of {supported}")]
pub struct UnknownSchema {
    /// The unrecognised text.
    pub value: String,
    /// The message identifiers this builder can emit.
    pub supported: &'static str,
}

// ── location ──────────────────────────────────────────────────────────────────

/// Where in a message a validation error occurred.
///
/// A collection run is thousands of transactions long, so "`Dbtr/Nm` is too
/// long" only becomes actionable once it says *which* one. Both indices are
/// zero-based and refer to the order the groups and entries were added.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Location {
    /// Index of the `PmtInf` group, or `None` for a message-level error.
    pub group: Option<usize>,
    /// Index of the transaction within that group, or `None` for a group-level
    /// error.
    pub transaction: Option<usize>,
}

impl Location {
    /// A message-level location — neither group nor transaction.
    #[must_use]
    pub const fn message() -> Self {
        Self {
            group: None,
            transaction: None,
        }
    }

    /// A group-level location.
    #[must_use]
    pub const fn group(index: usize) -> Self {
        Self {
            group: Some(index),
            transaction: None,
        }
    }

    /// A transaction-level location.
    #[must_use]
    pub const fn transaction(group: usize, transaction: usize) -> Self {
        Self {
            group: Some(group),
            transaction: Some(transaction),
        }
    }
}

impl std::fmt::Display for Location {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match (self.group, self.transaction) {
            (None, _) => f.write_str("message"),
            (Some(g), None) => write!(f, "PmtInf[{g}]"),
            (Some(g), Some(t)) => write!(f, "PmtInf[{g}]/Tx[{t}]"),
        }
    }
}

// ── build error ───────────────────────────────────────────────────────────────

/// A validation failure, with the position in the message that caused it.
///
/// Returned by `Pain001Builder::build` and `Pain008Builder::build`. Match on
/// [`kind`](Self::kind) to react to the rule that was broken and read
/// [`location`](Self::location) to tell the operator which transaction to fix.
///
/// # Examples
///
/// ```
/// use sepa::{
///     DirectDebitEntry, DirectDebitGroup, IsoDate, Pain008Builder, ValidationError,
///     validate_creditor_id, validate_iban,
/// };
///
/// let iban = validate_iban("DE89370400440532013000")?;
/// let ci = validate_creditor_id("DE98ZZZ09999999999")?;
/// let date = IsoDate::new(2026, 7, 20)?;
///
/// let err = Pain008Builder::new("Stadtwerke GmbH")
///     .msg_id("DD-1")
///     .add_group(
///         DirectDebitGroup::new("Stadtwerke GmbH", &iban, &ci)
///             .collection_date(date)
///             .add_entry(DirectDebitEntry::new(
///                 "MND-1", date, "Erste Kundin", iban.clone(), 100, "E2E-1",
///             ))
///             // The second collection has a zero amount.
///             .add_entry(DirectDebitEntry::new(
///                 "MND-2", date, "Zweiter Kunde", iban.clone(), 0, "E2E-2",
///             )),
///     )
///     .build()
///     .unwrap_err();
///
/// assert_eq!(err.location.group, Some(0));
/// assert_eq!(err.location.transaction, Some(1));
/// assert!(matches!(err.kind, ValidationError::AmountOutOfRange { .. }));
/// assert_eq!(
///     err.to_string(),
///     "PmtInf[0]/Tx[1]: DrctDbtTxInf/InstdAmt is 0 ct, outside the permitted 1 \u{2013} 99999999999 ct",
/// );
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{location}: {kind}")]
pub struct BuildError {
    /// Which group and transaction the failure belongs to.
    pub location: Location,
    /// The rule that was broken.
    #[source]
    pub kind: ValidationError,
}

impl BuildError {
    /// A message-level failure.
    #[must_use]
    pub const fn message(kind: ValidationError) -> Self {
        Self {
            location: Location::message(),
            kind,
        }
    }

    /// A group-level failure.
    #[must_use]
    pub const fn group(index: usize, kind: ValidationError) -> Self {
        Self {
            location: Location::group(index),
            kind,
        }
    }

    /// A transaction-level failure.
    #[must_use]
    pub const fn transaction(group: usize, transaction: usize, kind: ValidationError) -> Self {
        Self {
            location: Location::transaction(group, transaction),
            kind,
        }
    }
}

/// Attach a [`Location`] to a `Result<_, ValidationError>`.
pub(crate) trait Locate<T> {
    fn at(self, location: Location) -> Result<T, BuildError>;
}

impl<T> Locate<T> for Result<T, ValidationError> {
    fn at(self, location: Location) -> Result<T, BuildError> {
        self.map_err(|kind| BuildError { location, kind })
    }
}

/// Error returned when streaming a batch to an [`io::Write`](std::io::Write) target.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum WriteError {
    /// The batch violates an EPC rule; nothing was written.
    #[error(transparent)]
    Validation(#[from] BuildError),

    /// The underlying writer failed.
    #[error(transparent)]
    Io(#[from] std::io::Error),
}

// ── charset policy ────────────────────────────────────────────────────────────

/// How a builder handles text outside the SEPA Basic Latin character set.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CharsetPolicy {
    /// Convert unsupported characters automatically (default).
    ///
    /// Length limits are checked **after** conversion, since German-style
    /// transliteration can lengthen a string (`Müller` → `Mueller`).
    Transliterate(Transliteration),
    /// Reject unsupported characters with [`ValidationError::InvalidCharacter`].
    ///
    /// Use when the caller has already sanitised its data and wants a hard
    /// guarantee that nothing is silently rewritten.
    Strict,
}

impl CharsetPolicy {
    /// Apply this policy to `text`, returning SEPA-legal output.
    ///
    /// # Errors
    ///
    /// Under [`CharsetPolicy::Strict`], returns [`ValidationError::InvalidCharacter`]
    /// for the first character outside the SEPA set.
    pub fn apply<'a>(
        self,
        field: &'static str,
        text: &'a str,
    ) -> Result<std::borrow::Cow<'a, str>, ValidationError> {
        match self {
            Self::Transliterate(style) => Ok(transliterate(text, style)),
            Self::Strict => match first_invalid_char(text) {
                Some(ch) => Err(ValidationError::InvalidCharacter { field, ch }),
                None => Ok(std::borrow::Cow::Borrowed(text)),
            },
        }
    }
}

impl Default for CharsetPolicy {
    fn default() -> Self {
        Self::Transliterate(Transliteration::German)
    }
}

// ── field checks ──────────────────────────────────────────────────────────────

/// Validate a `Max35Text` identifier: non-empty, ≤35 chars, slash rules.
///
/// # Errors
///
/// See [`ValidationError`].
pub fn check_id(field: &'static str, value: &str) -> Result<(), ValidationError> {
    check_len(field, value, MAX_ID_LEN)?;

    // Identifiers are never transliterated, whatever the CharsetPolicy says: an
    // identifier is a key the bank echoes back in pain.002 and camt.05x, so
    // silently rewriting `MND-Straße` to `MND-Strasse` would break the caller's
    // own reconciliation. Out-of-set characters are a hard error instead.
    if let Some(ch) = first_invalid_char(value) {
        return Err(ValidationError::InvalidCharacter { field, ch });
    }

    // EPC230-15 applies the slash rules to references and identifiers only.
    // Checked on the trimmed value, since XSD whitespace collapse would strip
    // surrounding spaces and expose a leading or trailing slash.
    let trimmed = value.trim();
    if trimmed.starts_with('/') || trimmed.ends_with('/') || trimmed.contains("//") {
        return Err(ValidationError::SlashRule { field });
    }
    Ok(())
}

/// Validate a party name: non-empty, ≤70 characters.
///
/// # Errors
///
/// See [`ValidationError`].
pub fn check_name(field: &'static str, value: &str) -> Result<(), ValidationError> {
    check_len(field, value, MAX_NAME_LEN)
}

/// Validate unstructured remittance information: non-empty, ≤140 characters.
///
/// # Errors
///
/// See [`ValidationError`].
pub fn check_remittance(field: &'static str, value: &str) -> Result<(), ValidationError> {
    check_len(field, value, MAX_REMITTANCE_LEN)
}

/// Non-empty and within `max` **characters** (not bytes).
fn check_len(field: &'static str, value: &str, max: usize) -> Result<(), ValidationError> {
    if value.trim().is_empty() {
        return Err(ValidationError::Empty { field });
    }
    // Counted in chars: the ISO limits are character limits, and a byte-based
    // check would both mis-measure and risk slicing a multi-byte character.
    let actual = value.chars().count();
    if actual > max {
        return Err(ValidationError::TooLong { field, max, actual });
    }
    Ok(())
}

/// Validate an amount in cents against the SEPA range 0.01 – 999,999,999.99.
///
/// # Errors
///
/// Returns [`ValidationError::AmountOutOfRange`] outside that range. Note this
/// rejects zero and all negative amounts.
pub fn check_amount(field: &'static str, amount_ct: i64) -> Result<(), ValidationError> {
    if !(MIN_AMOUNT_CT..=MAX_AMOUNT_CT).contains(&amount_ct) {
        return Err(ValidationError::AmountOutOfRange { field, amount_ct });
    }
    Ok(())
}

/// Truncate `s` to at most `max` **characters**, never splitting one.
///
/// Slicing by byte index (`&s[..140]`) panics whenever the boundary lands
/// inside a multi-byte character — which a German remittance line reaches
/// routinely — and would mis-measure the limit even when it did not panic,
/// since ISO 20022 counts characters.
///
/// Returns `Cow::Borrowed` when no truncation is needed.
#[must_use]
pub fn truncate_chars(s: &str, max: usize) -> std::borrow::Cow<'_, str> {
    match s.char_indices().nth(max) {
        Some((byte_idx, _)) => std::borrow::Cow::Borrowed(&s[..byte_idx]),
        None => std::borrow::Cow::Borrowed(s),
    }
}

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

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

    #[test]
    fn ids_respect_length_and_slash_rules() {
        assert!(check_id("MsgId", "DD-2026-07-001").is_ok());
        assert!(check_id("MsgId", &"X".repeat(35)).is_ok());

        assert_eq!(
            check_id("MsgId", &"X".repeat(36)),
            Err(ValidationError::TooLong {
                field: "MsgId",
                max: 35,
                actual: 36
            })
        );
        assert_eq!(
            check_id("MsgId", ""),
            Err(ValidationError::Empty { field: "MsgId" })
        );
        assert_eq!(
            check_id("MsgId", "   "),
            Err(ValidationError::Empty { field: "MsgId" })
        );
        for bad in ["/leading", "trailing/", "double//slash"] {
            assert_eq!(
                check_id("EndToEndId", bad),
                Err(ValidationError::SlashRule {
                    field: "EndToEndId"
                }),
                "{bad:?} must violate the slash rule"
            );
        }
        // A single interior slash is fine.
        assert!(check_id("EndToEndId", "INV/2026/07").is_ok());
    }

    #[test]
    fn lengths_are_counted_in_characters_not_bytes() {
        // 70 'ä' is 140 bytes but only 70 characters — must be accepted.
        let name = "ä".repeat(70);
        assert_eq!(name.len(), 140);
        assert!(check_name("Nm", &name).is_ok());
        assert!(check_name("Nm", &"ä".repeat(71)).is_err());
    }

    #[test]
    fn name_and_remittance_limits() {
        assert!(check_name("Cdtr/Nm", &"A".repeat(70)).is_ok());
        assert!(check_name("Cdtr/Nm", &"A".repeat(71)).is_err());
        assert!(check_remittance("Ustrd", &"A".repeat(140)).is_ok());
        assert!(check_remittance("Ustrd", &"A".repeat(141)).is_err());
    }

    #[test]
    fn amount_range_matches_the_epc_rule() {
        assert!(check_amount("InstdAmt", 1).is_ok());
        assert!(check_amount("InstdAmt", MAX_AMOUNT_CT).is_ok());

        for bad in [0, -1, MAX_AMOUNT_CT + 1, i64::MIN, i64::MAX] {
            assert_eq!(
                check_amount("InstdAmt", bad),
                Err(ValidationError::AmountOutOfRange {
                    field: "InstdAmt",
                    amount_ct: bad
                }),
                "{bad} must be rejected"
            );
        }
    }

    #[test]
    fn sct_inst_100k_cap_is_not_enforced() {
        // Removed from the scheme on 5 Oct 2025 — 250,000 EUR must be accepted.
        assert!(check_amount("InstdAmt", 25_000_000).is_ok());
    }

    #[test]
    fn identifiers_reject_non_sepa_characters_under_every_policy() {
        // An identifier is a reconciliation key: it must round-trip exactly, so
        // it is never transliterated, even under the default policy.
        for field in ["MsgId", "EndToEndId", "MndtId"] {
            assert_eq!(
                check_id(field, "MND-Straße"),
                Err(ValidationError::InvalidCharacter { field, ch: 'ß' })
            );
        }
        assert!(check_id("MsgId", "MND-Strasse-01").is_ok());
    }

    #[test]
    fn slash_rule_survives_whitespace_padding() {
        // XSD whitespace collapse would strip the padding and expose the slash.
        assert_eq!(
            check_id("MsgId", " /x "),
            Err(ValidationError::SlashRule { field: "MsgId" })
        );
        assert_eq!(
            check_id("MsgId", " x/ "),
            Err(ValidationError::SlashRule { field: "MsgId" })
        );
    }

    #[test]
    fn locations_read_as_element_paths() {
        assert_eq!(Location::message().to_string(), "message");
        assert_eq!(Location::group(0).to_string(), "PmtInf[0]");
        assert_eq!(Location::transaction(1, 42).to_string(), "PmtInf[1]/Tx[42]");
    }

    #[test]
    fn build_errors_carry_both_the_rule_and_the_position() {
        let err = BuildError::transaction(
            2,
            7,
            ValidationError::AmountOutOfRange {
                field: "InstdAmt",
                amount_ct: 0,
            },
        );
        assert_eq!(err.location, Location::transaction(2, 7));
        assert!(err.to_string().starts_with("PmtInf[2]/Tx[7]: "));
        // The rule stays matchable through the wrapper.
        assert!(matches!(err.kind, ValidationError::AmountOutOfRange { .. }));
    }

    #[test]
    fn strict_policy_rejects_non_sepa_characters() {
        let policy = CharsetPolicy::Strict;
        assert_eq!(policy.apply("Nm", "Mueller").unwrap(), "Mueller");
        assert_eq!(
            policy.apply("Nm", "Müller"),
            Err(ValidationError::InvalidCharacter {
                field: "Nm",
                ch: 'ü'
            })
        );
    }

    #[test]
    fn default_policy_transliterates() {
        let policy = CharsetPolicy::default();
        assert_eq!(policy.apply("Nm", "Müller & Co").unwrap(), "Mueller + Co");
    }

    #[test]
    fn truncation_never_splits_a_character() {
        // Regression: `&desc[..140]` panicked when byte 140 fell inside 'ü'.
        let s = format!("{}ü", "A".repeat(139));
        assert_eq!(s.len(), 141, "141 bytes, 140 characters");
        let out = truncate_chars(&s, 140);
        assert_eq!(out.chars().count(), 140);
        assert!(out.ends_with('ü'), "the whole character must survive");

        // One character over: the 'ü' is dropped whole, not split.
        let s2 = format!("{}ü", "A".repeat(140));
        let out2 = truncate_chars(&s2, 140);
        assert_eq!(out2, "A".repeat(140));
    }

    #[test]
    fn truncation_is_a_no_op_when_within_limit() {
        assert!(matches!(
            truncate_chars("short", 140),
            std::borrow::Cow::Borrowed("short")
        ));
        assert_eq!(truncate_chars("", 140), "");
    }

    #[test]
    fn epc_policy_transliterates_one_to_one() {
        let policy = CharsetPolicy::Transliterate(Transliteration::Epc);
        assert_eq!(policy.apply("Nm", "Müller & Co").unwrap(), "Muller + Co");
    }
}