ctb_formats_encoding/
cp437.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later AND MIT
2// SPDX-License-Identifier for parts derived from codepage-437: MIT
3/*
4This file is part of Collective Toolbox, a database and document workspace and utilities.
5Copyright (C) 2026 Collective Toolbox Developers
6Contact: info@collectivetoolbox.com
7
8This program is free software: you can redistribute it and/or modify it under
9the terms of the GNU Affero General Public License as published by the Free
10Software Foundation, either version 3 of the License, or (at your option) any
11later version.
12
13This program is distributed in the hope that it will be useful, but WITHOUT ANY
14WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
16
17You should have received a copy of the GNU Affero General Public License along
18with this program.  If not, see <https://www.gnu.org/licenses/>.
19*/
20
21// Copyright (c) 2018 nabijaczleweli
22
23// See additional licensing details at end of file.
24
25// More-or-less independent implementation; used the test data and docs to create this alternative which is a bit easier to read for me but likely slower.
26
27//! Code Page 437 (DOS Latin US) character encoding and decoding utilities.
28
29#[allow(
30    unused_imports,
31    clippy::wildcard_imports,
32    reason = "Standard workspace module prelude"
33)]
34use crate::utilities::*;
35
36use std::collections::HashMap;
37use std::sync::LazyLock;
38
39use crate::mapping::SingleByteMapping;
40use crate::utilities::csv_tools::{self, CsvParseOptions};
41use ctb_formats_utilities::encoding::LowArea;
42use ctb_utilities::anyhow::anyhow;
43
44fn try_load_mapping(
45    values_path: &str,
46    variants_path: Option<&str>,
47    is_control: bool,
48) -> Result<SingleByteMapping> {
49    let mut decode_table = ['\0'; 256];
50    let mut encode_table = HashMap::new();
51
52    // 1. Initialize standard ASCII ranges
53    if is_control {
54        for i in 0..128 {
55            let byte = u8::try_from(i)?;
56            let character = char::from(byte);
57            if let Some(slot) = decode_table.get_mut(usize::from(byte)) {
58                *slot = character;
59            }
60            encode_table.insert(character, byte);
61        }
62    } else {
63        if let Some(slot) = decode_table.get_mut(0) {
64            *slot = '\0';
65        }
66        encode_table.insert('\0', 0);
67        for i in 0x20..0x7F {
68            let byte = u8::try_from(i)?;
69            let character = char::from(byte);
70            if let Some(slot) = decode_table.get_mut(usize::from(byte)) {
71                *slot = character;
72            }
73            encode_table.insert(character, byte);
74        }
75    }
76
77    // 2. Load values.tsv
78    if let Some(values_bytes) = crate::get_encoding_data(values_path) {
79        let table = csv_tools::parse_csv_reader(
80            &values_bytes,
81            CsvParseOptions {
82                has_header: true,
83                delimiter: b'\t',
84                ..Default::default()
85            },
86        )?;
87
88        for row in table.rows_iter() {
89            if let (Some(r0), Some(r1)) = (row.first(), row.get(1)) {
90                let byte = ctb_utilities::string::parse_hex_u8(r0)?;
91                let uni_code = ctb_utilities::string::parse_hex_u32(r1)?;
92                let character = char::from_u32(uni_code).ok_or_else(|| {
93                    anyhow!("Invalid Unicode code point '{r1}'")
94                })?;
95
96                if let Some(slot) = decode_table.get_mut(usize::from(byte)) {
97                    *slot = character;
98                }
99                encode_table.insert(character, byte);
100            }
101        }
102    }
103
104    // 3. Load variants.tsv if requested
105    if let Some(vpath) = variants_path {
106        if let Some(variants_bytes) = crate::get_encoding_data(vpath) {
107            let table = csv_tools::parse_csv_reader(
108                &variants_bytes,
109                CsvParseOptions {
110                    has_header: true,
111                    delimiter: b'\t',
112                    ..Default::default()
113                },
114            )?;
115
116            for row in table.rows_iter() {
117                if let (Some(r0), Some(r1)) = (row.first(), row.get(1)) {
118                    let byte = ctb_utilities::string::parse_hex_u8(r0)?;
119                    let uni_code = ctb_utilities::string::parse_hex_u32(r1)?;
120                    let character =
121                        char::from_u32(uni_code).ok_or_else(|| {
122                            anyhow!("Invalid Unicode code point '{r1}'")
123                        })?;
124
125                    // Variants only extend the encode_table, do not overwrite the decode_table
126                    encode_table.insert(character, byte);
127                }
128            }
129        }
130    }
131
132    Ok(SingleByteMapping::from_raw(decode_table, encode_table))
133}
134
135#[expect(clippy::expect_used, reason = "Better to fail early here")]
136pub(crate) static CP437_DINGBATS: LazyLock<SingleByteMapping> =
137    LazyLock::new(|| {
138        try_load_mapping(
139            "cp437/cp437_dingbats/values.tsv",
140            Some("cp437/cp437_dingbats/variants.tsv"),
141            false,
142        )
143        .expect("Failed to load CP437 dingbats mapping")
144    });
145
146#[expect(clippy::expect_used, reason = "Better to fail early here")]
147pub(crate) static CP437_DINGBATS_BASE: LazyLock<SingleByteMapping> =
148    LazyLock::new(|| {
149        try_load_mapping("cp437/cp437_dingbats/values.tsv", None, false)
150            .expect("Failed to load CP437 dingbats base mapping")
151    });
152
153#[expect(clippy::expect_used, reason = "Better to fail early here")]
154pub(crate) static CP437_CONTROL: LazyLock<SingleByteMapping> =
155    LazyLock::new(|| {
156        try_load_mapping(
157            "cp437/cp437_control/values.tsv",
158            Some("cp437/cp437_control/variants.tsv"),
159            true,
160        )
161        .expect("Failed to load CP437 control mapping")
162    });
163
164#[expect(clippy::expect_used, reason = "Better to fail early here")]
165pub(crate) static CP437_CONTROL_BASE: LazyLock<SingleByteMapping> =
166    LazyLock::new(|| {
167        try_load_mapping("cp437/cp437_control/values.tsv", None, true)
168            .expect("Failed to load CP437 control base mapping")
169    });
170
171pub(crate) fn get_mapping(
172    low_area: LowArea,
173    include_variants: bool,
174) -> &'static SingleByteMapping {
175    match (low_area, include_variants) {
176        (LowArea::Graphical, true) => &CP437_DINGBATS,
177        (LowArea::Graphical, false) => &CP437_DINGBATS_BASE,
178        (LowArea::Control, true) => &CP437_CONTROL,
179        (LowArea::Control, false) => &CP437_CONTROL_BASE,
180    }
181}
182
183#[cfg(test)]
184#[allow(
185    clippy::panic,
186    clippy::expect_used,
187    clippy::unwrap_used,
188    clippy::unwrap_in_result,
189    clippy::panic_in_result_fn,
190    clippy::indexing_slicing,
191    clippy::arithmetic_side_effects,
192    reason = "Standard repository test boilerplate"
193)]
194mod tests {
195    use super::*;
196    use ctb_formats_utilities::encoding::CharEncoding;
197
198    #[crate::ctb_test]
199    fn test_cp437_control_decoding() -> Result<()> {
200        let all_bytes = get_all_bytes()?;
201        let enc = CharEncoding::cp437_control();
202        let decoded = crate::decode(enc, &all_bytes)?;
203
204        let expected_bytes = crate::get_encoding_data(
205            "fixtures/cp437/cp437_control/all.utf8",
206        )
207        .ok_or_else(|| anyhow!("Missing all.utf8 fixture for control"))?;
208        let expected = String::from_utf8(expected_bytes)?;
209
210        assert_eq!(decoded, expected);
211        Ok(())
212    }
213
214    #[crate::ctb_test]
215    fn test_cp437_dingbats_decoding() -> Result<()> {
216        let all_bytes = get_all_bytes()?;
217        let enc = CharEncoding::cp437();
218        let decoded = crate::decode(enc, &all_bytes)?;
219
220        let expected_bytes =
221            crate::get_encoding_data("fixtures/cp437/cp437_dingbats/all.utf8")
222                .ok_or_else(|| {
223                    anyhow!("Missing all.utf8 fixture for dingbats")
224                })?;
225        let expected = String::from_utf8(expected_bytes)?;
226
227        assert_eq!(decoded, expected);
228        Ok(())
229    }
230
231    #[crate::ctb_test]
232    fn test_cp437_control_variants() -> Result<()> {
233        let enc = CharEncoding::cp437_control();
234        let variants_utf8_bytes = crate::get_encoding_data(
235            "fixtures/cp437/cp437_control/variants.utf8",
236        )
237        .ok_or_else(|| anyhow!("Missing variants.utf8 fixture for control"))?;
238        let variants_utf8 = String::from_utf8(variants_utf8_bytes)?;
239
240        let expected_cp437 = crate::get_encoding_data(
241            "fixtures/cp437/cp437_control/variants.cp437",
242        )
243        .ok_or_else(|| anyhow!("Missing variants.cp437 fixture for control"))?;
244
245        let encoded = crate::encode(enc, &variants_utf8)?;
246        assert_eq!(encoded, expected_cp437);
247        Ok(())
248    }
249
250    #[crate::ctb_test]
251    fn test_cp437_dingbats_variants() -> Result<()> {
252        let enc = CharEncoding::cp437();
253        let variants_utf8_bytes = crate::get_encoding_data(
254            "fixtures/cp437/cp437_dingbats/variants.utf8",
255        )
256        .ok_or_else(|| anyhow!("Missing variants.utf8 fixture for dingbats"))?;
257        let variants_utf8 = String::from_utf8(variants_utf8_bytes)?;
258
259        let expected_cp437 = crate::get_encoding_data(
260            "fixtures/cp437/cp437_dingbats/variants.cp437",
261        )
262        .ok_or_else(|| {
263            anyhow!("Missing variants.cp437 fixture for dingbats")
264        })?;
265
266        let encoded = crate::encode(enc, &variants_utf8)?;
267        assert_eq!(encoded, expected_cp437);
268        Ok(())
269    }
270
271    #[crate::ctb_test]
272    fn test_remap() -> Result<()> {
273        let mut mapping = CP437_DINGBATS.clone();
274        let square_root_or_checkmark = 0xFB;
275
276        // Before remapping: 0xFB -> '√'
277        assert_eq!(mapping.chr(square_root_or_checkmark), "√");
278        assert_eq!(mapping.asc("√"), Some(square_root_or_checkmark));
279
280        // Remap to check mark '✓'
281        mapping.remap(square_root_or_checkmark, '✓');
282
283        // After remapping: 0xFB -> '✓'
284        assert_eq!(mapping.chr(square_root_or_checkmark), "✓");
285        assert_eq!(mapping.asc("✓"), Some(square_root_or_checkmark));
286        assert_eq!(mapping.decode(&[square_root_or_checkmark])?, "✓");
287        assert_eq!(mapping.encode("✓")?, vec![square_root_or_checkmark]);
288
289        // Remapping should not have affected original
290        assert_eq!(CP437_DINGBATS.chr(square_root_or_checkmark), "√");
291        Ok(())
292    }
293
294    #[crate::ctb_test]
295    fn test_chr_asc() -> Result<()> {
296        let enc_dingbats = CharEncoding::cp437();
297        let enc_control = CharEncoding::cp437_control();
298
299        for code in 0u8..=255 {
300            let character = crate::chr(enc_dingbats, code);
301            let retrieved_code = crate::asc(enc_dingbats, &character);
302            assert_eq!(Some(code), retrieved_code);
303        }
304
305        for code in 0u8..=255 {
306            let character = crate::chr(enc_control, code);
307            let retrieved_code = crate::asc(enc_control, &character);
308            assert_eq!(Some(code), retrieved_code);
309        }
310
311        assert_eq!(Some(65), crate::asc(enc_dingbats, "A"));
312        assert_eq!("A", crate::chr(enc_dingbats, 65));
313        assert_eq!(Some(65), crate::asc(enc_control, "A"));
314        assert_eq!("A", crate::chr(enc_control, 65));
315
316        Ok(())
317    }
318}
319
320/*
321Licensing notice for parts derived from codepage-437 (https://crates.io/crates/codepage-437):
322======
323
324The MIT License (MIT)
325
326Copyright (c) 2018 nabijaczleweli
327
328Permission is hereby granted, free of charge, to any person obtaining a copy
329of this software and associated documentation files (the "Software"), to deal
330in the Software without restriction, including without limitation the rights
331to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
332copies of the Software, and to permit persons to whom the Software is
333furnished to do so, subject to the following conditions:
334
335The above copyright notice and this permission notice shall be included in all
336copies or substantial portions of the Software.
337
338THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
339IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
340FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
341AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
342LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
343OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
344SOFTWARE.
345*/