ctb_formats_dcdata/
dc_char.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//! Document Character (`DcChar`) representation and conversions.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use crate::syntax::SyntaxRuleResolver;
30use ctb_formats_dctf::{
31    encode_dctf, encode_dctf_buf, len_dctf, len_utf_8e_128,
32};
33pub use ctb_utilities::dc_char::DcChar;
34
35/// Returns whether the given token (u128 character code) represents a type
36/// token in Document Character syntax.
37#[must_use]
38pub fn is_type_token(token: u128) -> bool {
39    crate::syntax::default_syntax_resolver()
40        .token_fills_role(token, crate::syntax::DcRole::TypeToken)
41}
42
43/// Extension methods for [`DcChar`] specific to document formats and serialization.
44pub trait DcCharExt {
45    /// Returns whether this character represents a type token.
46    #[must_use]
47    fn is_type_token(self) -> bool;
48
49    /// Returns whether this character fills the specified syntactic or semantic role
50    /// using the default compiled syntax resolver.
51    #[must_use]
52    fn fills_role(self, role: crate::syntax::DcRole) -> bool;
53
54    /// Returns whether this character fills the specified syntactic or semantic role
55    /// according to the provided resolver.
56    #[must_use]
57    fn fills_role_with(
58        self,
59        role: crate::syntax::DcRole,
60        resolver: &dyn crate::syntax::SyntaxRuleResolver,
61    ) -> bool;
62
63    /// Converts this character into a sequence of short Document Character IDs.
64    #[must_use]
65    fn to_short_vec(self) -> Vec<u32>;
66
67    /// Returns the number of bytes required to encode this `DcChar` in
68    /// `DcTF` (`.dctf`, `f641`) format (1..=23 bytes).
69    #[must_use]
70    fn len_dctf(self) -> usize;
71
72    /// Returns the number of bytes required to encode this `DcChar` in legacy
73    /// `UTF-8e-128` (`DcUtf`, `f89`) format (1..=24 bytes).
74    #[must_use]
75    fn len_utf_8e_128(self) -> usize;
76
77    /// Encodes this `DcChar` in `DcTF` into the provided byte buffer (must be
78    /// at least 23 bytes) and returns the number of bytes written.
79    fn encode_buf(self, buf: &mut [u8]) -> usize;
80
81    /// Encodes this `DcChar` in `DcTF` into a newly allocated `Vec<u8>`.
82    #[must_use]
83    fn encode(self) -> Vec<u8>;
84}
85
86impl DcCharExt for DcChar {
87    fn is_type_token(self) -> bool {
88        is_type_token(self.0)
89    }
90    fn fills_role(self, role: crate::syntax::DcRole) -> bool {
91        crate::syntax::default_syntax_resolver().token_fills_role(self.0, role)
92    }
93    fn fills_role_with(
94        self,
95        role: crate::syntax::DcRole,
96        resolver: &dyn crate::syntax::SyntaxRuleResolver,
97    ) -> bool {
98        resolver.token_fills_role(self.0, role)
99    }
100    fn to_short_vec(self) -> Vec<u32> {
101        #[expect(
102            clippy::expect_used,
103            reason = "DC_ESCAPE and DC_LONG_DC are compile-time short Dc constants (Short Dc 255 and Short Dc 308)"
104        )]
105        let (escape, long_dc) = (
106            crate::dc::DC_ESCAPE
107                .to_short()
108                .expect("DC_ESCAPE is Short Dc 255"),
109            crate::dc::DC_LONG_DC
110                .to_short()
111                .expect("DC_LONG_DC is Short Dc 308"),
112        );
113
114        if self == crate::dc::DC_LONG_DC {
115            vec![escape, long_dc]
116        } else if self == crate::dc::DC_ESCAPE {
117            vec![escape, escape]
118        } else if let Ok(short_id) = self.to_short() {
119            vec![short_id]
120        } else {
121            let mut out = Vec::new();
122            out.push(long_dc);
123            out.extend(crate::dc_number_minimal::u128_to_dc_number_short(
124                self.0,
125            ));
126            out
127        }
128    }
129
130    fn len_dctf(self) -> usize {
131        len_dctf(self.0)
132    }
133
134    fn len_utf_8e_128(self) -> usize {
135        len_utf_8e_128(self.0)
136    }
137
138    fn encode_buf(self, buf: &mut [u8]) -> usize {
139        encode_dctf_buf(buf, self.0)
140    }
141
142    fn encode(self) -> Vec<u8> {
143        encode_dctf(self.0)
144    }
145}
146
147#[cfg(test)]
148#[allow(
149    clippy::panic,
150    clippy::expect_used,
151    clippy::unwrap_used,
152    clippy::unwrap_in_result,
153    clippy::panic_in_result_fn,
154    clippy::indexing_slicing,
155    clippy::arithmetic_side_effects,
156    reason = "Standard repository test boilerplate"
157)]
158mod tests {
159    use super::*;
160    use ctb_utilities::dc_char::{FORMAT_REGION_START, SHORT_DC_REGION_START};
161
162    #[crate::ctb_test]
163    fn test_from_short_and_to_short() {
164        let dc_203 = DcChar::from_short(203);
165        assert_eq!(dc_203.0, SHORT_DC_REGION_START.saturating_add(203));
166        assert_eq!(dc_203.to_short().unwrap(), 203);
167        assert!(dc_203.is_short_dc());
168        assert_eq!(dc_203.to_short_dc(), Some(203));
169
170        let non_short = DcChar::from_long(42);
171        assert!(!non_short.is_short_dc());
172        non_short.to_short().unwrap_err();
173    }
174
175    #[crate::ctb_test]
176    fn test_from_format_and_to_format() {
177        let fmt_199 = DcChar::from_format(199);
178        assert_eq!(fmt_199.0, FORMAT_REGION_START.saturating_add(199));
179        assert!(fmt_199.is_format());
180        assert_eq!(fmt_199.to_format().unwrap(), 199);
181
182        let non_fmt = DcChar::from_short(10);
183        assert!(!non_fmt.is_format());
184        non_fmt.to_format().unwrap_err();
185    }
186
187    #[crate::ctb_test]
188    fn test_from_unicode_and_to_unicode() {
189        let uni_a = DcChar::from_unicode(65).unwrap();
190        assert_eq!(uni_a.to_unicode().unwrap(), 65);
191        assert_eq!(uni_a.as_char(), Some('A'));
192        assert_eq!(uni_a, 'A');
193
194        DcChar::from_unicode(0x11_0000).unwrap_err();
195    }
196
197    #[crate::ctb_test]
198    fn test_to_short_vec_infallible() {
199        // Short Dc
200        let dc_42 = DcChar::from_short(42);
201        assert_eq!(dc_42.to_short_vec(), vec![42]);
202
203        // Dc 308 escaped
204        let dc_308 = DcChar::from_short(308);
205        assert_eq!(dc_308.to_short_vec(), vec![255, 308]);
206
207        // Dc 255 escaped
208        let dc_255 = DcChar::from_short(255);
209        assert_eq!(dc_255.to_short_vec(), vec![255, 255]);
210
211        // Unicode 'A' (65): 65 in base 64 is 1 * 64 + 1 -> 'B' (128), 'B' (128)
212        let uni_a = DcChar::from_char('A');
213        let short_vec = uni_a.to_short_vec();
214        assert_eq!(short_vec.get(0..3), Some(&[308, 6, 199][..]));
215        assert_eq!(short_vec.last(), Some(&7));
216    }
217
218    #[crate::ctb_test]
219    fn test_partial_eq_comparisons() {
220        let dc = DcChar::from_short(203);
221        assert_eq!(dc, SHORT_DC_REGION_START.saturating_add(203));
222        assert!(dc.eq(&(SHORT_DC_REGION_START.saturating_add(203))));
223
224        let uni = DcChar::from_char('Z');
225        assert_eq!(uni, 'Z');
226        assert!(uni.eq(&'Z'));
227    }
228
229    #[crate::ctb_test]
230    fn test_is_type_token() {
231        assert!(is_type_token(DcChar::from_format(490).to_u128()));
232        assert!(is_type_token(DcChar::from_format(0).to_u128()));
233        assert!(DcChar::from_format(80).is_type_token());
234
235        assert!(is_type_token(DcChar::from_short(275).to_u128()));
236        assert!(is_type_token(DcChar::from_short(264).to_u128()));
237        assert!(is_type_token(DcChar::from_short(278).to_u128()));
238        assert!(is_type_token(DcChar::from_short(280).to_u128()));
239        assert!(is_type_token(DcChar::from_short(306).to_u128()));
240        assert!(is_type_token(DcChar::from_short(513).to_u128()));
241        assert!(is_type_token(DcChar::from_short(300).to_u128()));
242        assert!(is_type_token(DcChar::from_short(516).to_u128()));
243
244        // EL Routines and Miscellaneous are NOT type tokens
245        assert!(!is_type_token(DcChar::from_short(265).to_u128()));
246        assert!(!is_type_token(DcChar::from_short(266).to_u128()));
247        assert!(!is_type_token(DcChar::from_short(267).to_u128()));
248
249        assert!(!is_type_token(DcChar::from_short(42).to_u128()));
250        assert!(!is_type_token(DcChar::from_char('A').to_u128()));
251        assert!(!DcChar::from_short(310).is_type_token());
252    }
253
254    #[crate::ctb_test]
255    fn test_composite_role_canonical_matches() {
256        use crate::syntax::DcRole;
257
258        // TypeToken: .EM Types and format IDs match, routines do not
259        assert!(
260            DcRole::TypeToken
261                .matches_canonical(DcChar::from_short(278).to_u128())
262        );
263        assert!(
264            DcRole::TypeToken
265                .matches_canonical(DcChar::from_short(280).to_u128())
266        );
267        assert!(
268            DcRole::TypeToken
269                .matches_canonical(DcChar::from_short(306).to_u128())
270        );
271        assert!(
272            !DcRole::TypeToken
273                .matches_canonical(DcChar::from_short(265).to_u128())
274        );
275        assert!(
276            !DcRole::TypeToken
277                .matches_canonical(DcChar::from_short(266).to_u128())
278        );
279        assert!(
280            !DcRole::TypeToken
281                .matches_canonical(DcChar::from_short(267).to_u128())
282        );
283
284        // Base64Digit: 127..=190
285        assert!(
286            DcRole::Base64Digit
287                .matches_canonical(DcChar::from_short(127).to_u128())
288        );
289        assert!(
290            DcRole::Base64Digit
291                .matches_canonical(DcChar::from_short(190).to_u128())
292        );
293        assert!(
294            !DcRole::Base64Digit
295                .matches_canonical(DcChar::from_short(191).to_u128())
296        );
297        assert!(
298            !DcRole::Base64Digit
299                .matches_canonical(DcChar::from_short(195).to_u128())
300        );
301
302        // EvaluableExpressionStarter: .EM Routines and reference/invocation starters
303        assert!(
304            DcRole::EvaluableExpressionStarter
305                .matches_canonical(DcChar::from_short(256).to_u128())
306        );
307        assert!(
308            DcRole::EvaluableExpressionStarter
309                .matches_canonical(DcChar::from_short(265).to_u128())
310        );
311        assert!(
312            DcRole::EvaluableExpressionStarter
313                .matches_canonical(DcChar::from_short(276).to_u128())
314        );
315        assert!(
316            DcRole::EvaluableExpressionStarter
317                .matches_canonical(DcChar::from_short(279).to_u128())
318        );
319        assert!(
320            DcRole::EvaluableExpressionStarter
321                .matches_canonical(DcChar::from_short(540).to_u128())
322        );
323        assert!(
324            DcRole::EvaluableExpressionStarter
325                .matches_canonical(DcChar::from_short(397).to_u128())
326        );
327        assert!(
328            DcRole::EvaluableExpressionStarter
329                .matches_canonical(DcChar::from_short(561).to_u128())
330        );
331        assert!(
332            !DcRole::EvaluableExpressionStarter
333                .matches_canonical(DcChar::from_short(6).to_u128())
334        );
335    }
336}