ctb_formats_encoding/
mapping.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Unified table-driven single-byte character mapping and encoding abstractions.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use ctb_utilities::anyhow::anyhow;
30use std::collections::HashMap;
31
32pub use ctb_formats_utilities::encoding::{
33    CharEncoding, LineEndingFormat, LineEndingKind, LineEndingOption, LowArea,
34    NeoRegion, TerminationMode,
35};
36
37/// A 256-entry bidirectional mapping between single bytes and Unicode characters.
38#[derive(Debug, Clone)]
39pub struct SingleByteMapping {
40    decode_table: [char; 256],
41    encode_table: HashMap<char, u8>,
42}
43
44impl SingleByteMapping {
45    /// Creates a mapping from raw decode and encode tables.
46    #[must_use]
47    pub const fn from_raw(
48        decode_table: [char; 256],
49        encode_table: HashMap<char, u8>,
50    ) -> Self {
51        Self {
52            decode_table,
53            encode_table,
54        }
55    }
56
57    /// Decodes a single byte to its corresponding Unicode character.
58    pub fn decode_byte(&self, code: u8) -> Result<char> {
59        self.decode_table
60            .get(usize::from(code))
61            .copied()
62            .ok_or_else(|| anyhow!("Invalid byte {code}"))
63    }
64
65    /// Returns the character string for a single byte.
66    #[expect(
67        clippy::expect_used,
68        reason = "u8 index is 0..=255 which always fits in 256-entry decode_table"
69    )]
70    #[must_use]
71    pub fn chr(&self, code: u8) -> String {
72        self.decode_table
73            .get(usize::from(code))
74            .copied()
75            .expect("u8 fits in 256-entry decode table")
76            .to_string()
77    }
78
79    /// Returns the byte value for the first character of a string, if mappable.
80    pub fn asc(&self, s: &str) -> Option<u8> {
81        let first_char = s.chars().next()?;
82        self.encode_table.get(&first_char).copied()
83    }
84
85    /// Encodes a Unicode string into a vector of bytes.
86    pub fn encode(&self, input: &str) -> Result<Vec<u8>> {
87        let mut result = Vec::with_capacity(input.len());
88        for c in input.chars() {
89            if let Some(&byte) = self.encode_table.get(&c) {
90                result.push(byte);
91            } else {
92                return Err(anyhow!(
93                    "Encoding error: unmappable character '{c}'"
94                ));
95            }
96        }
97        Ok(result)
98    }
99
100    /// Decodes a slice of bytes into a Unicode string.
101    #[expect(
102        clippy::expect_used,
103        reason = "u8 index is 0..=255 which always fits in 256-entry decode_table"
104    )]
105    pub fn decode(&self, input: &[u8]) -> Result<String> {
106        let mut result = String::with_capacity(input.len());
107        for &byte in input {
108            result.push(
109                self.decode_table
110                    .get(usize::from(byte))
111                    .copied()
112                    .expect("u8 fits in 256-entry decode table"),
113            );
114        }
115        Ok(result)
116    }
117
118    /// Remaps a single byte to a new Unicode character in both tables.
119    #[expect(
120        clippy::expect_used,
121        reason = "u8 index is 0..=255 which always fits in 256-entry decode_table"
122    )]
123    pub fn remap(&mut self, byte: u8, character: char) {
124        let idx = usize::from(byte);
125        let old_char = self
126            .decode_table
127            .get(idx)
128            .copied()
129            .expect("u8 fits in 256-entry decode table");
130        if let Some(slot) = self.decode_table.get_mut(idx) {
131            *slot = character;
132        }
133
134        if self.encode_table.get(&old_char) == Some(&byte) {
135            self.encode_table.remove(&old_char);
136        }
137        self.encode_table.insert(character, byte);
138    }
139}
140
141/// Returns the static `SingleByteMapping` for the specified `CharEncoding`.
142#[must_use]
143pub fn mapping(enc: CharEncoding) -> &'static SingleByteMapping {
144    match enc {
145        CharEncoding::Cp437 {
146            low_area,
147            include_variants,
148        } => crate::cp437::get_mapping(low_area, include_variants),
149        CharEncoding::Neo { region, low_area } => {
150            crate::neo::get_mapping(region, low_area)
151        }
152        CharEncoding::MacRoman => &crate::standard::MACROMAN_MAPPING,
153        CharEncoding::Windows1252 => &crate::standard::WINDOWS_1252_MAPPING,
154        CharEncoding::Iso88591 => &crate::standard::ISO_8859_1_MAPPING,
155        CharEncoding::Ascii => &crate::standard::ASCII_MAPPING,
156    }
157}
158
159/// Encodes a Unicode string using the specified character encoding.
160pub fn encode(enc: CharEncoding, input: &str) -> Result<Vec<u8>> {
161    mapping(enc).encode(input)
162}
163
164/// Encodes a Unicode string with optional line ending conversion.
165pub fn encode_with_options(
166    enc: CharEncoding,
167    input: &str,
168    line_ending_opt: LineEndingOption,
169) -> Result<Vec<u8>> {
170    let converted = crate::line_endings::apply_line_ending_option(
171        input,
172        enc,
173        line_ending_opt,
174    )?;
175    mapping(enc).encode(&converted)
176}
177
178/// Decodes a byte slice into a Unicode string using the specified character encoding.
179pub fn decode(enc: CharEncoding, input: &[u8]) -> Result<String> {
180    mapping(enc).decode(input)
181}
182
183/// Decodes a byte slice into a Unicode string with optional line ending conversion.
184pub fn decode_with_options(
185    enc: CharEncoding,
186    input: &[u8],
187    line_ending_opt: LineEndingOption,
188) -> Result<String> {
189    let decoded = mapping(enc).decode(input)?;
190    crate::line_endings::apply_line_ending_option(
191        &decoded,
192        enc,
193        line_ending_opt,
194    )
195}
196
197/// Transcodes bytes from one character encoding to another with optional line ending conversion.
198pub fn transcode(
199    input: &[u8],
200    src_enc: CharEncoding,
201    dst_enc: CharEncoding,
202    line_ending_opt: LineEndingOption,
203) -> Result<Vec<u8>> {
204    let decoded = decode(src_enc, input)?;
205    encode_with_options(dst_enc, &decoded, line_ending_opt)
206}
207
208/// Returns the string representation of a character code in the specified encoding.
209#[must_use]
210pub fn chr(enc: CharEncoding, code: u8) -> String {
211    mapping(enc).chr(code)
212}
213
214/// Returns the character corresponding to a byte in the specified encoding.
215pub fn chr_char(enc: CharEncoding, code: u8) -> Result<char> {
216    mapping(enc).decode_byte(code)
217}
218
219/// Returns the byte value for the first character of a string in the specified encoding.
220#[must_use]
221pub fn asc(enc: CharEncoding, s: &str) -> Option<u8> {
222    mapping(enc).asc(s)
223}
224
225#[cfg(test)]
226#[allow(
227    clippy::panic,
228    clippy::expect_used,
229    clippy::unwrap_used,
230    clippy::unwrap_in_result,
231    clippy::panic_in_result_fn,
232    clippy::indexing_slicing,
233    clippy::arithmetic_side_effects,
234    reason = "Standard repository test boilerplate"
235)]
236mod tests {
237    use super::*;
238
239    #[crate::ctb_test]
240    fn test_unified_cp437_encoding() -> Result<()> {
241        let enc = CharEncoding::cp437();
242        let encoded = encode(enc, "A")?;
243        assert_eq!(encoded, vec![65]);
244        let decoded = decode(enc, &[65])?;
245        assert_eq!(decoded, "A");
246        assert_eq!(chr(enc, 65), "A");
247        assert_eq!(asc(enc, "A"), Some(65));
248        Ok(())
249    }
250
251    #[crate::ctb_test]
252    fn test_encode_decode_with_options() -> Result<()> {
253        let mac = CharEncoding::mac_roman();
254        let unix_text = "Hello\nWorld\n";
255
256        // encode with EncodingDefault on MacRoman should produce CR line endings (0x0D)
257        let mac_bytes = encode_with_options(
258            mac,
259            unix_text,
260            LineEndingOption::EncodingDefault,
261        )?;
262        assert_eq!(mac_bytes, b"Hello\rWorld\r");
263
264        // decode with EncodingDefault on Windows1252 should convert to CRLF
265        let win = CharEncoding::windows_1252();
266        let win_text = decode_with_options(
267            win,
268            b"Hello\nWorld\n",
269            LineEndingOption::EncodingDefault,
270        )?;
271        assert_eq!(win_text, "Hello\r\nWorld\r\n");
272
273        // Transcode from Windows-1252 (with CRLF) to MacRoman with EncodingDefault -> CR (0x0D)
274        let win_bytes = b"Hello\r\nWorld\r\n";
275        let transcoded =
276            transcode(win_bytes, win, mac, LineEndingOption::EncodingDefault)?;
277        assert_eq!(transcoded, b"Hello\rWorld\r");
278
279        Ok(())
280    }
281
282    #[crate::ctb_test]
283    fn test_format_id_and_dc_char_integration() -> Result<()> {
284        use ctb_utilities::format_id::{
285            DC_ALPHA_SMART_NEO_LOW_CTL_US, DC_ALPHA_SMART_NEO_LOW_GR_US,
286            DC_LINE_ENDING_CR_LF, DC_MAC_ROMAN, FormatId,
287        };
288
289        // Neo variants to dedicated FormatIds and Dcs
290        let neo_gr_us = CharEncoding::neo(NeoRegion::Us, LowArea::Graphical);
291        assert_eq!(neo_gr_us.to_format_id(), FormatId::AlphaSmartNeoLowGrUs);
292        assert_eq!(neo_gr_us.dc_char(), Some(DC_ALPHA_SMART_NEO_LOW_GR_US));
293        assert_eq!(
294            CharEncoding::from_format_id(FormatId::AlphaSmartNeoLowGrUs),
295            Some(neo_gr_us)
296        );
297
298        let neo_ctl_us = CharEncoding::neo(NeoRegion::Us, LowArea::Control);
299        assert_eq!(neo_ctl_us.to_format_id(), FormatId::AlphaSmartNeoLowCtlUs);
300        assert_eq!(neo_ctl_us.dc_char(), Some(DC_ALPHA_SMART_NEO_LOW_CTL_US));
301
302        // Simple encodings
303        let mac = CharEncoding::mac_roman();
304        assert_eq!(mac.to_format_id(), FormatId::MacRoman);
305        assert_eq!(mac.dc_char(), Some(DC_MAC_ROMAN));
306        assert_eq!(CharEncoding::from_format_id(FormatId::MacRoman), Some(mac));
307
308        let iso = CharEncoding::iso_8859_1();
309        assert_eq!(iso.to_format_id(), FormatId::Iso88591);
310        assert_eq!(CharEncoding::from_format_id(FormatId::Iso88591), Some(iso));
311
312        // Line ending formats to FormatIds and Dcs
313        let crlf = LineEndingFormat::terminated(LineEndingKind::CrLf);
314        assert_eq!(crlf.to_format_id(), FormatId::LineEndingCrLf);
315        assert_eq!(crlf.dc_char(), Some(DC_LINE_ENDING_CR_LF));
316        assert_eq!(
317            LineEndingFormat::from_format_id(FormatId::LineEndingCrLf),
318            Some(crlf)
319        );
320
321        let cr_sep = LineEndingFormat::separated(LineEndingKind::Cr);
322        assert_eq!(cr_sep.to_format_id(), FormatId::LineSeparatorCr);
323        assert_eq!(
324            LineEndingFormat::from_format_id(FormatId::LineSeparatorCr),
325            Some(cr_sep)
326        );
327
328        Ok(())
329    }
330}