ctb_formats_eite/
dc.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//! Direct-connect data structures and table definitions for EITE.
21
22pub mod data;
23
24use crate::utilities::*;
25
26use anyhow::{Result, anyhow, ensure};
27
28use crate::dc::data::{
29    DCDATA_BIDI_CLASS_COL, DCDATA_CASING_COL, DCDATA_COMBINING_CLASS_COL,
30    DCDATA_COMPLEX_TRAITS_COL, DCDATA_DESCRIPTION_COL, DCDATA_ID_COL,
31    DCDATA_NAME_COL, DCDATA_SCRIPT_COL, DCDATA_TYPE_COL, dc_data_lookup_by_id,
32    dc_data_lookup_by_value, dc_dataset_length, is_dc_dataset,
33};
34use crate::util::string::substring_bug_compatible;
35use ctb_formats_base64::{
36    bytes_to_standard_base64, decimal_to_standard_base64,
37    standard_base64_to_bytes, standard_base64_to_decimal,
38};
39
40use ctb_formats_dcdata::DcCharExt;
41pub use ctb_formats_dcdata::dc::{
42    DC_BASE64_END, DC_BASE64_PADDING, DC_BASE64_START,
43    DC_END_ENCAPSULATION_BINARY, DC_END_ENCAPSULATION_UTF8, DC_ESCAPE,
44    DC_REPLACEMENT_UNAVAIL_DC, DC_REPLACEMENT_UNAVAIL_UNICODE,
45    DC_START_ENCAPSULATION_BINARY, DC_START_ENCAPSULATION_UTF8, DcChar,
46};
47pub use ctb_formats_dcdata::dc_number_minimal::is_dc_base64_encapsulation_char;
48
49/* ===== Dc classification & queries ===== */
50
51pub fn is_known_dc(v: u32) -> Result<bool> {
52    let short_id =
53        usize::try_from(v).context("Failed to convert Dc ID to usize")?;
54    Ok(ctb_formats_dcdata::get_short_dc_defn(short_id).is_some())
55}
56
57pub fn maximum_known_short_dc() -> Result<usize> {
58    Ok(ctb_formats_dcdata::maximum_known_short_dc())
59}
60
61/// Return true if Dc should be treated as a newline (coarse heuristic).
62pub fn dc_is_newline(dc: u32) -> bool {
63    // Copied literal list from original: [119,120,121,240,294,295]
64    matches!(dc, 119 | 120 | 121 | 240 | 294 | 295)
65}
66
67/// True if general category 'Zs'.
68pub fn dc_is_space(dc: u32) -> Result<bool> {
69    ensure!(is_known_dc(dc)?, "Unknown Dc {dc}");
70    Ok(dc_get_type(dc)? == "Zs")
71}
72
73/// True if printable (excludes line/para separators, categories starting with
74/// '!' or 'C').
75pub fn dc_is_printable(dc: u32) -> Result<bool> {
76    ensure!(is_known_dc(dc)?, "Unknown Dc {dc}");
77    let t = dc_get_type(dc)?;
78    if t == "Zl" || t == "Zp" {
79        return Ok(false);
80    }
81    // Reason for fallback: when type classification string t is empty, space char ' ' serves as non-control fallback, allowing function to return true.
82    let general = t.chars().next().unwrap_or(' ');
83    if general == '!' || general == 'C' {
84        return Ok(false);
85    }
86    Ok(true)
87}
88
89pub fn dc_is_el_code(dc: u32) -> Result<bool> {
90    ensure!(is_known_dc(dc)?, "Unknown Dc {dc}");
91    let script = dc_get_script(dc)?;
92    Ok(script.get(0..3) == Some("EL "))
93}
94
95pub fn dc_get_el_class(dc: u32) -> Result<String> {
96    ensure!(is_known_dc(dc)?, "Unknown Dc {dc}");
97    let script = dc_get_script(dc)?;
98    substring_bug_compatible(&script, 3, -1)
99}
100
101// ---------------------------------------------------------------------------
102// Field access
103// ---------------------------------------------------------------------------
104
105/// Generic field fetch (dataset “`DcData`”, by numeric Dc id and original JS field number).
106pub fn dc_get_field(dc: u32, field_number: usize) -> Result<String> {
107    let dc_str = dc.to_string();
108    dc_data_lookup_by_value("DcData", DCDATA_ID_COL, &dc_str, field_number)
109        .map_err(|e| anyhow!("dc_get_field: {e}"))
110}
111
112/// Name (field 1).
113pub fn dc_get_name(dc: u32) -> Result<String> {
114    dc_get_field(dc, DCDATA_NAME_COL)
115}
116
117/// Combining class (field 2).
118pub fn dc_get_combining_class(dc: u32) -> Result<String> {
119    dc_get_field(dc, DCDATA_COMBINING_CLASS_COL)
120}
121
122/// Bidi class (field 3).
123pub fn dc_get_bidi_class(dc: u32) -> Result<String> {
124    dc_get_field(dc, DCDATA_BIDI_CLASS_COL)
125}
126
127/// Casing (field 4).
128pub fn dc_get_casing(dc: u32) -> Result<String> {
129    dc_get_field(dc, DCDATA_CASING_COL)
130}
131
132/// Type (field 5).
133pub fn dc_get_type(dc: u32) -> Result<String> {
134    dc_get_field(dc, DCDATA_TYPE_COL)
135}
136
137/// Script (field 6).
138pub fn dc_get_script(dc: u32) -> Result<String> {
139    dc_get_field(dc, DCDATA_SCRIPT_COL)
140}
141
142/// Complex traits (field 7).
143pub fn dc_get_complex_traits(dc: u32) -> Result<String> {
144    dc_get_field(dc, DCDATA_COMPLEX_TRAITS_COL)
145}
146
147/// Description (field 8).
148pub fn dc_get_description(dc: u32) -> Result<String> {
149    dc_get_field(dc, DCDATA_DESCRIPTION_COL)
150}
151
152/// Return length of the primary '`DcData`' dataset.
153pub fn get_dc_count() -> Result<usize> {
154    Ok(ctb_formats_dcdata::get_dc_count())
155}
156
157/// Extract an entire column (by field number) from a dataset.
158pub fn dc_get_column(
159    dataset: &str,
160    field_number: usize,
161) -> Result<Vec<String>> {
162    if !is_dc_dataset(dataset) {
163        return Err(anyhow!("dc_get_column: unknown dataset '{dataset}'"));
164    }
165    let len = dc_dataset_length(dataset)?;
166    let mut out = Vec::with_capacity(len);
167    for row in 0..len {
168        let v = dc_data_lookup_by_id(dataset, row, field_number)
169            .map_err(|e| anyhow!("dc_get_column: {e}"))?;
170        out.push(v);
171    }
172    Ok(out)
173}
174
175/// Look up a Dc (document character) mapping into a specific output format.
176///
177/// Equivalent of dcGetMappingToFormat(intDc, strFormat) in the original.
178/// Uses dataset path "mappings/to/{format}" and retrieves field 1 (second column)
179/// of the row number equal to the Dc value.
180///
181/// Returns an empty string if lookup fails (mimicking loosely the JS behavior),
182/// but logs an error via Result if the underlying dataset access errors.
183pub fn dc_get_mapping_to_format(dc: u32, format: &str) -> Result<String> {
184    let dataset = format!("mappings/to/{format}");
185    // Underlying call may error if dataset/indices are invalid:
186    match dc_data_lookup_by_id(
187        &dataset,
188        usize::try_from(dc).context("Could not get usize from Dc")?,
189        1,
190    ) {
191        Ok(s) => Ok(s),
192        Err(e) => Err(anyhow!("dc_get_mapping_to_format failed: {e}")),
193    }
194}
195
196/// Expand a Unicode or Dc general category code to human-readable form.
197fn format_dc_type(type_code: &str) -> String {
198    let desc = describe_general_category(type_code);
199    if desc == type_code {
200        type_code.to_string()
201    } else {
202        format!("{type_code} ({desc})")
203    }
204}
205
206/// Expand a Unicode or Dc general category code to human-readable form.
207fn describe_general_category(type_code: &str) -> String {
208    match type_code {
209        "!Cx" => "Control: Dc special".to_string(),
210        other => ctb_formats_utilities::describe_general_category(other),
211    }
212}
213
214pub fn is_dc_base64_encapsulation_character(dc: u32) -> bool {
215    is_dc_base64_encapsulation_char(DcChar::from_short(dc))
216}
217
218pub fn string_to_dc_encapsulated_utf8(input: &str) -> Result<Vec<u32>> {
219    bytes_as_dc_encapsulated_utf8(input.as_bytes())
220}
221
222pub fn bytes_as_dc_encapsulated_utf8(input: &[u8]) -> Result<Vec<u32>> {
223    let mut out: Vec<u32> = Vec::new();
224
225    out.push(DC_START_ENCAPSULATION_UTF8.to_short()?);
226    let mut raw = bytes_to_dc_encapsulated_raw(input)?;
227    out.append(&mut raw);
228    out.push(DC_END_ENCAPSULATION_UTF8.to_short()?);
229
230    Ok(out)
231}
232
233pub fn bytes_to_dc_encapsulated_binary(input: &[u8]) -> Result<Vec<u32>> {
234    let mut out: Vec<u32> = Vec::new();
235
236    out.push(DC_START_ENCAPSULATION_BINARY.to_short()?);
237    for ch in ctb_formats_dcdata::dc_number_minimal::u128_to_dc_number_chars(
238        u128::try_from(input.len())?,
239    ) {
240        out.extend(ch.to_short_vec());
241    }
242    let mut raw = bytes_to_dc_encapsulated_raw(input)?;
243    out.append(&mut raw);
244    out.push(DC_END_ENCAPSULATION_BINARY.to_short()?);
245
246    Ok(out)
247}
248
249pub fn bytes_to_dc_encapsulated_raw(bytes: &[u8]) -> Result<Vec<u32>> {
250    let decimal = standard_base64_to_decimal(bytes_to_standard_base64(bytes))
251        .context("Failed to encode base64")?;
252
253    let padding_short = DC_BASE64_PADDING.to_short()?;
254    let start_short = DC_BASE64_START.to_short()?;
255
256    let mut dc_encoded: Vec<u32> = Vec::new();
257    for b64 in decimal {
258        if b64 == 64 {
259            // Padding
260            dc_encoded.push(padding_short);
261        } else {
262            dc_encoded.push(start_short.saturating_add(u32::from(b64)));
263        }
264    }
265
266    Ok(dc_encoded)
267}
268
269pub fn dc_encapsulated_raw_to_bytes(input: &[u32]) -> Result<Vec<u8>> {
270    let padding_short = DC_BASE64_PADDING.to_short()?;
271    let start_short = DC_BASE64_START.to_short()?;
272    let mut out: Vec<u8> = Vec::new();
273
274    // let input_as_u8: Vec<u8> = input.iter().map(|&x| x as u8).collect();
275    let mut dc_decoded: Vec<u8> = Vec::new();
276    for dc in input {
277        if *dc == padding_short {
278            dc_decoded.push(64);
279            continue;
280        }
281        if !is_dc_base64_encapsulation_character(*dc) {
282            return Err(anyhow!(
283                "Invalid Dc {dc} in encapsulated raw sequence"
284            ));
285        }
286        dc_decoded.push(u8::try_from(dc.saturating_sub(start_short))?);
287    }
288
289    let base64 = decimal_to_standard_base64(dc_decoded)
290        .context("Failed to translate Dcs to base64")?;
291
292    out.extend_from_slice(&standard_base64_to_bytes(&base64)?);
293
294    Ok(out)
295}
296
297#[cfg(test)]
298#[allow(
299    clippy::panic,
300    clippy::expect_used,
301    clippy::unwrap_used,
302    clippy::unwrap_in_result,
303    clippy::panic_in_result_fn,
304    clippy::indexing_slicing,
305    clippy::arithmetic_side_effects,
306    reason = "Standard repository test boilerplate"
307)]
308mod tests {
309
310    use crate::utilities::{assert_vec_u8_ok_eq, assert_vec_u32_eq};
311
312    use super::*;
313
314    #[crate::ctb_test]
315    fn test_dc_newline_list() {
316        for dc in [119, 120, 121, 240, 294, 295] {
317            assert!(dc_is_newline(dc));
318        }
319        assert!(!dc_is_newline(118));
320    }
321
322    #[crate::ctb_test]
323    fn test_dc_bidi_class_120() {
324        assert_eq!(
325            dc_get_bidi_class(120).expect("Bidi class was incorrect"),
326            "B"
327        );
328    }
329
330    #[crate::ctb_test]
331    fn test_dc_is_space() -> Result<()> {
332        assert!(is_known_dc(18)?);
333        assert_eq!(dc_get_type(18).expect("Dc type was incorrect"), "Zs");
334        assert!(dc_is_space(18).expect("Dc 18 is a space"));
335        Ok(())
336    }
337
338    #[crate::ctb_test]
339    fn test_format_dc_predicates() {
340        // These tests rely on dataset-driven predicates. If datasets are not
341        // loaded in the test harness, fail early and print a clear message.
342
343        // dc_is_printable(21) expected true
344        match dc_is_printable(21) {
345            Ok(v) => assert!(v, "Expected dc 21 printable"),
346            Err(e) => panic!("Failed to run dc_is_printable(21): {e}"),
347        }
348
349        // dc_is_printable(231) expected false (Not(dcIsPrintable(231)))
350        match dc_is_printable(231) {
351            Ok(v) => assert!(!v, "Expected dc 231 NOT printable"),
352            Err(e) => panic!("Failed to run dc_is_printable(231): {e}"),
353        }
354
355        // dc_is_newline(120) expected true
356        assert!(
357            dc_is_newline(120),
358            "Expected dc 120 to be recognized as newline"
359        );
360    }
361
362    #[crate::ctb_test]
363    fn test_bytes_to_dc_encapsulated_raw() -> Result<()> {
364        let input = b"Hello, world!";
365        // Base64: SGVsbG8sIHdvcmxkIQ==
366        // Decimal: 18 6 21 44 27 6
367        //          60 44 8 7 29 47
368        //          28 38 49 36 8 16
369        //          64 64
370        let expected = vec![
371            145, 133, 148, 171, 154, 133, // comment to assuage rustfmt
372            187, 171, 135, 134, 156, 174, //
373            155, 165, 176, 163, 135, 143, //
374            195, 195,
375        ];
376        let result = bytes_to_dc_encapsulated_raw(input)?;
377        assert_vec_u32_eq(&expected, &result);
378        Ok(())
379    }
380
381    #[crate::ctb_test]
382    fn test_dc_encapsulated_raw_to_bytes() {
383        let input = vec![
384            145, 133, 148, 171, 154, 133, // comment to assuage rustfmt
385            187, 171, 135, 134, 156, 174, //
386            155, 165, 176, 163, 135, 143, //
387            195, 195,
388        ];
389        let expected = b"Hello, world!";
390        let result = dc_encapsulated_raw_to_bytes(&input);
391        assert_vec_u8_ok_eq(expected, result);
392    }
393
394    #[crate::ctb_test]
395    fn test_string_to_dc_encapsulated_utf8() -> Result<()> {
396        let input = "Hello, world!";
397        // Base64: SGVsbG8sIHdvcmxkIQ==
398        // Decimal: 18 6 21 44 27 6
399        //          60 44 8 7 29 47
400        //          28 38 49 36 8 16
401        //          64 64
402        let expected = vec![
403            191, //
404            145, 133, 148, 171, 154, 133, //
405            187, 171, 135, 134, 156, 174, //
406            155, 165, 176, 163, 135, 143, //
407            195, 195, //
408            192,
409        ];
410        let result = string_to_dc_encapsulated_utf8(input)?;
411        assert_eq!(result, expected);
412        let result = bytes_as_dc_encapsulated_utf8(input.as_bytes())?;
413        assert_eq!(result, expected);
414        Ok(())
415    }
416
417    #[crate::ctb_test]
418    fn test_bytes_to_dc_encapsulated_binary() -> Result<()> {
419        let input = b"Hello, world!";
420        // Base64: SGVsbG8sIHdvcmxkIQ==
421        // Decimal: 18 6 21 44 27 6
422        //          60 44 8 7 29 47
423        //          28 38 49 36 8 16
424        //          64 64
425        let mut expected = vec![203];
426        for ch in
427            ctb_formats_dcdata::dc_number_minimal::u128_to_dc_number_chars(13)
428        {
429            expected.extend(ch.to_short_vec());
430        }
431        expected.extend([
432            145, 133, 148, 171, 154, 133, //
433            187, 171, 135, 134, 156, 174, //
434            155, 165, 176, 163, 135, 143, //
435            195, 195, //
436            204,
437        ]);
438        let result = bytes_to_dc_encapsulated_binary(input)?;
439        assert_eq!(result, expected);
440        Ok(())
441    }
442}