ctb_formats_encoding/
neo.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//! Neo character encoding and decoding utilities.
21//!
22//! Provides bidirectional character mappings for AlphaSmart Neo devices with
23//! US, Ukrainian Mac, and Ukrainian PC layouts. By default, the low character
24//! area (0x00..=0x1F) uses graphical symbols (the common device character set),
25//! with an optional control character mode available. Documentation of the
26//! control character encoding (with graphical 0x0) was found commented out in
27//! the `AlphaSync` driver.
28//!
29//! `AlphaWord` uses a more complex file format/encoding. FIXME update this comment with details from `AlphaSync`.
30
31#[allow(
32    unused_imports,
33    clippy::wildcard_imports,
34    reason = "Standard workspace module prelude"
35)]
36use crate::utilities::*;
37
38use ctb_utilities::anyhow::anyhow;
39use ctb_utilities::string::parse_hex_codepoints;
40use std::collections::HashMap;
41use std::sync::LazyLock;
42
43use crate::mapping::SingleByteMapping;
44pub use ctb_formats_utilities::encoding::{LowArea, NeoRegion};
45
46/// Loads a `SingleByteMapping` table for the specified region and low-area mode.
47pub fn try_load_mapping(
48    region: NeoRegion,
49    low_area: LowArea,
50) -> Result<SingleByteMapping> {
51    let low_file = match low_area {
52        LowArea::Graphical => "neo/low-graphical.csv",
53        LowArea::Control => "neo/low-control.csv",
54    };
55    let high_file = match region {
56        NeoRegion::Us => "neo/us.csv",
57        NeoRegion::UaMac => "neo/ua-mac.csv",
58        NeoRegion::UaPc => "neo/ua-pc.csv",
59    };
60
61    let low_bytes = crate::get_encoding_data(low_file)
62        .ok_or_else(|| anyhow!("Missing Neo low-area data file: {low_file}"))?;
63    let high_bytes = crate::get_encoding_data(high_file).ok_or_else(|| {
64        anyhow!("Missing Neo high-area data file: {high_file}")
65    })?;
66
67    let low_str = std::str::from_utf8(&low_bytes)?;
68    let high_str = std::str::from_utf8(&high_bytes)?;
69
70    let low_chars = parse_hex_codepoints(low_str)?;
71    let high_chars = parse_hex_codepoints(high_str)?;
72
73    if low_chars.len() != 32 {
74        return Err(anyhow!(
75            "Expected 32 low-area characters, got {}",
76            low_chars.len()
77        ));
78    }
79    if high_chars.len() != 224 {
80        return Err(anyhow!(
81            "Expected 224 high-area characters, got {}",
82            high_chars.len()
83        ));
84    }
85
86    let mut decode_table = ['\0'; 256];
87    let mut encode_table = HashMap::new();
88
89    for (i, &ch) in low_chars.iter().enumerate() {
90        let byte = u8::try_from(i)?;
91        if let Some(slot) = decode_table.get_mut(usize::from(byte)) {
92            *slot = ch;
93        }
94        encode_table.entry(ch).or_insert(byte);
95    }
96
97    for (i, &ch) in high_chars.iter().enumerate() {
98        let byte = u8::try_from(i.saturating_add(32))?;
99        if let Some(slot) = decode_table.get_mut(usize::from(byte)) {
100            *slot = ch;
101        }
102        encode_table.entry(ch).or_insert(byte);
103    }
104
105    Ok(SingleByteMapping::from_raw(decode_table, encode_table))
106}
107
108/// Static instance for Neo US layout with graphical low area (the default/usual encoding).
109#[expect(clippy::expect_used, reason = "Better to fail early here")]
110pub(crate) static NEO_US: LazyLock<SingleByteMapping> = LazyLock::new(|| {
111    try_load_mapping(NeoRegion::Us, LowArea::Graphical)
112        .expect("Failed to load Neo US (Graphical) mapping")
113});
114
115/// Static instance for Neo US layout with control low area (graphical 0x0 byte).
116#[expect(clippy::expect_used, reason = "Better to fail early here")]
117pub(crate) static NEO_US_CONTROL: LazyLock<SingleByteMapping> =
118    LazyLock::new(|| {
119        try_load_mapping(NeoRegion::Us, LowArea::Control)
120            .expect("Failed to load Neo US (Control) mapping")
121    });
122
123/// Static instance for Neo Ukrainian Mac layout with graphical low area.
124#[expect(clippy::expect_used, reason = "Better to fail early here")]
125pub(crate) static NEO_UA_MAC: LazyLock<SingleByteMapping> =
126    LazyLock::new(|| {
127        try_load_mapping(NeoRegion::UaMac, LowArea::Graphical)
128            .expect("Failed to load Neo UA-Mac (Graphical) mapping")
129    });
130
131/// Static instance for Neo Ukrainian Mac layout with control low area.
132#[expect(clippy::expect_used, reason = "Better to fail early here")]
133pub(crate) static NEO_UA_MAC_CONTROL: LazyLock<SingleByteMapping> =
134    LazyLock::new(|| {
135        try_load_mapping(NeoRegion::UaMac, LowArea::Control)
136            .expect("Failed to load Neo UA-Mac (Control) mapping")
137    });
138
139/// Static instance for Neo Ukrainian PC layout with graphical low area.
140#[expect(clippy::expect_used, reason = "Better to fail early here")]
141pub(crate) static NEO_UA_PC: LazyLock<SingleByteMapping> =
142    LazyLock::new(|| {
143        try_load_mapping(NeoRegion::UaPc, LowArea::Graphical)
144            .expect("Failed to load Neo UA-PC (Graphical) mapping")
145    });
146
147/// Static instance for Neo Ukrainian PC layout with control low area.
148#[expect(clippy::expect_used, reason = "Better to fail early here")]
149pub(crate) static NEO_UA_PC_CONTROL: LazyLock<SingleByteMapping> =
150    LazyLock::new(|| {
151        try_load_mapping(NeoRegion::UaPc, LowArea::Control)
152            .expect("Failed to load Neo UA-PC (Control) mapping")
153    });
154
155/// Returns the static `SingleByteMapping` for the specified region and low area.
156#[must_use]
157pub(crate) fn get_mapping(
158    region: NeoRegion,
159    low_area: LowArea,
160) -> &'static SingleByteMapping {
161    match (region, low_area) {
162        (NeoRegion::Us, LowArea::Graphical) => &NEO_US,
163        (NeoRegion::Us, LowArea::Control) => &NEO_US_CONTROL,
164        (NeoRegion::UaMac, LowArea::Graphical) => &NEO_UA_MAC,
165        (NeoRegion::UaMac, LowArea::Control) => &NEO_UA_MAC_CONTROL,
166        (NeoRegion::UaPc, LowArea::Graphical) => &NEO_UA_PC,
167        (NeoRegion::UaPc, LowArea::Control) => &NEO_UA_PC_CONTROL,
168    }
169}
170
171#[cfg(test)]
172#[allow(
173    clippy::panic,
174    clippy::expect_used,
175    clippy::unwrap_used,
176    clippy::unwrap_in_result,
177    clippy::panic_in_result_fn,
178    clippy::indexing_slicing,
179    clippy::arithmetic_side_effects,
180    reason = "Standard repository test boilerplate"
181)]
182mod tests {
183    use super::*;
184    use ctb_formats_utilities::encoding::CharEncoding;
185
186    #[crate::ctb_test]
187    fn test_neo_us_graphical_low_area() -> Result<()> {
188        let enc = CharEncoding::neo_us();
189        // In graphical mode, 0x00 is ■ (0x25a0), 0x01 is δ (0x03b4), 0x02 is Δ (0x0394)
190        assert_eq!(crate::chr(enc, 0x00), "■");
191        assert_eq!(crate::chr(enc, 0x01), "δ");
192        assert_eq!(crate::chr(enc, 0x02), "Δ");
193
194        assert_eq!(crate::asc(enc, "■"), Some(0x00));
195        assert_eq!(crate::asc(enc, "δ"), Some(0x01));
196        assert_eq!(crate::asc(enc, "Δ"), Some(0x02));
197        Ok(())
198    }
199
200    #[crate::ctb_test]
201    fn test_neo_us_control_low_area() -> Result<()> {
202        let enc = CharEncoding::neo(NeoRegion::Us, LowArea::Control);
203        // In control mode, 0x00 is ■ (0x25a0), 0x01 is '\u{1}', 0x02 is '\u{2}'
204        assert_eq!(crate::chr(enc, 0x00), "■");
205        assert_eq!(crate::chr(enc, 0x01), "\u{1}");
206        assert_eq!(crate::chr(enc, 0x02), "\u{2}");
207
208        assert_eq!(crate::asc(enc, "\u{1}"), Some(0x01));
209        assert_eq!(crate::asc(enc, "\u{2}"), Some(0x02));
210        Ok(())
211    }
212
213    #[crate::ctb_test]
214    fn test_neo_us_roundtrip() -> Result<()> {
215        let enc = CharEncoding::neo_us();
216        let text = "Hello, World! 123 - α β Ω";
217        let encoded = crate::encode(enc, text)?;
218        let decoded = crate::decode(enc, &encoded)?;
219        assert_eq!(decoded, text);
220        Ok(())
221    }
222
223    #[crate::ctb_test]
224    fn test_neo_ua_mac_and_pc() -> Result<()> {
225        let ua_mac = CharEncoding::neo(NeoRegion::UaMac, LowArea::Graphical);
226        let ua_pc = CharEncoding::neo(NeoRegion::UaPc, LowArea::Graphical);
227
228        // Byte 0x22 in UA Mac: 0x0404 ('Є')
229        assert_eq!(crate::chr(ua_mac, 0x22), "Є");
230        assert_eq!(crate::asc(ua_mac, "Є"), Some(0x22));
231
232        // Byte 0x22 in UA PC: 0x0404 ('Є')
233        assert_eq!(crate::chr(ua_pc, 0x22), "Є");
234        assert_eq!(crate::asc(ua_pc, "Є"), Some(0x22));
235
236        // Roundtrip encode/decode on UA Mac
237        let ua_text = "Привіт, світ!";
238        let encoded = crate::encode(ua_mac, ua_text)?;
239        let decoded = crate::decode(ua_mac, &encoded)?;
240        assert_eq!(decoded, ua_text);
241
242        // Roundtrip encode/decode on UA PC
243        let encoded_pc = crate::encode(ua_pc, ua_text)?;
244        let decoded_pc = crate::decode(ua_pc, &encoded_pc)?;
245        assert_eq!(decoded_pc, ua_text);
246        Ok(())
247    }
248
249    #[crate::ctb_test]
250    fn test_neo_remapping() -> Result<()> {
251        let mut mapping = NEO_US.clone();
252        // Remap byte 0x24 ($) to € (0x20ac)
253        assert_eq!(mapping.chr(0x24), "$");
254        mapping.remap(0x24, '€');
255        assert_eq!(mapping.chr(0x24), "€");
256        assert_eq!(mapping.asc("€"), Some(0x24));
257        assert_eq!(mapping.decode(&[0x24])?, "€");
258        assert_eq!(mapping.encode("€")?, vec![0x24]);
259        Ok(())
260    }
261}