ctb_formats_dcdata/
dc_number_minimal.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//! Minimal Document Character (`DcChar`) numeral encoding and Base64 encapsulation.
21//!
22//! Provides the foundational encoding of unsigned 128-bit integers into sequences
23//! of short Document Characters (Dcs) using Format 199 and Base64 encapsulation Dcs
24//! (short Dcs 127..=190 and 195).
25
26#[allow(
27    unused_imports,
28    clippy::wildcard_imports,
29    reason = "Standard workspace module prelude"
30)]
31use crate::utilities::*;
32
33use anyhow::{Result, anyhow, bail};
34
35use crate::dc::{
36    DC_BASE64_PADDING, DC_BASE64_START, DC_BEGIN_NUMBER, DC_END_NUMBER,
37    DC_NEGATIVE,
38};
39use crate::dc_char::{DcChar, DcCharExt};
40use crate::syntax::{DcRole, SyntaxRuleResolver, default_syntax_resolver};
41use ctb_utilities::DC_INTEGER;
42use ctb_utilities::format_id::FormatId;
43use malachite::{
44    Integer, Natural,
45    base::num::basic::traits::Zero,
46    base::num::conversion::traits::PowerOf2Digits,
47};
48
49/// Converts a 6-bit Base64 numeral value (0..=63) or padding sentinel (64) into
50/// its corresponding Base64 encapsulation `DcChar`.
51///
52/// Values `0..=63` map to short Dcs `127..=190`.
53/// Value `64` maps to short Dc `195` (`DC_BASE64_PADDING`).
54#[must_use]
55pub fn dc_base64_digit_to_char(val: u8) -> DcChar {
56    if val == 64 {
57        DC_BASE64_PADDING
58    } else {
59        let offset = u32::from(val.min(63));
60        #[expect(
61            clippy::expect_used,
62            reason = "DC_BASE64_START is a compile-time short Dc constant (Short Dc 127)"
63        )]
64        let start = DC_BASE64_START
65            .to_short()
66            .expect("DC_BASE64_START is Short Dc 127");
67        DcChar::from_short(start.saturating_add(offset))
68    }
69}
70
71/// Converts a Base64 encapsulation `DcChar` into its 6-bit numeral value (0..=63)
72/// or padding sentinel (64).
73///
74/// # Errors
75/// Returns an error if `ch` is not a valid Base64 encapsulation character.
76pub fn dc_base64_char_to_digit(ch: DcChar) -> Result<u8> {
77    dc_base64_char_to_digit_with_resolver(
78        ch,
79        crate::syntax::default_syntax_resolver().as_ref(),
80    )
81}
82
83/// Converts a Base64 encapsulation `DcChar` into its 6-bit numeral value (0..=63)
84/// or padding sentinel (64) using `resolver`.
85///
86/// # Errors
87/// Returns an error if `ch` is not a valid Base64 encapsulation character.
88pub fn dc_base64_char_to_digit_with_resolver(
89    ch: DcChar,
90    resolver: &dyn SyntaxRuleResolver,
91) -> Result<u8> {
92    if let Some(digit) = resolver.base64_digit_value(ch.to_u128()) {
93        Ok(digit)
94    } else {
95        bail!("DcChar({ch}) is not a Base64 encapsulation digit or padding")
96    }
97}
98
99/// Returns `true` if `ch` is a Base64 encapsulation digit (127..=190) or padding (195).
100#[must_use]
101pub fn is_dc_base64_encapsulation_char(ch: DcChar) -> bool {
102    is_dc_base64_encapsulation_char_with_resolver(
103        ch,
104        crate::syntax::default_syntax_resolver().as_ref(),
105    )
106}
107
108/// Returns `true` if `ch` is a Base64 encapsulation digit (127..=190) or padding (195)
109/// according to `resolver`.
110#[must_use]
111pub fn is_dc_base64_encapsulation_char_with_resolver(
112    ch: DcChar,
113    resolver: &dyn SyntaxRuleResolver,
114) -> bool {
115    ch.fills_role_with(DcRole::Base64Digit, resolver)
116        || ch.fills_role_with(DcRole::Base64Padding, resolver)
117}
118
119/// Encodes an unsigned 128-bit integer into a sequence of `DcChar`s.
120///
121/// Structure:
122/// `[DC_BEGIN_NUMBER, DC_INTEGER, ...Base64 encapsulation digits..., DC_END_NUMBER]`
123#[must_use]
124pub fn u128_to_dc_number_chars(mut val: u128) -> Vec<DcChar> {
125    let mut digits = Vec::new();
126    if val == 0 {
127        digits.push(DC_BASE64_START);
128    } else {
129        while val > 0 {
130            #[expect(
131                clippy::expect_used,
132                reason = "Divisor 64 is non-zero and remainder mod 64 is in 0..=63 which fits in u8"
133            )]
134            let rem_u8 = u8::try_from(
135                val.checked_rem(64).expect("divisor 64 is non-zero"),
136            )
137            .expect("remainder mod 64 fits in u8");
138            digits.push(dc_base64_digit_to_char(rem_u8));
139            #[expect(clippy::expect_used, reason = "Divisor 64 is non-zero")]
140            {
141                val = val.checked_div(64).expect("divisor 64 is non-zero");
142            }
143        }
144        digits.reverse();
145    }
146
147    let mut result = Vec::with_capacity(digits.len().saturating_add(3));
148    result.push(DC_BEGIN_NUMBER);
149    result.push(DC_INTEGER);
150    result.extend(digits);
151    result.push(DC_END_NUMBER);
152    result
153}
154
155/// Encodes an unsigned 128-bit integer into a sequence of short Document Character IDs (`u32`).
156///
157/// Structure:
158/// `[6 (Begin number), 199 (Format 199), ...Base64 encapsulation digits (127..=190)..., 7 (End number)]`
159#[must_use]
160pub fn u128_to_dc_number_short(val: u128) -> Vec<u32> {
161    let chars = u128_to_dc_number_chars(val);
162    let mut out = Vec::with_capacity(chars.len());
163    for ch in chars {
164        if ch == DC_INTEGER {
165            #[expect(
166                clippy::expect_used,
167                reason = "DC_INTEGER is a compile-time format Dc constant (Format 199)"
168            )]
169            out.push(ch.to_format().expect("DC_INTEGER is Format 199"));
170        } else {
171            #[expect(
172                clippy::expect_used,
173                reason = "u128_to_dc_number_chars only emits DC_BEGIN_NUMBER, DC_END_NUMBER, and Base64 short Dcs alongside DC_INTEGER"
174            )]
175            out.push(
176                ch.to_short()
177                    .expect("non-format numeral character is a short Dc"),
178            );
179        }
180    }
181    out
182}
183
184/// Reads a single unsigned 128-bit integer from a slice of Document Character
185/// Global Graph IDs (`&[u128]`), returning the parsed `u128` integer and the
186/// number of tokens consumed from the slice.
187///
188/// Expects the numeral sequence:
189/// `[DC_BEGIN_NUMBER, DC_INTEGER, ...Base64 encapsulation digits..., DC_END_NUMBER]`
190///
191/// # Errors
192/// Returns an error if the token stream does not start with a valid Dc integer
193/// numeral frame or if the value overflows `u128`.
194pub fn read_dc_number_u128(gids: &[u128]) -> Result<(u128, usize)> {
195    read_dc_number_u128_with_resolver(
196        gids,
197        crate::syntax::default_syntax_resolver().as_ref(),
198    )
199}
200
201/// Reads a single unsigned 128-bit integer from a slice of Document Character
202/// Global Graph IDs (`&[u128]`) using `resolver`, returning the parsed `u128`
203/// integer and the number of tokens consumed from the slice.
204///
205/// # Errors
206/// Returns an error if the token stream does not start with a valid Dc integer
207/// numeral frame or if the value overflows `u128`.
208pub fn read_dc_number_u128_with_resolver(
209    gids: &[u128],
210    resolver: &dyn SyntaxRuleResolver,
211) -> Result<(u128, usize)> {
212    let Some(&first) = gids.first() else {
213        bail!("Empty GID stream");
214    };
215    let first_dc = DcChar::from_u128(first);
216    ensure!(
217        first_dc.fills_role_with(DcRole::BeginNumber, resolver),
218        "Expected Dc 6 (Begin number), found {first}"
219    );
220
221    let Some(&second) = gids.get(1) else {
222        bail!("Unexpected end of stream after Dc 6");
223    };
224    ensure!(
225        resolver.is_equivalent_to(second, DC_INTEGER.to_u128()),
226        "Expected Format 199 (DC_INTEGER) after Dc 6, found {second}"
227    );
228
229    let mut idx = 2usize;
230    let mut val: u128 = 0;
231    let mut found_end = false;
232    let mut digit_count = 0usize;
233
234    while let Some(&gid) = gids.get(idx) {
235        idx = idx.saturating_add(1);
236        let dc = DcChar::from_u128(gid);
237        if dc.fills_role_with(DcRole::EndNumber, resolver) {
238            found_end = true;
239            break;
240        }
241
242        let digit = dc_base64_char_to_digit_with_resolver(dc, resolver)?;
243
244        ensure!(
245            digit < 64,
246            "Padding character not permitted in integer numeral"
247        );
248        val = val
249            .checked_mul(64)
250            .and_then(|v| v.checked_add(u128::from(digit)))
251            .ok_or_else(|| anyhow!("Overflow reading u128 integer numeral"))?;
252        digit_count = digit_count.saturating_add(1);
253    }
254
255    ensure!(found_end, "Unclosed Dc number: missing Dc 7 (End number)");
256    ensure!(digit_count > 0, "Dc number has no digits");
257    Ok((val, idx))
258}
259
260fn validate_int_for_format(
261    val: &Integer,
262    fmt: Option<FormatId>,
263) -> Result<DcChar> {
264    // Reason for fallback: unannotated Dc integer numerals represent arbitrary-precision integers by specification, so None canonically selects FormatId::Integer rather than masking a missing-format error.
265    let resolved = fmt.unwrap_or(FormatId::Integer);
266    let in_range = match resolved {
267        FormatId::Integer => true,
268        FormatId::U8 => u8::try_from(val).is_ok(),
269        FormatId::I8 => i8::try_from(val).is_ok(),
270        FormatId::U16 => u16::try_from(val).is_ok(),
271        FormatId::I16 => i16::try_from(val).is_ok(),
272        FormatId::U32 => u32::try_from(val).is_ok(),
273        FormatId::I32 => i32::try_from(val).is_ok(),
274        FormatId::U64 => u64::try_from(val).is_ok(),
275        FormatId::I64 => i64::try_from(val).is_ok(),
276        FormatId::U128 => u128::try_from(val).is_ok(),
277        FormatId::I128 => i128::try_from(val).is_ok(),
278        other => {
279            bail!("Unsupported integer FormatId {other:?} in DcNumber");
280        }
281    };
282    anyhow::ensure!(
283        in_range,
284        "Integer value {val} is out of range for FormatId {resolved:?}"
285    );
286    resolved
287        .dc_char()
288        .with_context(|| format!("FormatId {resolved:?} has no DcChar"))
289}
290
291/// Encodes an arbitrary-precision `malachite::Integer` into canonical `DcNumber`
292/// `DcChar` tokens `[Dc 6, <format_dc>, (optional Dc 11), <base64 digits>, Dc 7]`.
293pub fn integer_to_dc_number_chars(
294    val: &Integer,
295    fmt: Option<FormatId>,
296) -> Result<Vec<DcChar>> {
297    let fmt_dc = validate_int_for_format(val, fmt)?;
298    let is_negative = *val < Integer::ZERO;
299    let abs = val.unsigned_abs_ref();
300    let b64_digits: Vec<u8> = if *abs == Natural::ZERO {
301        vec![0]
302    } else {
303        abs.to_power_of_2_digits_desc(6u64)
304    };
305    let mut out = Vec::with_capacity(
306        b64_digits
307            .len()
308            .saturating_add(if is_negative { 4 } else { 3 }),
309    );
310    out.push(DC_BEGIN_NUMBER);
311    out.push(fmt_dc);
312    if is_negative {
313        out.push(DC_NEGATIVE);
314    }
315    for d in b64_digits {
316        out.push(dc_base64_digit_to_char(d));
317    }
318    out.push(DC_END_NUMBER);
319    Ok(out)
320}
321
322/// Reads an arbitrary-precision signed integer from a `DcNumber` token slice
323/// (`[Dc 6, <format_dc>, (optional sign), <base64 digits>+, Dc 7]`).
324pub fn read_typed_dc_integer_with_resolver(
325    tokens: &[DcChar],
326    resolver: &dyn SyntaxRuleResolver,
327) -> Result<(Option<FormatId>, Integer, usize)> {
328    let Some(&first) = tokens.first() else {
329        bail!("Empty token stream reading typed Dc integer");
330    };
331    anyhow::ensure!(
332        resolver.token_fills_role(first.to_u128(), DcRole::BeginNumber),
333        "Expected Dc 6 (Begin number), found {first}"
334    );
335    let fmt_dc = *tokens
336        .get(1)
337        .context("Unexpected end of Dc number after Dc 6")?;
338    let fmt = if let Some(f) = FormatId::from_dc_id(fmt_dc.to_u128()) {
339        f
340    } else if resolver.is_equivalent_to(fmt_dc.to_u128(), DC_INTEGER.to_u128())
341    {
342        FormatId::Integer
343    } else {
344        bail!("Expected integer format Dc after Dc 6, found {fmt_dc}");
345    };
346
347    let mut idx = 2usize;
348    let mut is_negative = false;
349    if let Some(&sign_tok) = tokens.get(idx) {
350        if resolver.token_fills_role(sign_tok.to_u128(), DcRole::Negative) {
351            is_negative = true;
352            idx = idx.saturating_add(1);
353        } else if resolver
354            .token_fills_role(sign_tok.to_u128(), DcRole::Positive)
355        {
356            idx = idx.saturating_add(1);
357        }
358    }
359
360    let mut digits: Vec<u8> = Vec::new();
361    let mut found_end = false;
362    while let Some(&tok) = tokens.get(idx) {
363        idx = idx.saturating_add(1);
364        if resolver.token_fills_role(tok.to_u128(), DcRole::EndNumber) {
365            found_end = true;
366            break;
367        }
368        let digit = dc_base64_char_to_digit_with_resolver(tok, resolver)?;
369        anyhow::ensure!(
370            digit < 64,
371            "Invalid Base64 digit {digit} in DcNumber integer"
372        );
373        digits.push(digit);
374    }
375
376    anyhow::ensure!(found_end, "Unclosed Dc number: missing Dc 7 (End number)");
377    anyhow::ensure!(!digits.is_empty(), "Dc number has no digits");
378
379    let nat = Natural::from_power_of_2_digits_desc(6u64, digits.into_iter())
380        .context("Failed to reconstruct Natural from Base64 digits")?;
381    let val = Integer::from_sign_and_abs(!is_negative, nat);
382    let _ = validate_int_for_format(&val, Some(fmt))?;
383    Ok((Some(fmt), val, idx))
384}
385
386/// Convenience wrapper for [`read_typed_dc_integer_with_resolver`] using the
387/// default dataset syntax resolver.
388pub fn read_typed_dc_integer(
389    tokens: &[DcChar],
390) -> Result<(Option<FormatId>, Integer, usize)> {
391    let resolver = default_syntax_resolver();
392    read_typed_dc_integer_with_resolver(tokens, resolver.as_ref())
393}
394
395#[cfg(test)]
396#[allow(
397    clippy::panic,
398    clippy::expect_used,
399    clippy::unwrap_used,
400    clippy::unwrap_in_result,
401    clippy::panic_in_result_fn,
402    clippy::indexing_slicing,
403    clippy::arithmetic_side_effects,
404    reason = "Standard repository test boilerplate"
405)]
406mod tests {
407    use super::*;
408
409    #[crate::ctb_test]
410    fn test_base64_digit_roundtrip() {
411        for digit in 0..=63 {
412            let ch = dc_base64_digit_to_char(digit);
413            assert!(is_dc_base64_encapsulation_char(ch));
414            assert_eq!(dc_base64_char_to_digit(ch).unwrap(), digit);
415        }
416
417        let pad = dc_base64_digit_to_char(64);
418        assert_eq!(pad, DC_BASE64_PADDING);
419        assert!(is_dc_base64_encapsulation_char(pad));
420        assert_eq!(dc_base64_char_to_digit(pad).unwrap(), 64);
421    }
422
423    #[crate::ctb_test]
424    fn test_u128_to_dc_number_short_zero() {
425        let res = u128_to_dc_number_short(0);
426        assert_eq!(res, vec![6, 199, 127, 7]);
427    }
428
429    #[crate::ctb_test]
430    fn test_u128_to_dc_number_short_sixty_four() {
431        // 64 in base 64 is digits 1 ('B' = 128) and 0 ('A' = 127)
432        let res = u128_to_dc_number_short(64);
433        assert_eq!(res, vec![6, 199, 128, 127, 7]);
434    }
435
436    #[crate::ctb_test]
437    fn test_read_dc_number_u128_roundtrip() {
438        for &val in
439            &[0u128, 1, 42, 63, 64, 65, 4095, 4096, 1_000_000, u128::MAX]
440        {
441            let chars = u128_to_dc_number_chars(val);
442            let gids: Vec<u128> = chars.iter().map(|c| c.to_u128()).collect();
443            let (parsed, consumed) = read_dc_number_u128(&gids).unwrap();
444            assert_eq!(parsed, val);
445            assert_eq!(consumed, gids.len());
446        }
447    }
448
449    #[crate::ctb_test]
450    fn test_read_dc_number_u128_with_custom_resolver() {
451        struct AliasResolver(std::collections::HashMap<u128, u128>);
452        impl crate::syntax::SyntaxRuleResolver for AliasResolver {
453            fn resolve_rule(
454                &self,
455                target: &crate::syntax::CharTarget,
456            ) -> Option<&crate::syntax::DcSyntaxRule> {
457                crate::syntax::default_syntax_resolver().resolve_rule(target)
458            }
459            fn resolve_named_type(
460                &self,
461                name: &str,
462            ) -> Option<&crate::syntax::SyntaxPattern> {
463                crate::syntax::default_syntax_resolver()
464                    .resolve_named_type(name)
465            }
466            fn matches_script(&self, script_name: &str, token: u128) -> bool {
467                crate::syntax::default_syntax_resolver()
468                    .matches_script(script_name, token)
469            }
470            fn canonical_token(&self, token: u128) -> u128 {
471                let mapped = self.0.get(&token).copied().unwrap_or(token);
472                crate::syntax::default_syntax_resolver().canonical_token(mapped)
473            }
474        }
475
476        let alias_begin = DcChar::from_long(99001).to_u128();
477        let alias_int = DcChar::from_long(99002).to_u128();
478        let alias_digit1 = DcChar::from_long(99003).to_u128();
479        let alias_digit0 = DcChar::from_long(99004).to_u128();
480        let alias_end = DcChar::from_long(99005).to_u128();
481        let mut map = std::collections::HashMap::new();
482        map.insert(alias_begin, DC_BEGIN_NUMBER.to_u128());
483        map.insert(alias_int, DC_INTEGER.to_u128());
484        map.insert(alias_digit1, dc_base64_digit_to_char(1).to_u128());
485        map.insert(alias_digit0, dc_base64_digit_to_char(0).to_u128());
486        map.insert(alias_end, DC_END_NUMBER.to_u128());
487        let resolver = AliasResolver(map);
488
489        assert!(is_dc_base64_encapsulation_char_with_resolver(
490            DcChar::from_u128(alias_digit1),
491            &resolver
492        ));
493        let gids = vec![
494            alias_begin,
495            alias_int,
496            alias_digit1,
497            alias_digit0,
498            alias_end,
499        ];
500        let (parsed, consumed) =
501            read_dc_number_u128_with_resolver(&gids, &resolver).unwrap();
502        assert_eq!(parsed, 64);
503        assert_eq!(consumed, 5);
504    }
505}