ctb_formats_dcstring/converters/
dcts.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//! Implementation of Format 461 (Dcts: DcText short).
21//!
22//! Like DcText, but Document Characters (Dcs) are short by default:
23//! - `@123@` = short Dc 123 (`SHORT_DC_REGION_START + 123`)
24//! - `a` = literal Unicode `a`
25//! - `@@` = codepoint 64 (`@`)
26//! - `@l123@` = long Dc 123
27//! - `@L123@` = local node reference (short Dc 296 followed by Dc number 123)
28//! - `@u123a@` = Unicode codepoint U+123A (hex)
29//! - `@f123@` = Format 123 (`FORMAT_REGION_START + 123`)
30
31#[allow(
32    unused_imports,
33    clippy::wildcard_imports,
34    reason = "Standard workspace module prelude"
35)]
36use crate::utilities::*;
37
38use anyhow::Result;
39use ctb_formats_dctf::decode_dctf;
40use ctb_formats_utilities::{ConversionOutput, FormatLog};
41use ctb_storage_minimal::global_graph_layout::{
42    FORMAT_REGION_END, FORMAT_REGION_START, SHORT_DC_REGION_END,
43    SHORT_DC_REGION_START, UNICODE_REGION_END,
44};
45use ctb_storage_minimal::shorthand::DcShorthand;
46
47use super::dctext::{
48    DcList, dcarray_to_dclist, dclist_to_dcarray, dclist_to_dcutf,
49    dctf_to_dclist, dcutf_to_dclist,
50};
51use crate::DcString;
52use crate::dc_char::DcChar;
53use crate::dc_number::{integer_to_dc_number_global, read_dc_number_global};
54use crate::dc_str::DcStr;
55
56/// Parses a Dcts document (`&[u8]`) directly into a `DcString`.
57///
58/// Plain text characters become their corresponding Unicode codepoints (`0..=0x10FFFF`).
59/// Tokens enclosed in `@...@` are parsed according to their prefix:
60/// - `@@`: codepoint 64 (`@`)
61/// - `@<number>@`: short Dc ID (e.g. `@123@` -> `SHORT_DC_REGION_START + 123`)
62/// - `@l<number>@`: long Dc ID (e.g. `@l123@` -> `123`)
63/// - `@L<number>@`: local node reference (short Dc 296 + Dc number `<number>`)
64/// - `@u<hex>@`: Unicode codepoint (e.g. `@u123a@` -> `U+123A`)
65/// - `@f<number>@`: Format ID (e.g. `@f123@` -> `FORMAT_REGION_START + 123`)
66///
67/// # Errors
68/// Returns an error if the document cannot be parsed into a `DcString`.
69pub fn dcts_to_dcstring(document: &[u8]) -> Result<ConversionOutput<DcString>> {
70    let mut log = FormatLog::default();
71    let mut dc_string = DcString::with_capacity(document.len());
72    let mut i = 0usize;
73
74    while i < document.len() {
75        let Some(slice) = document.get(i..) else {
76            break;
77        };
78        let Some(&first_byte) = slice.first() else {
79            break;
80        };
81
82        if first_byte == b'@' {
83            if let Some(rest) = slice.get(1..) {
84                if let Some(end_rel) = rest.iter().position(|&b| b == b'@') {
85                    if let Some(token_bytes) = rest.get(..end_rel) {
86                        if let Ok(token_str) = std::str::from_utf8(token_bytes)
87                        {
88                            if token_str.is_empty() {
89                                // @@ token represents @ (codepoint 64)
90                                dc_string.push(DcChar(64u128));
91                                i = i.saturating_add(2);
92                                continue;
93                            }
94
95                            if let Ok(shorthand) = DcShorthand::parse(token_str)
96                            {
97                                match shorthand {
98                                    DcShorthand::Local(int_val) => {
99                                        let malachite_val =
100                                            malachite::Integer::from(int_val);
101                                        match integer_to_dc_number_global(
102                                            &malachite_val,
103                                        ) {
104                                            Ok(dc_num_gids) => {
105                                                dc_string.push(DcChar(
106                                                    1_114_408u128,
107                                                ));
108                                                for gid in dc_num_gids {
109                                                    dc_string.push(DcChar(gid));
110                                                }
111                                                i = i
112                                                    .saturating_add(2)
113                                                    .saturating_add(end_rel);
114                                                continue;
115                                            }
116                                            Err(e) => {
117                                                log.warn(&format!(
118                                                    "Failed to encode Dc number for local node @{token_str}@: {e}"
119                                                ));
120                                            }
121                                        }
122                                    }
123                                    other => {
124                                        if let Ok(gid) = other.to_global_id() {
125                                            dc_string.push(DcChar(gid));
126                                            i = i
127                                                .saturating_add(2)
128                                                .saturating_add(end_rel);
129                                            continue;
130                                        }
131                                    }
132                                }
133                            } else {
134                                log.warn(&format!(
135                                    "Unrecognized token @{token_str}@ in Dcts"
136                                ));
137                            }
138                        }
139                    }
140                }
141            }
142        }
143
144        if let Some((codepoint, size)) = decode_dctf(slice) {
145            dc_string.push(DcChar(codepoint));
146            i = i.saturating_add(size);
147        } else {
148            dc_string.push(DcChar(u128::from(first_byte)));
149            i = i.saturating_add(1);
150        }
151    }
152
153    Ok(ConversionOutput::new(dc_string, log))
154}
155
156/// Parses a Dcts document (`&[u8]`) into a `DcList` (`Vec<u128>`).
157///
158/// # Errors
159/// Returns an error if the document cannot be parsed into a `DcList`.
160pub fn dcts_to_dclist(document: &[u8]) -> Result<ConversionOutput<DcList>> {
161    let out = dcts_to_dcstring(document)?;
162    Ok(ConversionOutput::new(out.result.to_dclist(), out.log))
163}
164
165pub use ctb_formats_dcdata::dcts::{
166    DctsOptions, dclist_to_dcts, dclist_to_dcts_string_with_options,
167    dclist_to_dcts_with_options,
168};
169
170/// Serializes a `DcStr` to Dcts format bytes (`Vec<u8>`).
171#[must_use]
172pub fn dcstring_to_dcts(s: &DcStr) -> Vec<u8> {
173    let dclist = s.to_dclist();
174    dclist_to_dcts(&dclist)
175}
176
177/// Converts a Dcts document to `DcMstring`.
178pub fn dcts_to_dcmstring(
179    bytes: &[u8],
180) -> Result<(crate::DcMstring, FormatLog)> {
181    dcts_to_dcmstring_with_options(bytes, false)
182}
183
184/// Converts a Dcts document to `DcMstring`, optionally in permissive mode.
185pub fn dcts_to_dcmstring_with_options(
186    bytes: &[u8],
187    permissive: bool,
188) -> Result<(crate::DcMstring, FormatLog)> {
189    let conv = dcts_to_dcstring(bytes)?;
190    if !permissive && conv.log.has_errors() {
191        bail!(
192            "Invalid Dcts token(s): {}",
193            conv.log.get_errors().join("; ")
194        );
195    }
196    let policy = if permissive {
197        crate::DcProjectionPolicy::forgiving()
198    } else {
199        crate::DcProjectionPolicy::strict()
200    };
201    let doc =
202        crate::DcMstring::from_dc_string_with_policy(&conv.result, &policy)?;
203    Ok((doc, conv.log))
204}
205
206/// Converts a `DcMstring` to Dcts bytes.
207pub fn dcmstring_to_dcts(
208    doc: &crate::DcMstring,
209) -> Result<(Vec<u8>, FormatLog)> {
210    let dc_string = super::document_dc_string(doc)?;
211    let bytes = dcstring_to_dcts(&dc_string);
212    Ok((bytes, FormatLog::default()))
213}
214
215/// Converts Dcts format bytes to DcTF format bytes.
216///
217/// # Errors
218/// Returns an error if the document cannot be parsed into a `DcString`.
219pub fn dcts_to_dctf(document: Vec<u8>) -> Result<Vec<u8>> {
220    let out = dcts_to_dcstring(&document)?;
221    out.log.auto_log();
222    Ok(out.result.into_bytes())
223}
224
225/// Converts DcTF format bytes to Dcts format bytes.
226#[must_use]
227pub fn dctf_to_dcts(document: Vec<u8>) -> Vec<u8> {
228    let dclist = dctf_to_dclist(&document);
229    dclist_to_dcts(&dclist)
230}
231
232/// Converts Dcts format bytes to legacy DcUtf format bytes.
233///
234/// # Errors
235/// Returns an error if the document cannot be parsed into a `DcString`.
236pub fn dcts_to_dcutf(document: Vec<u8>) -> Result<Vec<u8>> {
237    let out = dcts_to_dcstring(&document)?;
238    out.log.auto_log();
239    Ok(dclist_to_dcutf(&out.result.to_dclist()))
240}
241
242/// Converts legacy DcUtf format bytes to Dcts format bytes.
243#[must_use]
244pub fn dcutf_to_dcts(document: Vec<u8>) -> Vec<u8> {
245    let dclist = dcutf_to_dclist(&document);
246    dclist_to_dcts(&dclist)
247}
248
249/// Converts an EITE DcArray (short Dcs, `&[u32]`) to Dcts format (`Vec<u8>`).
250///
251/// # Errors
252/// Returns an error if the array cannot be converted.
253pub fn dcarray_to_dcts(dc_array: &[u32]) -> Result<ConversionOutput<Vec<u8>>> {
254    let conv = dcarray_to_dclist(dc_array)?;
255    let text_bytes = dclist_to_dcts(&conv.result);
256    Ok(ConversionOutput::new(text_bytes, conv.log))
257}
258
259/// Converts a Dcts document (`&[u8]`) to an EITE DcArray (short Dcs, `Vec<u32>`).
260///
261/// # Errors
262/// Returns an error if the document cannot be converted.
263pub fn dcts_to_dcarray(document: &[u8]) -> Result<ConversionOutput<Vec<u32>>> {
264    let conv = dcts_to_dcstring(document)?;
265    let array_conv = dclist_to_dcarray(&conv.result.to_dclist())?;
266    let mut total_log = conv.log;
267    total_log.merge(&array_conv.log);
268    Ok(ConversionOutput::new(array_conv.result, total_log))
269}
270
271#[cfg(test)]
272#[allow(
273    clippy::panic,
274    clippy::expect_used,
275    clippy::unwrap_used,
276    clippy::unwrap_in_result,
277    clippy::panic_in_result_fn,
278    clippy::indexing_slicing,
279    clippy::arithmetic_side_effects,
280    reason = "Standard repository test boilerplate"
281)]
282mod tests {
283    use super::*;
284
285    #[crate::ctb_test]
286    fn test_dcts_tokens() {
287        // @123@ = short Dc 123 (1114112 + 123 = 1114235)
288        // a = literal Unicode a (97)
289        // @@ = literal @ (64)
290        // @l123@ = long Dc 123 (123)
291        // @L42@ = local node 42
292        // @u123a@ = U+123A (4666)
293        // @f123@ = format 123 (2228224 + 123 = 2228347)
294        let input = b"a @123@ @@ @l123@ @L42@ @u123a@ @f123@";
295        let conv = dcts_to_dcstring(input).expect("parse dcts");
296        assert!(!conv.log.has_warnings());
297        let list = conv.result.to_dclist();
298
299        // Verify the decoded IDs
300        assert_eq!(list.first().copied(), Some(97)); // 'a'
301        assert_eq!(list.get(1).copied(), Some(32)); // ' '
302        assert_eq!(list.get(2).copied(), Some(1_114_235)); // short Dc 123
303        assert_eq!(list.get(3).copied(), Some(32)); // ' '
304        assert_eq!(list.get(4).copied(), Some(64)); // '@@'
305        assert_eq!(list.get(5).copied(), Some(32)); // ' '
306        assert_eq!(list.get(6).copied(), Some(123)); // long Dc 123
307        assert_eq!(list.get(7).copied(), Some(32)); // ' '
308        assert_eq!(list.get(8).copied(), Some(1_114_408)); // local node prefix
309        // local node Dc number follows...
310        assert_eq!(list.get(list.len().saturating_sub(3)).copied(), Some(4666)); // U+123A
311        assert_eq!(list.get(list.len().saturating_sub(2)).copied(), Some(32)); // ' '
312        assert_eq!(list.last().copied(), Some(2_228_347)); // format 123
313    }
314
315    #[crate::ctb_test]
316    fn test_dcts_serialization_roundtrip() {
317        let input = "a @123@ @@ @l100000000000@ @L42@ \u{123a} @f123@";
318        let conv = dcts_to_dcstring(input.as_bytes()).expect("parse dcts");
319        assert!(!conv.log.has_warnings());
320
321        let serialized = dcstring_to_dcts(&conv.result);
322        let s = String::from_utf8(serialized).expect("valid utf-8");
323        assert_eq!(s, input);
324    }
325
326    #[crate::ctb_test]
327    fn test_dcts_u_token_serializes_to_char_or_surrogate() {
328        // @u61@ parses to 97 ('a'), which serializes as literal 'a'
329        let conv = dcts_to_dcstring(b"@u61@").expect("parse");
330        assert_eq!(conv.result.to_dclist(), vec![97]);
331        let out = dcstring_to_dcts(&conv.result);
332        assert_eq!(String::from_utf8(out).unwrap(), "a");
333
334        // Surrogate codepoints cannot be represented as char, so serialize as @u...
335        let conv_surr = dcts_to_dcstring(b"@ud800@").expect("parse surrogate");
336        assert_eq!(conv_surr.result.to_dclist(), vec![0xd800]);
337        let out_surr = dcstring_to_dcts(&conv_surr.result);
338        assert_eq!(String::from_utf8(out_surr).unwrap(), "@ud800@");
339    }
340
341    #[crate::ctb_test]
342    fn test_dcts_dcarray_conversions() {
343        let original_dcarray = vec![0, 1, 18, 50, 200, 297];
344        let conv = dcarray_to_dcts(&original_dcarray).expect("to dcts");
345        assert!(!conv.log.has_warnings());
346        assert_eq!(
347            String::from_utf8(conv.result.clone()).unwrap(),
348            "@0@@1@@18@@50@@200@@297@"
349        );
350
351        let back = dcts_to_dcarray(&conv.result).expect("back to dcarray");
352        assert!(!back.log.has_warnings());
353        assert_eq!(back.result, original_dcarray);
354    }
355
356    #[crate::ctb_test]
357    fn test_dcts_dcstring_and_dcutf_roundtrip() {
358        let input = "hello @123@ @f461@ @L7@ world";
359        let out = dcts_to_dcstring(input.as_bytes()).expect("dcstring");
360        assert!(!out.log.has_warnings());
361
362        let roundtrip_bytes = dcstring_to_dcts(&out.result);
363        assert_eq!(String::from_utf8(roundtrip_bytes).unwrap(), input);
364
365        let dcutf = dcts_to_dcutf(input.as_bytes().to_vec()).unwrap();
366        let roundtrip_from_dcutf = dcutf_to_dcts(dcutf);
367        assert_eq!(String::from_utf8(roundtrip_from_dcutf).unwrap(), input);
368    }
369
370    #[crate::ctb_test]
371    fn test_dcts_warnings_on_invalid_tokens() {
372        // Invalid hex in @u...
373        let conv = dcts_to_dcstring(b"@uzzz@").expect("parse");
374        assert!(conv.log.has_warnings());
375
376        // Unicode codepoint > 0x10FFFF
377        let conv2 = dcts_to_dcstring(b"@u110000@").expect("parse");
378        assert!(conv2.log.has_warnings());
379
380        // Invalid format number
381        let conv3 = dcts_to_dcstring(b"@fxyz@").expect("parse");
382        assert!(conv3.log.has_warnings());
383
384        // Invalid long Dc
385        let conv4 = dcts_to_dcstring(b"@lxyz@").expect("parse");
386        assert!(conv4.log.has_warnings());
387
388        // Uppercase @U... and @F... are not defined in specification
389        let conv5 = dcts_to_dcstring(b"@U123@").expect("parse");
390        assert!(conv5.log.has_warnings());
391
392        let conv6 = dcts_to_dcstring(b"@F123@").expect("parse");
393        assert!(conv6.log.has_warnings());
394    }
395}