ctb_formats_eite/dc/
data.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 and data table definitions for EITE format systems.
21
22use crate::utilities::*;
23
24use std::{collections::HashMap, sync::LazyLock};
25
26use anyhow::{Context, Result, anyhow};
27
28use crate::exceptions::DC_DATA_NO_RESULT_EXCEPTION;
29use crate::json;
30
31pub const DCDATA_ID_COL: usize = 0;
32pub const DCDATA_NAME_COL: usize = 1;
33pub const DCDATA_COMBINING_CLASS_COL: usize = 2;
34/// Bidi class column index.
35pub const DCDATA_BIDI_CLASS_COL: usize = 3;
36pub const DCDATA_CASING_COL: usize = 4;
37/// General category column index
38pub const DCDATA_TYPE_COL: usize = 5;
39/// Script column index.
40pub const DCDATA_SCRIPT_COL: usize = 6;
41pub const DCDATA_COMPLEX_TRAITS_COL: usize = 7;
42pub const DCDATA_DESCRIPTION_COL: usize = 8;
43
44pub const DC_FORMATS_ID_COL: usize = 0;
45pub const DC_FORMATS_NAME_COL: usize = 1;
46pub const DC_FORMATS_EXTENSION_COL: usize = 2;
47pub const DC_FORMATS_IMPORT_SUPPORT_COL: usize = 3;
48pub const DC_FORMATS_EXPORT_SUPPORT_COL: usize = 4;
49pub const DC_FORMATS_TEST_COVERAGE_COL: usize = 5;
50pub const DC_FORMATS_TYPE_COL: usize = 6;
51pub const DC_FORMATS_LABEL_COL: usize = 7;
52pub const DC_FORMATS_VARIANT_TYPES_COL: usize = 8;
53pub const DC_FORMATS_COMMENTS_COL: usize = 9;
54
55pub struct EiteData {
56    // Data / datasets
57    datasets: Vec<String>,
58    datasets_loaded: bool,
59    pub data: HashMap<String, Vec<Vec<String>>>, // dataset name -> rows (including header + trailing newline row)
60}
61
62impl EiteData {
63    pub fn new() -> Result<Self> {
64        let mut data = HashMap::new();
65        let mut loaded_datasets = Vec::new();
66
67        for dataset_name in list_dc_datasets() {
68            if dataset_name == "DcData" {
69                let rows = ctb_formats_dcdata::get_eite_dc_data_rows().to_vec();
70                data.insert(dataset_name.to_string(), rows);
71                loaded_datasets.push(dataset_name.to_string());
72                continue;
73            }
74
75            let path = format!("{dataset_name}.csv");
76            // Try to load the asset
77            let dataset_bytes = crate::get_eite_data(&path)
78                .with_context(|| format!("asset not found: {path}"))?;
79            let mut rdr =
80                csv::Reader::from_reader(std::io::Cursor::new(dataset_bytes));
81            let mut rows = Vec::new();
82            for result in rdr.records() {
83                match result {
84                    Ok(record) => {
85                        // record is a csv::StringRecord, convert to Vec<String>
86                        rows.push(
87                            record
88                                .iter()
89                                .map(std::string::ToString::to_string)
90                                .collect(),
91                        );
92                    }
93                    Err(e) => {
94                        anyhow::bail!(
95                            "Error parsing row in dataset {dataset_name}: {e}"
96                        );
97                    }
98                }
99            }
100            data.insert(dataset_name.to_string(), rows);
101            loaded_datasets.push(dataset_name.to_string());
102        }
103
104        Ok(Self {
105            datasets: loaded_datasets,
106            datasets_loaded: true,
107            data,
108        })
109    }
110
111    pub fn json(&self) -> String {
112        json!(self.data).to_string()
113    }
114
115    /// Returns total rows excluding header.
116    fn dc_dataset_length(&self, dataset: &str) -> Result<usize> {
117        let rows = self
118            .data
119            .get(dataset)
120            .with_context(|| format!("dataset not loaded: {dataset}"))?;
121        if dataset == "DcData" {
122            Ok(rows.len())
123        } else {
124            Ok(rows.len().saturating_sub(2))
125        }
126    }
127
128    fn dc_data_get_column(
129        &self,
130        dataset: &str,
131        col_num: usize,
132    ) -> Result<Vec<String>> {
133        let rows = self
134            .data
135            .get(dataset)
136            .with_context(|| format!("dataset not loaded: {dataset}"))?;
137        let mut out = Vec::new();
138        for row in rows.iter().take(rows.len()) {
139            if let Some(v) = row.get(col_num) {
140                out.push(v.clone());
141            }
142        }
143        Ok(out)
144    }
145
146    /// rowNum is zero-based for content rows (header skipped).
147    /// If out of range (beyond trailing sentinel) returns UUID sentinel constant.
148    fn dc_data_lookup_by_id(
149        &self,
150        dataset: &str,
151        row_num: usize,
152        field_num: usize,
153    ) -> Result<String> {
154        let rows = self
155            .data
156            .get(dataset)
157            .ok_or_else(|| anyhow!("dataset not loaded: {dataset}"))?;
158
159        if row_num >= rows.len() {
160            return Err(anyhow!(DC_DATA_NO_RESULT_EXCEPTION.to_string()));
161        }
162
163        let row = rows
164            .get(row_num)
165            .ok_or_else(|| anyhow!("index out of bounds"))?;
166        let value = row
167            .get(field_num)
168            .cloned()
169            .ok_or_else(|| anyhow!(DC_DATA_NO_RESULT_EXCEPTION.to_string()))?;
170
171        Ok(value)
172    }
173
174    /// Returns first match or sentinel UUID if none.
175    fn dc_data_lookup_by_value(
176        &self,
177        dataset: &str,
178        filter_field: usize,
179        filter_value: &str,
180        desired_field: usize,
181    ) -> Result<String> {
182        let rows = self
183            .data
184            .get(dataset)
185            .ok_or_else(|| anyhow!("dataset not loaded: {dataset}"))?;
186
187        for row in rows {
188            if row.get(filter_field).is_some_and(|s| s == filter_value) {
189                let value =
190                    row.get(desired_field).cloned().ok_or_else(|| {
191                        anyhow!(DC_DATA_NO_RESULT_EXCEPTION.to_string())
192                    })?;
193                return Ok(value);
194            }
195        }
196        Err(anyhow!(DC_DATA_NO_RESULT_EXCEPTION.to_string()))
197    }
198
199    /// All matches.
200    fn dc_data_filter_by_value(
201        &self,
202        dataset: &str,
203        filter_field: usize,
204        filter_value: &str,
205        desired_field: usize,
206    ) -> Result<Vec<String>> {
207        let rows = self
208            .data
209            .get(dataset)
210            .with_context(|| format!("dataset not loaded: {dataset}"))?;
211        let mut out = Vec::new();
212        for row in rows.iter().take(rows.len()) {
213            if row.get(filter_field).is_some_and(|s| s == filter_value) {
214                if let Some(v) = row.get(desired_field) {
215                    out.push(v.clone());
216                }
217            }
218        }
219        Ok(out)
220    }
221
222    fn dc_data_filter_by_value_greater(
223        &self,
224        dataset: &str,
225        filter_field: usize,
226        filter_value: i32,
227        desired_field: usize,
228    ) -> Result<Vec<String>> {
229        let rows = self
230            .data
231            .get(dataset)
232            .with_context(|| format!("dataset not loaded: {dataset}"))?;
233        let mut out = Vec::new();
234        for row in rows.iter().take(rows.len()) {
235            if let Some(cell) = row.get(filter_field) {
236                // Reason for fallback: empty whitespace cells fall back to raw cell string for parse failure
237                let first_token =
238                    cell.split_whitespace().next().unwrap_or(cell.as_str());
239                if let Ok(v) = first_token.parse::<i32>() {
240                    if v > filter_value {
241                        if let Some(d) = row.get(desired_field) {
242                            out.push(d.clone());
243                        }
244                    }
245                }
246            }
247        }
248        Ok(out)
249    }
250}
251
252// Lazy static instance
253static EITE_DATA: LazyLock<Result<EiteData>> = LazyLock::new(EiteData::new);
254
255fn get_eite_data() -> Result<&'static EiteData> {
256    EITE_DATA
257        .as_ref()
258        .map_err(|e| anyhow!("Failed to initialize EITE_DATA: {e:?}"))
259}
260
261/// Static list of known Dc datasets (mirrors original JS array).
262pub fn list_dc_datasets() -> Vec<&'static str> {
263    vec![
264        "DcData",
265        "formats",
266        "mappings/from/ascii",
267        "mappings/from/unicode",
268        "mappings/to/html",
269        "mappings/to/lang_en",
270        "mappings/to/unicode",
271    ]
272}
273
274pub fn json() -> Result<String> {
275    Ok(get_eite_data()?.json())
276}
277
278/// Returns true if the provided dataset name is one of the known Dc datasets.
279pub fn is_dc_dataset(name: &str) -> bool {
280    list_dc_datasets().iter().any(|s| s == &name)
281}
282
283pub fn dc_dataset_length(dataset: &str) -> Result<usize> {
284    get_eite_data()?.dc_dataset_length(dataset)
285}
286
287pub fn dc_data_get_column(
288    dataset: &str,
289    col_num: usize,
290) -> Result<Vec<String>> {
291    get_eite_data()?.dc_data_get_column(dataset, col_num)
292}
293
294pub fn dc_data_lookup_by_id(
295    dataset: &str,
296    row_num: usize,
297    field_num: usize,
298) -> Result<String> {
299    get_eite_data()?.dc_data_lookup_by_id(dataset, row_num, field_num)
300}
301
302pub fn dc_data_lookup_by_value(
303    dataset: &str,
304    filter_field: usize,
305    filter_value: &str,
306    desired_field: usize,
307) -> Result<String> {
308    get_eite_data()?.dc_data_lookup_by_value(
309        dataset,
310        filter_field,
311        filter_value,
312        desired_field,
313    )
314}
315
316pub fn dc_data_lookup_by_dc_in_col_0(
317    dataset: &str,
318    dc: u32,
319    desired_field: usize,
320) -> Result<String> {
321    dc_data_lookup_by_value(dataset, 0, &dc.to_string(), desired_field)
322}
323
324pub fn dc_data_filter_by_value(
325    dataset: &str,
326    filter_field: usize,
327    filter_value: &str,
328    desired_field: usize,
329) -> Result<Vec<String>> {
330    get_eite_data()?.dc_data_filter_by_value(
331        dataset,
332        filter_field,
333        filter_value,
334        desired_field,
335    )
336}
337
338pub fn dc_data_filter_by_value_greater(
339    dataset: &str,
340    filter_field: usize,
341    filter_value: i32,
342    desired_field: usize,
343) -> Result<Vec<String>> {
344    get_eite_data()?.dc_data_filter_by_value_greater(
345        dataset,
346        filter_field,
347        filter_value,
348        desired_field,
349    )
350}
351
352#[cfg(test)]
353#[allow(
354    clippy::panic,
355    clippy::expect_used,
356    clippy::unwrap_used,
357    clippy::unwrap_in_result,
358    clippy::panic_in_result_fn,
359    clippy::indexing_slicing,
360    clippy::arithmetic_side_effects,
361    reason = "Standard repository test boilerplate"
362)]
363mod tests {
364    use crate::{
365        dc::{get_dc_count, maximum_known_short_dc},
366        formats::is_format,
367    };
368
369    use super::*;
370
371    #[crate::ctb_test]
372    fn test_data_loaded() -> Result<()> {
373        let dc_count = get_dc_count()?;
374        let max_dc = maximum_known_short_dc()?;
375        assert_eq!(dc_dataset_length("DcData")?, dc_count);
376        assert!(dc_count <= max_dc.saturating_add(1));
377        assert!(max_dc >= 308);
378        assert!(is_format("unicode"));
379        assert!(is_format("utf8"));
380        Ok(())
381    }
382
383    #[crate::ctb_test]
384    fn test_list_dc_datasets_contains_expected() {
385        let list = list_dc_datasets();
386        assert!(list.contains(&"DcData"));
387        assert!(list.contains(&"mappings/to/html"));
388        assert!(!list.contains(&"nonexistent_dataset_xyz"));
389    }
390}