ctb_formats_dcdata/
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 Dcts (DcText short) serialization.
21//!
22//! Encodes sequences of Document Character (Dc) IDs to canonical Dcts text
23//! representation:
24//! - Plain text characters become literal Unicode (except `@` which becomes `@@`).
25//! - Short Dcs are formatted as `@{id}@`.
26//! - Formats are formatted as `@f{id}@`.
27//! - Unicode escapes outside standard scalar characters are `@u{hex}@`.
28//! - Local node references (Dc 296 followed by a numeral) are `@L{number}@`.
29//! - Long Dcs are `@l{id}@`.
30
31#[allow(
32    unused_imports,
33    clippy::wildcard_imports,
34    reason = "Standard workspace module prelude"
35)]
36use crate::utilities::*;
37
38use ctb_storage_minimal::global_graph_layout::{
39    FORMAT_REGION_END, FORMAT_REGION_START, SHORT_DC_REGION_END,
40    SHORT_DC_REGION_START, UNICODE_REGION_END,
41};
42
43use crate::dc_number_minimal::read_dc_number_u128;
44
45/// Options for Dcts serialization.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
47pub struct DctsOptions {
48    /// When true, format Unicode control characters (e.g. 0..=0x1F, 0x7F..=0x9F)
49    /// using `@u{hex}@` syntax instead of emitting raw control characters.
50    pub escape_control_chars: bool,
51}
52
53/// Serializes a sequence of Document Character IDs (`&[u128]`) to a Dcts `String`
54/// using the specified formatting options.
55#[must_use]
56pub fn dclist_to_dcts_string_with_options(
57    dclist: &[u128],
58    options: DctsOptions,
59) -> String {
60    let mut output = String::new();
61    let mut i = 0usize;
62
63    while i < dclist.len() {
64        let Some(&dcid) = dclist.get(i) else { break };
65
66        if dcid == 64 {
67            output.push_str("@@");
68        } else if dcid <= UNICODE_REGION_END {
69            if let Ok(cp) = u32::try_from(dcid) {
70                if let Some(ch) = char::from_u32(cp) {
71                    if options.escape_control_chars && ch.is_control() {
72                        output.push_str(&format!("@u{cp:x}@"));
73                    } else {
74                        output.push(ch);
75                    }
76                } else {
77                    output.push_str(&format!("@u{cp:x}@"));
78                }
79            } else {
80                output.push_str(&format!("@u{dcid:x}@"));
81            }
82        } else if dcid == 1_114_408 {
83            if let Some(rest) = dclist.get(i.saturating_add(1)..) {
84                if let Ok((int_val, consumed)) = read_dc_number_u128(rest) {
85                    output.push_str(&format!("@L{int_val}@"));
86                    i = i.saturating_add(1).saturating_add(consumed);
87                    continue;
88                }
89            }
90            output.push_str("@296@");
91        } else if (SHORT_DC_REGION_START..=SHORT_DC_REGION_END).contains(&dcid)
92        {
93            let short_id = dcid.saturating_sub(SHORT_DC_REGION_START);
94            output.push_str(&format!("@{short_id}@"));
95        } else if (FORMAT_REGION_START..=FORMAT_REGION_END).contains(&dcid) {
96            let fmt_id = dcid.saturating_sub(FORMAT_REGION_START);
97            output.push_str(&format!("@f{fmt_id}@"));
98        } else {
99            output.push_str(&format!("@l{dcid}@"));
100        }
101        i = i.saturating_add(1);
102    }
103    output
104}
105
106/// Serializes a sequence of Document Character IDs (`&[u128]`) to Dcts format
107/// bytes using the specified options.
108#[must_use]
109pub fn dclist_to_dcts_with_options(
110    dclist: &[u128],
111    options: DctsOptions,
112) -> Vec<u8> {
113    dclist_to_dcts_string_with_options(dclist, options).into_bytes()
114}
115
116/// Serializes a sequence of Document Character IDs (`&[u128]`) to Dcts format
117/// bytes using default options.
118#[must_use]
119pub fn dclist_to_dcts(dclist: &[u128]) -> Vec<u8> {
120    dclist_to_dcts_with_options(dclist, DctsOptions::default())
121}
122
123/// Parses strict Dcts text (`&[u8]`) into a sequence of [`DcChar`]s.
124///
125/// Unlike lenient display converters, every `@...@` token must either be `@@`
126/// (literal `'@'`) or a valid [`crate::DcShorthand`] (or `L<id>` local graph
127/// reference expanded to `Dc 296` followed by a `DcNumber`). All 128-bit
128/// Document Characters—including surrogate codepoints `0xD800..=0xDFFF`—are
129/// valid. Unclosed `@` delimiters, malformed shorthands, and invalid UTF-8
130/// return an error.
131pub fn parse_dcts_strict_to_dc_chars(bytes: &[u8]) -> Result<Vec<DcChar>> {
132    let text = std::str::from_utf8(bytes)
133        .map_err(|err| anyhow::anyhow!("Invalid UTF-8 in Dcts string: {err}"))?;
134    let mut out = Vec::with_capacity(text.len());
135    let mut chars = text.chars().peekable();
136    while let Some(ch) = chars.next() {
137        if ch != '@' {
138            out.push(DcChar(u128::from(u32::from(ch))));
139            continue;
140        }
141        let mut token = String::new();
142        let mut closed = false;
143        for inner in chars.by_ref() {
144            if inner == '@' {
145                closed = true;
146                break;
147            }
148            token.push(inner);
149        }
150        anyhow::ensure!(
151            closed,
152            "Unclosed '@' shorthand escape in Dcts string"
153        );
154        if token.is_empty() {
155            out.push(DcChar(u128::from(u32::from(b'@'))));
156            continue;
157        }
158        let shorthand = crate::DcShorthand::parse(&token)?;
159        match shorthand {
160            crate::DcShorthand::Local(local_id) => {
161                out.push(crate::dc::DC_LOCAL_NODE);
162                let val = malachite::Integer::from(local_id);
163                out.extend(crate::dc_number_minimal::integer_to_dc_number_chars(
164                    &val, None,
165                )?);
166            }
167            other => {
168                let gid = other.to_global_id()?;
169                out.push(DcChar(gid));
170            }
171        }
172    }
173    Ok(out)
174}
175
176#[cfg(test)]
177#[allow(
178    clippy::panic,
179    clippy::expect_used,
180    clippy::unwrap_used,
181    clippy::unwrap_in_result,
182    clippy::panic_in_result_fn,
183    clippy::indexing_slicing,
184    clippy::arithmetic_side_effects,
185    reason = "Standard repository test boilerplate"
186)]
187mod tests {
188    use super::*;
189
190    #[crate::ctb_test]
191    fn test_dclist_to_dcts_plain_and_escapes() {
192        // Plain text: "hello"
193        let stream = vec![104, 101, 108, 108, 111];
194        assert_eq!(
195            dclist_to_dcts_string_with_options(&stream, DctsOptions::default()),
196            "hello"
197        );
198
199        // Literal '@'
200        let at_stream = vec![64];
201        assert_eq!(
202            dclist_to_dcts_string_with_options(
203                &at_stream,
204                DctsOptions::default()
205            ),
206            "@@"
207        );
208
209        // Short Dc 123
210        let short_dc = SHORT_DC_REGION_START.saturating_add(123);
211        assert_eq!(
212            dclist_to_dcts_string_with_options(
213                &[short_dc],
214                DctsOptions::default()
215            ),
216            "@123@"
217        );
218
219        // Format 80
220        let fmt = FORMAT_REGION_START.saturating_add(80);
221        assert_eq!(
222            dclist_to_dcts_string_with_options(&[fmt], DctsOptions::default()),
223            "@f80@"
224        );
225    }
226
227    #[crate::ctb_test]
228    fn test_dclist_to_dcts_control_characters() {
229        let stream = vec![10, 0, 9]; // '\n', '\0', '\t'
230
231        // Default: raw control chars
232        let raw =
233            dclist_to_dcts_string_with_options(&stream, DctsOptions::default());
234        assert_eq!(raw, "\n\0\t");
235
236        // Escaped: control chars converted to @u...
237        let escaped = dclist_to_dcts_string_with_options(
238            &stream,
239            DctsOptions {
240                escape_control_chars: true,
241            },
242        );
243        assert_eq!(escaped, "@ua@@u0@@u9@");
244        // Surrogate-range Unicode Dcs (`0xD800..=0xDFFF`) are valid Document Characters (like WTF-8).
245        let parsed = parse_dcts_strict_to_dc_chars(b"a@ud800@@256@")
246            .expect("parse surrogate and short Dc in strict Dcts");
247        assert_eq!(
248            parsed,
249            vec![
250                DcChar::from(b'a'),
251                DcChar::from_u128(0xD800),
252                DcChar::from_u128(SHORT_DC_REGION_START.saturating_add(256)),
253            ]
254        );
255    }
256}