Skip to main content

dvb_si/text/
mod.rs

1//! DVB-SI text decoding — ETSI EN 300 468 Annex A.
2//!
3//! Covers the full Annex A Table A.3 selector set: the default Latin table
4//! (Figure A.1, an ISO 6937 superset — see `iso_6937_single`), ISO 8859-n
5//! (single-byte 0x01–0x0B and extended 0x10 forms), UCS-2 BE (0x11),
6//! KS X 1001 Korean (0x12, decoded as EUC-KR), GB-2312 Simplified Chinese
7//! (0x13, decoded via GBK which is a GB-2312 superset), Big5 Traditional
8//! Chinese (0x14), UTF-8 (0x15), and the 0x1F `encoding_type_id` escape
9//! (no ids are registered for broadcast use — yields U+FFFD). Reserved
10//! selectors (0x08, 0x0C–0x0F, 0x16–0x1E) yield U+FFFD per byte.
11//!
12//! Glyph mappings are pinned to EN 300 468 V1.19.1 (2025-02) Figure A.1
13//! "Character code table 00 - Latin alphabet with Unicode equivalents"
14//! (PDF p. 159, vendored at `specs/etsi_en_300_468_v01.19.01_dvb_si.pdf`;
15//! transcription in
16//! `dvb-si/docs/tables/en_300_468/figure-a1-character-code-table-00-default-latin-alphabet.md`).
17//!
18//! [`DvbText`] wraps the raw wire bytes and decodes only on demand — parsing
19//! stays zero-copy; decoding happens when you call [`DvbText::decode`], `Display`,
20//! or serde:
21//!
22//! ```
23//! use dvb_si::text::{DvbText, LangCode};
24//!
25//! // Leading 0x15 is the Annex A UTF-8 selector; "café" follows.
26//! let name = DvbText::new(&[0x15, b'c', b'a', b'f', 0xC3, 0xA9]);
27//! assert_eq!(name.decode(), "café");
28//! assert_eq!(name.raw(), &[0x15, b'c', b'a', b'f', 0xC3, 0xA9]); // selector kept
29//!
30//! // A selector-less default-Latin (ISO 6937) sequence: combining acute + e → é.
31//! assert_eq!(DvbText::new(&[0xC2, b'e']).decode(), "é");
32//!
33//! // LangCode is 3 raw bytes (ISO 639-2 / ISO 3166) decoded lossily on demand.
34//! assert_eq!(LangCode(*b"fre").as_str(), "fre");
35//! ```
36
37use alloc::borrow::Cow;
38use alloc::string::String;
39use alloc::vec::Vec;
40
41/// Decode a DVB text payload (e.g. short_event_descriptor event_name_char)
42/// into an owned UTF-8 `String`. The first byte may be a charset indicator
43/// per ETSI EN 300 468 Annex A Table A.3.
44#[must_use]
45pub fn decode_dvb_string(bytes: &[u8]) -> String {
46    if bytes.is_empty() {
47        return String::new();
48    }
49
50    let (charset, body) = split_charset(bytes);
51    let decoded = match charset {
52        Charset::Iso6937 => decode_iso_6937(body),
53        Charset::Iso8859(n) => decode_iso_8859(n, body),
54        Charset::Utf8 => String::from_utf8_lossy(body).into_owned(),
55        Charset::Ucs2Be => decode_ucs2_be(body),
56        #[cfg(feature = "std")]
57        Charset::Ksx1001 => decode_with(encoding_rs::EUC_KR, body),
58        #[cfg(feature = "std")]
59        Charset::Gb2312 => decode_with(encoding_rs::GBK, body),
60        #[cfg(feature = "std")]
61        Charset::Big5 => decode_with(encoding_rs::BIG5, body),
62        // The CJK codec tables come from `encoding_rs`, which is std-only; under
63        // `no_std` these decode lossily (replacement chars), like an unsupported
64        // charset. The raw bytes remain available via `DvbText`.
65        #[cfg(not(feature = "std"))]
66        Charset::Ksx1001 | Charset::Gb2312 | Charset::Big5 => {
67            body.iter().map(|_| '\u{FFFD}').collect()
68        }
69        Charset::Unsupported(_indicator) => body.iter().map(|_| '\u{FFFD}').collect(),
70    };
71
72    // Annex A.1 control codes:
73    //   single-byte tables: 0x86 emphasis on, 0x87 emphasis off, 0x8A CR/LF
74    //   -> space; other C0/C1 controls are stripped.
75    //   two-byte tables (Table A.2): the same functions live at U+E086 /
76    //   U+E087 / U+E08A inside the ISO 10646 PUA; the rest of
77    //   U+E080..U+E09F is reserved for control functions and stripped.
78    decoded
79        .chars()
80        .filter_map(|c| match c as u32 {
81            0x86 | 0x87 | 0xE086 | 0xE087 => None,
82            0x8A | 0xE08A => Some(' '),
83            0x0A => Some(' '),
84            0x00..0x20 => None,
85            0x80..0xA0 => None,
86            0xE080..0xE0A0 => None,
87            _ => Some(c),
88        })
89        .collect()
90}
91
92/// Convenience wrapper returning `Cow::Borrowed` for pure-ASCII input,
93/// `Cow::Owned` otherwise.
94#[must_use]
95pub fn decode(bytes: &[u8]) -> Cow<'_, str> {
96    if bytes.iter().all(|&b| b.is_ascii() && b >= 0x20) {
97        return Cow::Borrowed(core::str::from_utf8(bytes).unwrap_or(""));
98    }
99    Cow::Owned(decode_dvb_string(bytes))
100}
101
102/// Borrowed DVB-encoded text (EN 300 468 Annex A). Wraps the raw selector +
103/// body bytes; decoding happens only on [`DvbText::decode`] / `Display` /
104/// serde — never in the parse hot path.
105#[derive(Clone, Copy, PartialEq, Eq, Hash)]
106#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
107pub struct DvbText<'a>(&'a [u8]);
108
109impl<'a> DvbText<'a> {
110    /// Wrap raw Annex A bytes (charset selector included, if any).
111    #[must_use]
112    pub const fn new(raw: &'a [u8]) -> Self {
113        Self(raw)
114    }
115    /// The raw wire bytes, selector included.
116    #[must_use]
117    pub const fn raw(&self) -> &'a [u8] {
118        self.0
119    }
120    /// Decode per Annex A (Table A.3 selector + control codes). Borrows only
121    /// for selector-less printable-ASCII input; any charset selector byte
122    /// forces an owned decode.
123    #[must_use]
124    pub fn decode(&self) -> Cow<'a, str> {
125        decode(self.0)
126    }
127}
128
129impl core::ops::Deref for DvbText<'_> {
130    /// Derefs to the raw wire bytes (selector included) — `len()`/indexing are
131    /// byte counts for serialization, not decoded character counts.
132    type Target = [u8];
133    fn deref(&self) -> &[u8] {
134        self.0
135    }
136}
137
138impl core::fmt::Display for DvbText<'_> {
139    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
140        f.write_str(&self.decode())
141    }
142}
143
144impl core::fmt::Debug for DvbText<'_> {
145    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
146        write!(f, "DvbText({:?})", self.decode())
147    }
148}
149
150impl<'a> From<&'a [u8]> for DvbText<'a> {
151    fn from(raw: &'a [u8]) -> Self {
152        Self(raw)
153    }
154}
155
156#[cfg(feature = "serde")]
157impl serde::Serialize for DvbText<'_> {
158    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
159        s.serialize_str(&self.decode())
160    }
161}
162// Serialize-only: re-encoding decoded text into DVB charset bytes is lossy.
163// Structs holding DvbText derive Serialize only; re-parse from wire bytes.
164
165/// ISO 639-2 language code or ISO 3166 country code — 3 raw bytes.
166#[derive(Clone, Copy, PartialEq, Eq, Hash)]
167pub struct LangCode(pub [u8; 3]);
168
169impl LangCode {
170    /// The code as a string; lossy (U+FFFD) for non-ASCII garbage.
171    #[must_use]
172    pub fn as_str(&self) -> Cow<'_, str> {
173        String::from_utf8_lossy(&self.0)
174    }
175}
176
177impl core::ops::Deref for LangCode {
178    type Target = [u8; 3];
179    fn deref(&self) -> &[u8; 3] {
180        &self.0
181    }
182}
183
184impl core::fmt::Display for LangCode {
185    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
186        f.write_str(&self.as_str())
187    }
188}
189
190impl core::fmt::Debug for LangCode {
191    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
192        write!(f, "LangCode({})", self.as_str())
193    }
194}
195
196#[cfg(feature = "serde")]
197impl serde::Serialize for LangCode {
198    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
199        s.serialize_str(&self.as_str())
200    }
201}
202
203#[derive(Debug)]
204enum Charset {
205    Iso6937,
206    Iso8859(u8),
207    Utf8,
208    Ucs2Be,
209    /// KS X 1001 (selector 0x12), decoded as EUC-KR.
210    Ksx1001,
211    /// GB-2312 (selector 0x13), decoded via GBK (a GB-2312 superset).
212    Gb2312,
213    /// Big5 (selector 0x14).
214    Big5,
215    Unsupported(u8),
216}
217
218fn split_charset(bytes: &[u8]) -> (Charset, &[u8]) {
219    match bytes[0] {
220        b if b >= 0x20 => (Charset::Iso6937, bytes),
221        0x00 => (Charset::Iso6937, &bytes[1..]),
222        // Table A.3: 0x01..=0x0B map to ISO 8859-5..-15, EXCEPT 0x08 which is
223        // "reserved for future use" (there is no ISO 8859-12).
224        0x08 => (Charset::Unsupported(0x08), &bytes[1..]),
225        0x01..=0x0B => (Charset::Iso8859(bytes[0] + 4), &bytes[1..]),
226        0x10 if bytes.len() >= 3 && bytes[1] == 0x00 => (Charset::Iso8859(bytes[2]), &bytes[3..]),
227        0x11 => (Charset::Ucs2Be, &bytes[1..]),
228        0x12 => (Charset::Ksx1001, &bytes[1..]),
229        0x13 => (Charset::Gb2312, &bytes[1..]),
230        0x14 => (Charset::Big5, &bytes[1..]),
231        0x15 => (Charset::Utf8, &bytes[1..]),
232        // 0x1F: an 8-bit encoding_type_id follows (Table A.4 area); no ids are
233        // registered for broadcast text — treat the body as undecodable.
234        0x1F if bytes.len() >= 2 => (Charset::Unsupported(0x1F), &bytes[2..]),
235        other => (Charset::Unsupported(other), &bytes[1..]),
236    }
237}
238
239fn decode_iso_6937(bytes: &[u8]) -> String {
240    let mut out = String::with_capacity(bytes.len());
241    let mut i = 0;
242    while i < bytes.len() {
243        let b = bytes[i];
244        // 0xC0..=0xCF is the Figure A.1 non-spacing (combining-prefix) row.
245        if (0xC0..=0xCF).contains(&b) {
246            match combining_mark(b) {
247                Some(mark) if i + 1 < bytes.len() => {
248                    let base = bytes[i + 1];
249                    if let Some(c) = combine(b, base) {
250                        out.push(c);
251                    } else {
252                        // No precomposed form — emit base + Unicode combining
253                        // mark, which is canonically equivalent.
254                        out.push(iso_6937_single(base));
255                        out.push(mark);
256                    }
257                    i += 2;
258                }
259                // Undefined prefix (0xC0/0xC9/0xCC) or dangling prefix at end.
260                _ => {
261                    out.push('\u{FFFD}');
262                    i += 1;
263                }
264            }
265            continue;
266        }
267        out.push(iso_6937_single(b));
268        i += 1;
269    }
270    out
271}
272
273/// Decode a single (non-combining) byte of the default Latin table.
274///
275/// Source: ETSI EN 300 468 V1.19.1 (2025-02) Figure A.1 — "Character code
276/// table 00 - Latin alphabet with Unicode equivalents" (PDF p. 159). Per the
277/// note under the figure, the table is a superset of ISO/IEC 6937 with the
278/// Euro symbol (U+20AC) added at position 0xA4. Grey (undefined) positions
279/// decode to U+FFFD.
280fn iso_6937_single(b: u8) -> char {
281    match b {
282        0x00..=0x7F => b as char,
283        // Preserve ETSI Annex A.2 C1 control codes so the post-filter can act on them.
284        0x86 | 0x87 | 0x8A => b as char,
285        0x80..=0x9F => '\u{FFFD}',
286        0xA0 => '\u{00A0}', // NBSP
287        0xA1 => '¡',
288        0xA2 => '¢',
289        0xA3 => '£',
290        0xA4 => '\u{20AC}', // € — DVB addition (note under Figure A.1)
291        0xA5 => '¥',
292        0xA6 => '\u{FFFD}', // undefined
293        0xA7 => '§',
294        0xA8 => '\u{00A4}', // ¤ general currency sign
295        0xA9 => '\u{2018}', // ' left single quotation mark
296        0xAA => '\u{201C}', // " left double quotation mark
297        0xAB => '«',
298        0xAC => '\u{2190}', // ←
299        0xAD => '\u{2191}', // ↑
300        0xAE => '\u{2192}', // →
301        0xAF => '\u{2193}', // ↓
302        0xB0 => '°',
303        0xB1 => '±',
304        0xB2 => '²',
305        0xB3 => '³',
306        0xB4 => '\u{00D7}', // ×
307        0xB5 => 'µ',
308        0xB6 => '¶',
309        0xB7 => '·',
310        0xB8 => '\u{00F7}', // ÷
311        0xB9 => '\u{2019}', // ' right single quotation mark
312        0xBA => '\u{201D}', // " right double quotation mark
313        0xBB => '»',
314        0xBC => '¼',
315        0xBD => '½',
316        0xBE => '¾',
317        0xBF => '¿',
318        // Combining-prefix row; reached only for a dangling/undefined prefix.
319        0xC0..=0xCF => '\u{FFFD}',
320        0xD0 => '\u{2015}', // ― horizontal bar
321        0xD1 => '¹',
322        0xD2 => '®',
323        0xD3 => '©',
324        0xD4 => '\u{2122}', // ™
325        0xD5 => '\u{266A}', // ♪ eighth note
326        0xD6 => '¬',
327        0xD7 => '\u{00A6}',        // ¦ broken bar
328        0xD8..=0xDB => '\u{FFFD}', // undefined
329        0xDC => '\u{215B}',        // ⅛
330        0xDD => '\u{215C}',        // ⅜
331        0xDE => '\u{215D}',        // ⅝
332        0xDF => '\u{215E}',        // ⅞
333        0xE0 => '\u{2126}',        // Ω OHM SIGN
334        0xE1 => 'Æ',
335        0xE2 => '\u{0110}', // Đ
336        0xE3 => 'ª',
337        0xE4 => '\u{0126}', // Ħ
338        0xE5 => '\u{FFFD}', // undefined
339        0xE6 => '\u{0132}', // IJ
340        0xE7 => '\u{013F}', // Ŀ
341        0xE8 => '\u{0141}', // Ł
342        0xE9 => 'Ø',
343        0xEA => '\u{0152}', // Œ
344        0xEB => 'º',
345        0xEC => 'Þ',
346        0xED => '\u{0166}', // Ŧ
347        0xEE => '\u{014A}', // Ŋ
348        0xEF => '\u{0149}', // ʼn
349        0xF0 => '\u{0138}', // ĸ
350        0xF1 => 'æ',
351        0xF2 => '\u{0111}', // đ
352        0xF3 => 'ð',
353        0xF4 => '\u{0127}', // ħ
354        0xF5 => '\u{0131}', // ı dotless i
355        0xF6 => '\u{0133}', // ij
356        0xF7 => '\u{0140}', // ŀ
357        0xF8 => '\u{0142}', // ł
358        0xF9 => 'ø',
359        0xFA => '\u{0153}', // œ
360        0xFB => 'ß',
361        0xFC => '\u{00FE}', // þ
362        0xFD => '\u{0167}', // ŧ
363        0xFE => '\u{014B}', // ŋ
364        0xFF => '\u{00AD}', // SHY soft hyphen
365    }
366}
367
368/// Unicode combining mark for a Figure A.1 non-spacing prefix byte
369/// (row 0xC0..=0xCF). `None` for the undefined positions 0xC0/0xC9/0xCC.
370fn combining_mark(prefix: u8) -> Option<char> {
371    Some(match prefix {
372        0xC1 => '\u{0300}', // grave
373        0xC2 => '\u{0301}', // acute
374        0xC3 => '\u{0302}', // circumflex
375        0xC4 => '\u{0303}', // tilde
376        0xC5 => '\u{0304}', // macron
377        0xC6 => '\u{0306}', // breve
378        0xC7 => '\u{0307}', // dot above
379        0xC8 => '\u{0308}', // diaeresis
380        0xCA => '\u{030A}', // ring above
381        0xCB => '\u{0327}', // cedilla
382        0xCD => '\u{030B}', // double acute
383        0xCE => '\u{0328}', // ogonek
384        0xCF => '\u{030C}', // caron
385        _ => return None,
386    })
387}
388
389fn combine(prefix: u8, base: u8) -> Option<char> {
390    Some(match (prefix, base) {
391        (0xC1, b'A') => 'À',
392        (0xC1, b'E') => 'È',
393        (0xC1, b'I') => 'Ì',
394        (0xC1, b'O') => 'Ò',
395        (0xC1, b'U') => 'Ù',
396        (0xC1, b'a') => 'à',
397        (0xC1, b'e') => 'è',
398        (0xC1, b'i') => 'ì',
399        (0xC1, b'o') => 'ò',
400        (0xC1, b'u') => 'ù',
401        (0xC2, b'A') => 'Á',
402        (0xC2, b'E') => 'É',
403        (0xC2, b'I') => 'Í',
404        (0xC2, b'O') => 'Ó',
405        (0xC2, b'U') => 'Ú',
406        (0xC2, b'Y') => 'Ý',
407        (0xC2, b'a') => 'á',
408        (0xC2, b'e') => 'é',
409        (0xC2, b'i') => 'í',
410        (0xC2, b'o') => 'ó',
411        (0xC2, b'u') => 'ú',
412        (0xC2, b'y') => 'ý',
413        (0xC2, b'C') => 'Ć',
414        (0xC2, b'c') => 'ć',
415        (0xC2, b'L') => 'Ĺ',
416        (0xC2, b'l') => 'ĺ',
417        (0xC2, b'N') => 'Ń',
418        (0xC2, b'n') => 'ń',
419        (0xC2, b'R') => 'Ŕ',
420        (0xC2, b'r') => 'ŕ',
421        (0xC2, b'S') => 'Ś',
422        (0xC2, b's') => 'ś',
423        (0xC2, b'Z') => 'Ź',
424        (0xC2, b'z') => 'ź',
425        (0xC3, b'A') => 'Â',
426        (0xC3, b'E') => 'Ê',
427        (0xC3, b'I') => 'Î',
428        (0xC3, b'O') => 'Ô',
429        (0xC3, b'U') => 'Û',
430        (0xC3, b'a') => 'â',
431        (0xC3, b'e') => 'ê',
432        (0xC3, b'i') => 'î',
433        (0xC3, b'o') => 'ô',
434        (0xC3, b'u') => 'û',
435        (0xC4, b'A') => 'Ã',
436        (0xC4, b'N') => 'Ñ',
437        (0xC4, b'O') => 'Õ',
438        (0xC4, b'a') => 'ã',
439        (0xC4, b'n') => 'ñ',
440        (0xC4, b'o') => 'õ',
441        (0xC4, b'I') => 'Ĩ',
442        (0xC4, b'i') => 'ĩ',
443        (0xC4, b'U') => 'Ũ',
444        (0xC4, b'u') => 'ũ',
445        // macron
446        (0xC5, b'A') => 'Ā',
447        (0xC5, b'a') => 'ā',
448        (0xC5, b'E') => 'Ē',
449        (0xC5, b'e') => 'ē',
450        (0xC5, b'I') => 'Ī',
451        (0xC5, b'i') => 'ī',
452        (0xC5, b'O') => 'Ō',
453        (0xC5, b'o') => 'ō',
454        (0xC5, b'U') => 'Ū',
455        (0xC5, b'u') => 'ū',
456        // breve
457        (0xC6, b'A') => 'Ă',
458        (0xC6, b'a') => 'ă',
459        (0xC6, b'G') => 'Ğ',
460        (0xC6, b'g') => 'ğ',
461        (0xC6, b'U') => 'Ŭ',
462        (0xC6, b'u') => 'ŭ',
463        // dot above
464        (0xC7, b'C') => 'Ċ',
465        (0xC7, b'c') => 'ċ',
466        (0xC7, b'E') => 'Ė',
467        (0xC7, b'e') => 'ė',
468        (0xC7, b'G') => 'Ġ',
469        (0xC7, b'g') => 'ġ',
470        (0xC7, b'I') => 'İ',
471        (0xC7, b'Z') => 'Ż',
472        (0xC7, b'z') => 'ż',
473        (0xC8, b'A') => 'Ä',
474        (0xC8, b'E') => 'Ë',
475        (0xC8, b'I') => 'Ï',
476        (0xC8, b'O') => 'Ö',
477        (0xC8, b'U') => 'Ü',
478        (0xC8, b'Y') => 'Ÿ',
479        (0xC8, b'a') => 'ä',
480        (0xC8, b'e') => 'ë',
481        (0xC8, b'i') => 'ï',
482        (0xC8, b'o') => 'ö',
483        (0xC8, b'u') => 'ü',
484        (0xC8, b'y') => 'ÿ',
485        // ring above
486        (0xCA, b'A') => 'Å',
487        (0xCA, b'a') => 'å',
488        (0xCA, b'U') => 'Ů',
489        (0xCA, b'u') => 'ů',
490        (0xCB, b'C') => 'Ç',
491        (0xCB, b'c') => 'ç',
492        (0xCB, b'G') => 'Ģ',
493        (0xCB, b'g') => 'ģ',
494        (0xCB, b'K') => 'Ķ',
495        (0xCB, b'k') => 'ķ',
496        (0xCB, b'L') => 'Ļ',
497        (0xCB, b'l') => 'ļ',
498        (0xCB, b'N') => 'Ņ',
499        (0xCB, b'n') => 'ņ',
500        (0xCB, b'R') => 'Ŗ',
501        (0xCB, b'r') => 'ŗ',
502        (0xCB, b'S') => 'Ş',
503        (0xCB, b's') => 'ş',
504        (0xCB, b'T') => 'Ţ',
505        (0xCB, b't') => 'ţ',
506        // double acute
507        (0xCD, b'O') => 'Ő',
508        (0xCD, b'o') => 'ő',
509        (0xCD, b'U') => 'Ű',
510        (0xCD, b'u') => 'ű',
511        // ogonek
512        (0xCE, b'A') => 'Ą',
513        (0xCE, b'a') => 'ą',
514        (0xCE, b'E') => 'Ę',
515        (0xCE, b'e') => 'ę',
516        (0xCE, b'I') => 'Į',
517        (0xCE, b'i') => 'į',
518        (0xCE, b'U') => 'Ų',
519        (0xCE, b'u') => 'ų',
520        // caron
521        (0xCF, b'C') => 'Č',
522        (0xCF, b'c') => 'č',
523        (0xCF, b'D') => 'Ď',
524        (0xCF, b'd') => 'ď',
525        (0xCF, b'E') => 'Ě',
526        (0xCF, b'e') => 'ě',
527        (0xCF, b'L') => 'Ľ',
528        (0xCF, b'l') => 'ľ',
529        (0xCF, b'N') => 'Ň',
530        (0xCF, b'n') => 'ň',
531        (0xCF, b'R') => 'Ř',
532        (0xCF, b'r') => 'ř',
533        (0xCF, b'S') => 'Š',
534        (0xCF, b's') => 'š',
535        (0xCF, b'T') => 'Ť',
536        (0xCF, b't') => 'ť',
537        (0xCF, b'Z') => 'Ž',
538        (0xCF, b'z') => 'ž',
539        _ => return None,
540    })
541}
542
543fn decode_iso_8859(n: u8, bytes: &[u8]) -> String {
544    // ISO/IEC 8859-1 (Latin-1) is the first 256 Unicode code points exactly, so
545    // a byte→char cast is a correct decode — and needs no codec tables, so it
546    // works under `no_std` too. (encoding_rs has no pure 8859-1; WINDOWS_1252
547    // differs in 0x80–0x9F, so don't use it here.)
548    if n == 1 {
549        return bytes.iter().map(|&b| b as char).collect();
550    }
551    // The other 8859 parts use `encoding_rs`'s codec tables, which are std-only;
552    // under `no_std` they decode lossily (replacement chars). Raw bytes remain
553    // available via `DvbText`.
554    #[cfg(feature = "std")]
555    {
556        use encoding_rs::*;
557        // `encoding_rs` (and the WHATWG label registry it implements) has no
558        // pure ISO/IEC 8859-9 or 8859-11 codec: web-compat routes both labels
559        // to windows-1254 / windows-874, which match the true 8859-9 / 8859-11
560        // GR range (0xA0-0xFF) byte-for-byte but remap 0x80-0x9F to printable
561        // characters, where DVB Annex A's single-byte tables leave that range
562        // as the C1 control set (§A.1's 0x86/0x87/0x8A emphasis/CR-LF codes
563        // live there, and `decode_dvb_string`'s post-filter only strips them
564        // in the C1 range) — so a Turkish/Thai emphasis marker or line break
565        // was coming out as a Windows-1252-style printable glyph instead of
566        // being recognised and stripped/converted. Every byte of these
567        // encodings decodes to exactly one code point (no multi-byte
568        // sequences, no BOM handling for a non-Unicode encoding), so decode
569        // then overwrite just the 0x80-0x9F positions with the raw C1 code
570        // point.
571        if n == 9 || n == 11 {
572            let encoding: &'static Encoding = if n == 9 { WINDOWS_1254 } else { WINDOWS_874 };
573            let (cow, _) = encoding.decode_without_bom_handling(bytes);
574            debug_assert_eq!(cow.chars().count(), bytes.len());
575            return bytes
576                .iter()
577                .zip(cow.chars())
578                .map(|(&b, c)| {
579                    if (0x80..=0x9F).contains(&b) {
580                        b as char
581                    } else {
582                        c
583                    }
584                })
585                .collect();
586        }
587        let encoding: &'static Encoding = match n {
588            2 => ISO_8859_2,
589            3 => ISO_8859_3,
590            4 => ISO_8859_4,
591            5 => ISO_8859_5,
592            6 => ISO_8859_6,
593            7 => ISO_8859_7,
594            8 => ISO_8859_8,
595            10 => ISO_8859_10,
596            13 => ISO_8859_13,
597            14 => ISO_8859_14,
598            15 => ISO_8859_15,
599            _ => return bytes.iter().map(|_| '\u{FFFD}').collect(),
600        };
601        let (cow, _, _) = encoding.decode(bytes);
602        cow.into_owned()
603    }
604    #[cfg(not(feature = "std"))]
605    {
606        let _ = n;
607        bytes.iter().map(|_| '\u{FFFD}').collect()
608    }
609}
610
611#[cfg(feature = "std")]
612fn decode_with(encoding: &'static encoding_rs::Encoding, bytes: &[u8]) -> String {
613    let (cow, _, _) = encoding.decode(bytes);
614    cow.into_owned()
615}
616
617fn decode_ucs2_be(bytes: &[u8]) -> String {
618    let code_units: Vec<u16> = bytes
619        .chunks_exact(2)
620        .map(|pair| u16::from_be_bytes(*pair.first_chunk::<2>().unwrap()))
621        .collect();
622    String::from_utf16_lossy(&code_units)
623}
624
625#[cfg(test)]
626mod tests {
627    use super::*;
628
629    #[test]
630    fn decode_empty_input_returns_empty_string() {
631        assert_eq!(decode_dvb_string(&[]), "");
632    }
633
634    #[test]
635    fn decode_plain_ascii_is_borrowed() {
636        let cow = decode(b"HELLO");
637        assert!(matches!(cow, Cow::Borrowed(_)));
638        assert_eq!(cow, "HELLO");
639    }
640
641    #[test]
642    fn decode_iso6937_latin_accent_chars() {
643        assert_eq!(decode_dvb_string(&[0x00, 0xC2, b'A']), "Á");
644        assert_eq!(decode_dvb_string(&[0x00, 0xC1, b'e']), "è");
645        assert_eq!(decode_dvb_string(&[0x00, 0xC8, b'o']), "ö");
646    }
647
648    #[test]
649    fn decode_selector_0x01_yields_iso8859_5_cyrillic() {
650        let s = decode_dvb_string(&[0x01, 0xB0, 0xB1]);
651        assert!(s.chars().all(|c| c != '\u{FFFD}'), "got: {s:?}");
652        assert!(!s.is_empty());
653    }
654
655    #[test]
656    fn decode_selector_0x10_extended_yields_iso8859_nn() {
657        let s = decode_dvb_string(&[0x10, 0x00, 0x09, b'A', b'B']);
658        assert_eq!(s, "AB");
659    }
660
661    #[test]
662    fn decode_selector_0x11_ucs2_be() {
663        let s = decode_dvb_string(&[0x11, 0x00, 0x41, 0x00, 0x42]);
664        assert_eq!(s, "AB");
665    }
666
667    #[test]
668    fn decode_selector_0x15_utf8_passthrough() {
669        let s = decode_dvb_string(&[0x15, 0xC3, 0xA9, 0xC3, 0xA9]);
670        assert_eq!(s, "éé");
671    }
672
673    #[test]
674    fn decode_control_chars_stripped_linefeed_becomes_space() {
675        let s = decode_dvb_string(b"A\x01B\nC");
676        assert_eq!(s, "AB C");
677    }
678
679    #[test]
680    fn emphasis_on_off_markers_stripped_per_annex_a2() {
681        // 0x86 and 0x87 are emphasis on/off markers per ETSI Annex A.2 — not
682        // representable in plain text, strip silently.
683        let s = decode_dvb_string(&[0x00, b'A', 0x86, b'B', 0x87, b'C']);
684        assert_eq!(s, "ABC");
685    }
686
687    #[test]
688    fn decode_annex_a2_crlf_0x8a_becomes_space() {
689        // 0x8A in DVB text maps to CR/LF per Annex A.2 — render as space.
690        let s = decode_dvb_string(&[0x00, b'A', 0x8A, b'B']);
691        assert_eq!(s, "A B");
692    }
693
694    /// Regression for r02-W3: ISO/IEC 8859-9 (selector 9, Turkish) and
695    /// 8859-11 (selector 11, Thai) share ISO 8859's C1 control layout in
696    /// 0x80-0x9F, unlike the windows-1254/windows-874 codepages
697    /// `encoding_rs` maps those selectors to (which put printable
698    /// characters there instead). Previously an Annex A.2 CR/LF (0x8A) or
699    /// emphasis marker (0x86/0x87) in Turkish/Thai text decoded as a
700    /// Windows-125x glyph and leaked through `decode_dvb_string`'s
701    /// control-code filter untouched, instead of being recognised.
702    #[cfg(feature = "std")]
703    #[test]
704    fn decode_selector_9_and_11_treat_0x80_0x9f_as_c1_controls() {
705        // Selector 9 = ISO 8859-9: 0x8A must become a space (CR/LF), exactly
706        // like the plain-Latin (selector 0x00) case above — not the
707        // windows-1254 glyph at that byte (Š).
708        let s = decode_dvb_string(&[0x10, 0x00, 0x09, b'A', 0x8A, b'B']);
709        assert_eq!(s, "A B");
710        // 0x80 has no Annex A.2 meaning and must be stripped, not decoded as
711        // windows-1254's Euro sign.
712        let s = decode_dvb_string(&[0x10, 0x00, 0x09, b'A', 0x80, b'B']);
713        assert_eq!(s, "AB");
714
715        // Selector 11 = ISO 8859-11: same story against windows-874.
716        let s = decode_dvb_string(&[0x10, 0x00, 0x0B, b'A', 0x8A, b'B']);
717        assert_eq!(s, "A B");
718        let s = decode_dvb_string(&[0x10, 0x00, 0x0B, b'A', 0x80, b'B']);
719        assert_eq!(s, "AB");
720
721        // The GR range (0xA0-0xFF) is unaffected: selector 9's Turkish
722        // İ (dotted capital I) at 0xDD still decodes correctly.
723        let s = decode_dvb_string(&[0x10, 0x00, 0x09, 0xDD]);
724        assert_eq!(s, "İ");
725    }
726
727    #[test]
728    fn decode_selector_0x12_ksx1001_euc_kr() {
729        // EUC-KR 0xB0A1 = '가' (HANGUL SYLLABLE GA).
730        assert_eq!(decode_dvb_string(&[0x12, 0xB0, 0xA1]), "가");
731    }
732
733    #[test]
734    fn decode_selector_0x13_gb2312() {
735        // GB-2312/GBK 0xC4E3 = '你'.
736        assert_eq!(decode_dvb_string(&[0x13, 0xC4, 0xE3]), "你");
737    }
738
739    #[test]
740    fn decode_selector_0x14_big5() {
741        // Big5 0xA4A4 = '中'.
742        assert_eq!(decode_dvb_string(&[0x14, 0xA4, 0xA4]), "中");
743    }
744
745    /// A multi-byte trail byte in 0x80–0x9F must survive: the C1 control
746    /// filter operates on decoded code points, never on raw trail bytes.
747    /// GBK 0x8180 = '亐' (U+4E90, trail byte in the C1 range).
748    #[test]
749    fn decode_selector_0x13_gbk_trail_byte_in_c1_range() {
750        assert_eq!(decode_dvb_string(&[0x13, 0x81, 0x80]), "亐");
751    }
752
753    /// Annex A.1 two-byte control codes live at U+E080–U+E09F in the PUA
754    /// (Table A.2): U+E08A is CR/LF → space; the reserved rest is stripped.
755    /// GBK 0xABCD decodes to U+E08A; GBK 0xABC3 decodes to U+E080.
756    #[test]
757    fn two_byte_control_codes_filtered() {
758        assert_eq!(decode_dvb_string(&[0x13, 0xAB, 0xCD]), " ");
759        assert_eq!(decode_dvb_string(&[0x13, 0xAB, 0xC3]), "");
760    }
761
762    /// 0x1F consumes its 8-bit encoding_type_id; the body is undecodable
763    /// (no registered broadcast ids) and yields U+FFFD per byte.
764    #[test]
765    fn decode_selector_0x1f_encoding_type_id() {
766        let s = decode_dvb_string(&[0x1F, 0x01, 0x41, 0x42]);
767        assert_eq!(s.chars().count(), 2);
768        assert!(s.chars().all(|c| c == '\u{FFFD}'));
769    }
770
771    /// Table A.3 marks single-byte selector 0x08 reserved (no ISO 8859-12).
772    #[test]
773    fn reserved_selector_0x08_is_unsupported() {
774        let s = decode_dvb_string(&[0x08, 0x41, 0x42]);
775        assert!(s.chars().all(|c| c == '\u{FFFD}'));
776        assert_eq!(s.chars().count(), 2);
777    }
778
779    #[test]
780    fn unknown_selector_returns_replacement_characters() {
781        // Selector 0x16 is reserved for future use — each byte becomes U+FFFD.
782        let s = decode_dvb_string(&[0x16, 0xAA, 0xBB, 0xCC]);
783        assert_eq!(s.chars().count(), 3);
784        assert!(s.chars().all(|c| c == '\u{FFFD}'));
785    }
786
787    /// An unsupported ISO 8859 part number (via 0x10 extended selector) yields
788    /// U+FFFD per byte rather than Latin-1 passthrough.
789    #[test]
790    fn selector_0x10_iso_8859_1_decodes_latin1() {
791        // 0x10 0x00 0x01 → ISO/IEC 8859-1 (Latin-1): bytes are the first 256
792        // Unicode code points 1:1, so 0xE9 → 'é'. (A valid charset; must NOT be
793        // treated as unsupported / U+FFFD.)
794        let s = decode_dvb_string(&[0x10, 0x00, 0x01, 0x41, 0xE9]);
795        assert_eq!(s, "Aé");
796    }
797
798    #[test]
799    fn unsupported_iso_8859_12_yields_replacement() {
800        // 0x10 0x00 0x0C → ISO 8859-12 does not exist (reserved); unsupported
801        // parts decode to U+FFFD, not fabricated text.
802        let s = decode_dvb_string(&[0x10, 0x00, 0x0C, 0x41, 0x42]);
803        assert!(s.chars().all(|c| c == '\u{FFFD}'), "got: {s:?}");
804    }
805
806    /// Pins the GR-area single-byte mappings to ETSI EN 300 468 V1.19.1
807    /// (2025-02) Figure A.1 — "Character code table 00 - Latin alphabet with
808    /// Unicode equivalents" (PDF p. 159; vendored at
809    /// `specs/etsi_en_300_468_v01.19.01_dvb_si.pdf`).
810    #[test]
811    fn figure_a1_gr_area_single_byte_mappings() {
812        let pins: &[(u8, char)] = &[
813            (0xA0, '\u{00A0}'), // NBSP
814            (0xA1, '¡'),
815            (0xA2, '¢'),
816            (0xA3, '£'),
817            (0xA4, '\u{20AC}'), // € — DVB addition (note under Figure A.1)
818            (0xA5, '¥'),
819            (0xA7, '§'),
820            (0xA8, '\u{00A4}'), // ¤ general currency sign
821            (0xA9, '\u{2018}'), // '
822            (0xAA, '\u{201C}'), // "
823            (0xAB, '«'),
824            (0xAC, '\u{2190}'), // ←
825            (0xAD, '\u{2191}'), // ↑
826            (0xAE, '\u{2192}'), // →
827            (0xAF, '\u{2193}'), // ↓
828            (0xB0, '°'),
829            (0xB1, '±'),
830            (0xB2, '²'),
831            (0xB3, '³'),
832            (0xB4, '\u{00D7}'), // ×
833            (0xB5, 'µ'),
834            (0xB6, '¶'),
835            (0xB7, '·'),
836            (0xB8, '\u{00F7}'), // ÷
837            (0xB9, '\u{2019}'), // '
838            (0xBA, '\u{201D}'), // "
839            (0xBB, '»'),
840            (0xBC, '¼'),
841            (0xBD, '½'),
842            (0xBE, '¾'),
843            (0xBF, '¿'),
844            (0xD0, '\u{2015}'), // ―
845            (0xD1, '¹'),
846            (0xD2, '®'),
847            (0xD3, '©'),
848            (0xD4, '\u{2122}'), // ™
849            (0xD5, '\u{266A}'), // ♪
850            (0xD6, '¬'),
851            (0xD7, '\u{00A6}'), // ¦
852            (0xDC, '\u{215B}'), // ⅛
853            (0xDD, '\u{215C}'), // ⅜
854            (0xDE, '\u{215D}'), // ⅝
855            (0xDF, '\u{215E}'), // ⅞
856            (0xE0, '\u{2126}'), // Ω OHM SIGN
857            (0xE1, 'Æ'),
858            (0xE2, '\u{0110}'), // Đ
859            (0xE3, 'ª'),
860            (0xE4, '\u{0126}'), // Ħ
861            (0xE6, '\u{0132}'), // IJ
862            (0xE7, '\u{013F}'), // Ŀ
863            (0xE8, '\u{0141}'), // Ł
864            (0xE9, 'Ø'),
865            (0xEA, '\u{0152}'), // Œ
866            (0xEB, 'º'),
867            (0xEC, 'Þ'),
868            (0xED, '\u{0166}'), // Ŧ
869            (0xEE, '\u{014A}'), // Ŋ
870            (0xEF, '\u{0149}'), // ʼn
871            (0xF0, '\u{0138}'), // ĸ
872            (0xF1, 'æ'),
873            (0xF2, '\u{0111}'), // đ
874            (0xF3, 'ð'),
875            (0xF4, '\u{0127}'), // ħ
876            (0xF5, '\u{0131}'), // ı
877            (0xF6, '\u{0133}'), // ij
878            (0xF7, '\u{0140}'), // ŀ
879            (0xF8, '\u{0142}'), // ł
880            (0xF9, 'ø'),
881            (0xFA, '\u{0153}'), // œ
882            (0xFB, 'ß'),
883            (0xFC, '\u{00FE}'), // þ
884            (0xFD, '\u{0167}'), // ŧ
885            (0xFE, '\u{014B}'), // ŋ
886            (0xFF, '\u{00AD}'), // SHY soft hyphen
887        ];
888        for &(byte, want) in pins {
889            let got = decode_dvb_string(&[0x00, byte]);
890            assert_eq!(
891                got,
892                want.to_string(),
893                "byte {byte:#04x}: want {want:?} (U+{:04X}), got {got:?}",
894                want as u32
895            );
896        }
897    }
898
899    /// Bytes undefined (grey) in Figure A.1 decode to U+FFFD.
900    #[test]
901    fn figure_a1_undefined_positions_are_replacement() {
902        for byte in [0xA6u8, 0xD8, 0xD9, 0xDA, 0xDB, 0xE5] {
903            let got = decode_dvb_string(&[0x00, byte]);
904            assert_eq!(got, "\u{FFFD}", "byte {byte:#04x} should be U+FFFD");
905        }
906    }
907
908    /// C-row prefixes with precomposed entries (Figure A.1 non-spacing row).
909    #[test]
910    fn figure_a1_combining_precomposed() {
911        assert_eq!(decode_dvb_string(&[0x00, 0xCA, b'a']), "å"); // ring U+030A
912        assert_eq!(decode_dvb_string(&[0x00, 0xCA, b'A']), "Å");
913        assert_eq!(decode_dvb_string(&[0x00, 0xCF, b's']), "š"); // caron U+030C
914        assert_eq!(decode_dvb_string(&[0x00, 0xCF, b'Z']), "Ž");
915        assert_eq!(decode_dvb_string(&[0x00, 0xCE, b'e']), "ę"); // ogonek U+0328
916        assert_eq!(decode_dvb_string(&[0x00, 0xCD, b'o']), "ő"); // double acute U+030B
917        assert_eq!(decode_dvb_string(&[0x00, 0xC7, b'z']), "ż"); // dot above U+0307
918        assert_eq!(decode_dvb_string(&[0x00, 0xC5, b'a']), "ā"); // macron U+0304
919        assert_eq!(decode_dvb_string(&[0x00, 0xC6, b'g']), "ğ"); // breve U+0306
920    }
921
922    /// A defined prefix with no precomposed form falls back to
923    /// base + Unicode combining mark (canonically equivalent).
924    #[test]
925    fn figure_a1_combining_fallback_emits_base_plus_mark() {
926        assert_eq!(decode_dvb_string(&[0x00, 0xC5, b'x']), "x\u{0304}");
927    }
928
929    /// Undefined C-row prefixes (0xC0, 0xC9, 0xCC) and a dangling prefix at
930    /// end of input decode to U+FFFD.
931    #[test]
932    fn figure_a1_combining_undefined_or_dangling_prefix() {
933        assert_eq!(decode_dvb_string(&[0x00, 0xC0, b'a']), "\u{FFFD}a");
934        assert_eq!(decode_dvb_string(&[0x00, 0xC9, b'a']), "\u{FFFD}a");
935        assert_eq!(decode_dvb_string(&[0x00, 0xCC, b'a']), "\u{FFFD}a");
936        assert_eq!(decode_dvb_string(&[0x00, 0xC2]), "\u{FFFD}");
937    }
938
939    #[test]
940    fn dvb_text_decodes_with_charset_selector() {
941        let t = DvbText::new(&[0x15, 0xC3, 0xA9]); // UTF-8 selector + é
942        assert_eq!(t.decode(), "é");
943        assert_eq!(t.raw(), &[0x15, 0xC3, 0xA9]);
944        assert_eq!(&t[..], &[0x15, 0xC3, 0xA9]); // Deref
945        assert_eq!(format!("{t}"), "é");
946    }
947
948    #[test]
949    fn lang_code_as_str() {
950        assert_eq!(LangCode(*b"fre").as_str(), "fre");
951        assert_eq!(LangCode([0xFF, b'r', b'e']).as_str(), "\u{FFFD}re"); // lossy, no panic
952    }
953
954    #[cfg(feature = "serde")]
955    #[test]
956    fn dvb_text_serializes_decoded() {
957        let t = DvbText::new(&[0x15, 0xC3, 0xA9]);
958        assert_eq!(serde_json::to_string(&t).unwrap(), "\"é\"");
959    }
960
961    #[cfg(feature = "serde")]
962    #[test]
963    fn lang_code_serializes_as_string() {
964        // Serialize-only: LangCode renders as its decoded string. Parsing FROM
965        // JSON is deliberately unsupported (re-parse from wire bytes instead).
966        let lc = LangCode(*b"FRA");
967        assert_eq!(serde_json::to_string(&lc).unwrap(), "\"FRA\"");
968    }
969}