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        let encoding: &'static Encoding = match n {
558            2 => ISO_8859_2,
559            3 => ISO_8859_3,
560            4 => ISO_8859_4,
561            5 => ISO_8859_5,
562            6 => ISO_8859_6,
563            7 => ISO_8859_7,
564            8 => ISO_8859_8,
565            9 => WINDOWS_1254,
566            10 => ISO_8859_10,
567            11 => WINDOWS_874,
568            13 => ISO_8859_13,
569            14 => ISO_8859_14,
570            15 => ISO_8859_15,
571            _ => return bytes.iter().map(|_| '\u{FFFD}').collect(),
572        };
573        let (cow, _, _) = encoding.decode(bytes);
574        cow.into_owned()
575    }
576    #[cfg(not(feature = "std"))]
577    {
578        let _ = n;
579        bytes.iter().map(|_| '\u{FFFD}').collect()
580    }
581}
582
583#[cfg(feature = "std")]
584fn decode_with(encoding: &'static encoding_rs::Encoding, bytes: &[u8]) -> String {
585    let (cow, _, _) = encoding.decode(bytes);
586    cow.into_owned()
587}
588
589fn decode_ucs2_be(bytes: &[u8]) -> String {
590    let code_units: Vec<u16> = bytes
591        .chunks_exact(2)
592        .map(|pair| u16::from_be_bytes(*pair.first_chunk::<2>().unwrap()))
593        .collect();
594    String::from_utf16_lossy(&code_units)
595}
596
597#[cfg(test)]
598mod tests {
599    use super::*;
600
601    #[test]
602    fn decode_empty_input_returns_empty_string() {
603        assert_eq!(decode_dvb_string(&[]), "");
604    }
605
606    #[test]
607    fn decode_plain_ascii_is_borrowed() {
608        let cow = decode(b"HELLO");
609        assert!(matches!(cow, Cow::Borrowed(_)));
610        assert_eq!(cow, "HELLO");
611    }
612
613    #[test]
614    fn decode_iso6937_latin_accent_chars() {
615        assert_eq!(decode_dvb_string(&[0x00, 0xC2, b'A']), "Á");
616        assert_eq!(decode_dvb_string(&[0x00, 0xC1, b'e']), "è");
617        assert_eq!(decode_dvb_string(&[0x00, 0xC8, b'o']), "ö");
618    }
619
620    #[test]
621    fn decode_selector_0x01_yields_iso8859_5_cyrillic() {
622        let s = decode_dvb_string(&[0x01, 0xB0, 0xB1]);
623        assert!(s.chars().all(|c| c != '\u{FFFD}'), "got: {s:?}");
624        assert!(!s.is_empty());
625    }
626
627    #[test]
628    fn decode_selector_0x10_extended_yields_iso8859_nn() {
629        let s = decode_dvb_string(&[0x10, 0x00, 0x09, b'A', b'B']);
630        assert_eq!(s, "AB");
631    }
632
633    #[test]
634    fn decode_selector_0x11_ucs2_be() {
635        let s = decode_dvb_string(&[0x11, 0x00, 0x41, 0x00, 0x42]);
636        assert_eq!(s, "AB");
637    }
638
639    #[test]
640    fn decode_selector_0x15_utf8_passthrough() {
641        let s = decode_dvb_string(&[0x15, 0xC3, 0xA9, 0xC3, 0xA9]);
642        assert_eq!(s, "éé");
643    }
644
645    #[test]
646    fn decode_control_chars_stripped_linefeed_becomes_space() {
647        let s = decode_dvb_string(b"A\x01B\nC");
648        assert_eq!(s, "AB C");
649    }
650
651    #[test]
652    fn emphasis_on_off_markers_stripped_per_annex_a2() {
653        // 0x86 and 0x87 are emphasis on/off markers per ETSI Annex A.2 — not
654        // representable in plain text, strip silently.
655        let s = decode_dvb_string(&[0x00, b'A', 0x86, b'B', 0x87, b'C']);
656        assert_eq!(s, "ABC");
657    }
658
659    #[test]
660    fn decode_annex_a2_crlf_0x8a_becomes_space() {
661        // 0x8A in DVB text maps to CR/LF per Annex A.2 — render as space.
662        let s = decode_dvb_string(&[0x00, b'A', 0x8A, b'B']);
663        assert_eq!(s, "A B");
664    }
665
666    #[test]
667    fn decode_selector_0x12_ksx1001_euc_kr() {
668        // EUC-KR 0xB0A1 = '가' (HANGUL SYLLABLE GA).
669        assert_eq!(decode_dvb_string(&[0x12, 0xB0, 0xA1]), "가");
670    }
671
672    #[test]
673    fn decode_selector_0x13_gb2312() {
674        // GB-2312/GBK 0xC4E3 = '你'.
675        assert_eq!(decode_dvb_string(&[0x13, 0xC4, 0xE3]), "你");
676    }
677
678    #[test]
679    fn decode_selector_0x14_big5() {
680        // Big5 0xA4A4 = '中'.
681        assert_eq!(decode_dvb_string(&[0x14, 0xA4, 0xA4]), "中");
682    }
683
684    /// A multi-byte trail byte in 0x80–0x9F must survive: the C1 control
685    /// filter operates on decoded code points, never on raw trail bytes.
686    /// GBK 0x8180 = '亐' (U+4E90, trail byte in the C1 range).
687    #[test]
688    fn decode_selector_0x13_gbk_trail_byte_in_c1_range() {
689        assert_eq!(decode_dvb_string(&[0x13, 0x81, 0x80]), "亐");
690    }
691
692    /// Annex A.1 two-byte control codes live at U+E080–U+E09F in the PUA
693    /// (Table A.2): U+E08A is CR/LF → space; the reserved rest is stripped.
694    /// GBK 0xABCD decodes to U+E08A; GBK 0xABC3 decodes to U+E080.
695    #[test]
696    fn two_byte_control_codes_filtered() {
697        assert_eq!(decode_dvb_string(&[0x13, 0xAB, 0xCD]), " ");
698        assert_eq!(decode_dvb_string(&[0x13, 0xAB, 0xC3]), "");
699    }
700
701    /// 0x1F consumes its 8-bit encoding_type_id; the body is undecodable
702    /// (no registered broadcast ids) and yields U+FFFD per byte.
703    #[test]
704    fn decode_selector_0x1f_encoding_type_id() {
705        let s = decode_dvb_string(&[0x1F, 0x01, 0x41, 0x42]);
706        assert_eq!(s.chars().count(), 2);
707        assert!(s.chars().all(|c| c == '\u{FFFD}'));
708    }
709
710    /// Table A.3 marks single-byte selector 0x08 reserved (no ISO 8859-12).
711    #[test]
712    fn reserved_selector_0x08_is_unsupported() {
713        let s = decode_dvb_string(&[0x08, 0x41, 0x42]);
714        assert!(s.chars().all(|c| c == '\u{FFFD}'));
715        assert_eq!(s.chars().count(), 2);
716    }
717
718    #[test]
719    fn unknown_selector_returns_replacement_characters() {
720        // Selector 0x16 is reserved for future use — each byte becomes U+FFFD.
721        let s = decode_dvb_string(&[0x16, 0xAA, 0xBB, 0xCC]);
722        assert_eq!(s.chars().count(), 3);
723        assert!(s.chars().all(|c| c == '\u{FFFD}'));
724    }
725
726    /// An unsupported ISO 8859 part number (via 0x10 extended selector) yields
727    /// U+FFFD per byte rather than Latin-1 passthrough.
728    #[test]
729    fn selector_0x10_iso_8859_1_decodes_latin1() {
730        // 0x10 0x00 0x01 → ISO/IEC 8859-1 (Latin-1): bytes are the first 256
731        // Unicode code points 1:1, so 0xE9 → 'é'. (A valid charset; must NOT be
732        // treated as unsupported / U+FFFD.)
733        let s = decode_dvb_string(&[0x10, 0x00, 0x01, 0x41, 0xE9]);
734        assert_eq!(s, "Aé");
735    }
736
737    #[test]
738    fn unsupported_iso_8859_12_yields_replacement() {
739        // 0x10 0x00 0x0C → ISO 8859-12 does not exist (reserved); unsupported
740        // parts decode to U+FFFD, not fabricated text.
741        let s = decode_dvb_string(&[0x10, 0x00, 0x0C, 0x41, 0x42]);
742        assert!(s.chars().all(|c| c == '\u{FFFD}'), "got: {s:?}");
743    }
744
745    /// Pins the GR-area single-byte mappings to ETSI EN 300 468 V1.19.1
746    /// (2025-02) Figure A.1 — "Character code table 00 - Latin alphabet with
747    /// Unicode equivalents" (PDF p. 159; vendored at
748    /// `specs/etsi_en_300_468_v01.19.01_dvb_si.pdf`).
749    #[test]
750    fn figure_a1_gr_area_single_byte_mappings() {
751        let pins: &[(u8, char)] = &[
752            (0xA0, '\u{00A0}'), // NBSP
753            (0xA1, '¡'),
754            (0xA2, '¢'),
755            (0xA3, '£'),
756            (0xA4, '\u{20AC}'), // € — DVB addition (note under Figure A.1)
757            (0xA5, '¥'),
758            (0xA7, '§'),
759            (0xA8, '\u{00A4}'), // ¤ general currency sign
760            (0xA9, '\u{2018}'), // '
761            (0xAA, '\u{201C}'), // "
762            (0xAB, '«'),
763            (0xAC, '\u{2190}'), // ←
764            (0xAD, '\u{2191}'), // ↑
765            (0xAE, '\u{2192}'), // →
766            (0xAF, '\u{2193}'), // ↓
767            (0xB0, '°'),
768            (0xB1, '±'),
769            (0xB2, '²'),
770            (0xB3, '³'),
771            (0xB4, '\u{00D7}'), // ×
772            (0xB5, 'µ'),
773            (0xB6, '¶'),
774            (0xB7, '·'),
775            (0xB8, '\u{00F7}'), // ÷
776            (0xB9, '\u{2019}'), // '
777            (0xBA, '\u{201D}'), // "
778            (0xBB, '»'),
779            (0xBC, '¼'),
780            (0xBD, '½'),
781            (0xBE, '¾'),
782            (0xBF, '¿'),
783            (0xD0, '\u{2015}'), // ―
784            (0xD1, '¹'),
785            (0xD2, '®'),
786            (0xD3, '©'),
787            (0xD4, '\u{2122}'), // ™
788            (0xD5, '\u{266A}'), // ♪
789            (0xD6, '¬'),
790            (0xD7, '\u{00A6}'), // ¦
791            (0xDC, '\u{215B}'), // ⅛
792            (0xDD, '\u{215C}'), // ⅜
793            (0xDE, '\u{215D}'), // ⅝
794            (0xDF, '\u{215E}'), // ⅞
795            (0xE0, '\u{2126}'), // Ω OHM SIGN
796            (0xE1, 'Æ'),
797            (0xE2, '\u{0110}'), // Đ
798            (0xE3, 'ª'),
799            (0xE4, '\u{0126}'), // Ħ
800            (0xE6, '\u{0132}'), // IJ
801            (0xE7, '\u{013F}'), // Ŀ
802            (0xE8, '\u{0141}'), // Ł
803            (0xE9, 'Ø'),
804            (0xEA, '\u{0152}'), // Œ
805            (0xEB, 'º'),
806            (0xEC, 'Þ'),
807            (0xED, '\u{0166}'), // Ŧ
808            (0xEE, '\u{014A}'), // Ŋ
809            (0xEF, '\u{0149}'), // ʼn
810            (0xF0, '\u{0138}'), // ĸ
811            (0xF1, 'æ'),
812            (0xF2, '\u{0111}'), // đ
813            (0xF3, 'ð'),
814            (0xF4, '\u{0127}'), // ħ
815            (0xF5, '\u{0131}'), // ı
816            (0xF6, '\u{0133}'), // ij
817            (0xF7, '\u{0140}'), // ŀ
818            (0xF8, '\u{0142}'), // ł
819            (0xF9, 'ø'),
820            (0xFA, '\u{0153}'), // œ
821            (0xFB, 'ß'),
822            (0xFC, '\u{00FE}'), // þ
823            (0xFD, '\u{0167}'), // ŧ
824            (0xFE, '\u{014B}'), // ŋ
825            (0xFF, '\u{00AD}'), // SHY soft hyphen
826        ];
827        for &(byte, want) in pins {
828            let got = decode_dvb_string(&[0x00, byte]);
829            assert_eq!(
830                got,
831                want.to_string(),
832                "byte {byte:#04x}: want {want:?} (U+{:04X}), got {got:?}",
833                want as u32
834            );
835        }
836    }
837
838    /// Bytes undefined (grey) in Figure A.1 decode to U+FFFD.
839    #[test]
840    fn figure_a1_undefined_positions_are_replacement() {
841        for byte in [0xA6u8, 0xD8, 0xD9, 0xDA, 0xDB, 0xE5] {
842            let got = decode_dvb_string(&[0x00, byte]);
843            assert_eq!(got, "\u{FFFD}", "byte {byte:#04x} should be U+FFFD");
844        }
845    }
846
847    /// C-row prefixes with precomposed entries (Figure A.1 non-spacing row).
848    #[test]
849    fn figure_a1_combining_precomposed() {
850        assert_eq!(decode_dvb_string(&[0x00, 0xCA, b'a']), "å"); // ring U+030A
851        assert_eq!(decode_dvb_string(&[0x00, 0xCA, b'A']), "Å");
852        assert_eq!(decode_dvb_string(&[0x00, 0xCF, b's']), "š"); // caron U+030C
853        assert_eq!(decode_dvb_string(&[0x00, 0xCF, b'Z']), "Ž");
854        assert_eq!(decode_dvb_string(&[0x00, 0xCE, b'e']), "ę"); // ogonek U+0328
855        assert_eq!(decode_dvb_string(&[0x00, 0xCD, b'o']), "ő"); // double acute U+030B
856        assert_eq!(decode_dvb_string(&[0x00, 0xC7, b'z']), "ż"); // dot above U+0307
857        assert_eq!(decode_dvb_string(&[0x00, 0xC5, b'a']), "ā"); // macron U+0304
858        assert_eq!(decode_dvb_string(&[0x00, 0xC6, b'g']), "ğ"); // breve U+0306
859    }
860
861    /// A defined prefix with no precomposed form falls back to
862    /// base + Unicode combining mark (canonically equivalent).
863    #[test]
864    fn figure_a1_combining_fallback_emits_base_plus_mark() {
865        assert_eq!(decode_dvb_string(&[0x00, 0xC5, b'x']), "x\u{0304}");
866    }
867
868    /// Undefined C-row prefixes (0xC0, 0xC9, 0xCC) and a dangling prefix at
869    /// end of input decode to U+FFFD.
870    #[test]
871    fn figure_a1_combining_undefined_or_dangling_prefix() {
872        assert_eq!(decode_dvb_string(&[0x00, 0xC0, b'a']), "\u{FFFD}a");
873        assert_eq!(decode_dvb_string(&[0x00, 0xC9, b'a']), "\u{FFFD}a");
874        assert_eq!(decode_dvb_string(&[0x00, 0xCC, b'a']), "\u{FFFD}a");
875        assert_eq!(decode_dvb_string(&[0x00, 0xC2]), "\u{FFFD}");
876    }
877
878    #[test]
879    fn dvb_text_decodes_with_charset_selector() {
880        let t = DvbText::new(&[0x15, 0xC3, 0xA9]); // UTF-8 selector + é
881        assert_eq!(t.decode(), "é");
882        assert_eq!(t.raw(), &[0x15, 0xC3, 0xA9]);
883        assert_eq!(&t[..], &[0x15, 0xC3, 0xA9]); // Deref
884        assert_eq!(format!("{t}"), "é");
885    }
886
887    #[test]
888    fn lang_code_as_str() {
889        assert_eq!(LangCode(*b"fre").as_str(), "fre");
890        assert_eq!(LangCode([0xFF, b'r', b'e']).as_str(), "\u{FFFD}re"); // lossy, no panic
891    }
892
893    #[cfg(feature = "serde")]
894    #[test]
895    fn dvb_text_serializes_decoded() {
896        let t = DvbText::new(&[0x15, 0xC3, 0xA9]);
897        assert_eq!(serde_json::to_string(&t).unwrap(), "\"é\"");
898    }
899
900    #[cfg(feature = "serde")]
901    #[test]
902    fn lang_code_serializes_as_string() {
903        // Serialize-only: LangCode renders as its decoded string. Parsing FROM
904        // JSON is deliberately unsupported (re-parse from wire bytes instead).
905        let lc = LangCode(*b"FRA");
906        assert_eq!(serde_json::to_string(&lc).unwrap(), "\"FRA\"");
907    }
908}