ctb_formats_dcstring/
dc_number.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 (Dc) numeric encoding and base64 encapsulation utilities.
21//!
22//! Provides encoding and decoding of numbers in Dc streams using Base64
23//! encapsulation digits (short Dcs 127..=190 and 195).
24//!
25//! Standard structure of a Dc number:
26//! 1. Dc 6 (`Begin number`)
27//! 2. Dc for format 199 (Global Graph ID `2228423` or short Dc `199`)
28//! 3. Optional Dc 10 (`Positive`) or Dc 11 (`Negative`)
29//! 4. Absolute value of integer converted to Base64 (using `ctb_formats_math::base`)
30//!    and encoded as Base64 encapsulation Dcs (127..=190)
31//! 5. Dc 7 (`End number`)
32
33#[allow(
34    unused_imports,
35    clippy::wildcard_imports,
36    reason = "Standard workspace module prelude"
37)]
38use crate::utilities::*;
39
40use anyhow::{Context, Result, anyhow, bail, ensure};
41use ctb_formats_math::base::{Base, format_natural, parse_natural};
42use malachite::{Integer, Natural};
43
44pub use ctb_formats_dcdata::DC_INTEGER;
45pub use ctb_formats_dcdata::dc::{
46    DC_BASE64_END, DC_BASE64_PADDING, DC_BASE64_START, DC_BEGIN_NUMBER,
47    DC_END_NUMBER, DC_NEGATIVE, DC_POSITIVE,
48};
49pub use ctb_formats_dcdata::dc_char::{DcChar, DcCharExt};
50pub use ctb_formats_dcdata::dc_number_minimal::{
51    dc_base64_char_to_digit, dc_base64_digit_to_char,
52    is_dc_base64_encapsulation_char,
53};
54use ctb_formats_dcdata::syntax::{DcRole, SyntaxRuleResolver};
55
56fn gid_fills_role(
57    gid: u128,
58    role: DcRole,
59    resolver: &dyn SyntaxRuleResolver,
60) -> bool {
61    if resolver.token_fills_role(gid, role) {
62        return true;
63    }
64    if let Ok(s) = u32::try_from(gid) {
65        if resolver.token_fills_role(DcChar::from_short(s).to_u128(), role) {
66            return true;
67        }
68        if resolver.token_fills_role(DcChar::from_format(s).to_u128(), role) {
69            return true;
70        }
71    }
72    false
73}
74
75fn gid_to_base64_digit(
76    gid: u128,
77    resolver: &dyn SyntaxRuleResolver,
78) -> Option<u8> {
79    if let Some(digit) = resolver.base64_digit_value(gid) {
80        return Some(digit);
81    }
82    if let Ok(s) = u32::try_from(gid) {
83        if let Some(digit) =
84            resolver.base64_digit_value(DcChar::from_short(s).to_u128())
85        {
86            return Some(digit);
87        }
88    }
89    None
90}
91
92fn base64_char_to_digit(c: char) -> Result<u8> {
93    match c {
94        'A'..='Z' => {
95            let offset = u32::from(c).saturating_sub(u32::from('A'));
96            u8::try_from(offset).map_err(|e| anyhow!("Invalid offset: {e}"))
97        }
98        'a'..='z' => {
99            let offset = u32::from(c).saturating_sub(u32::from('a'));
100            u8::try_from(offset.saturating_add(26))
101                .map_err(|e| anyhow!("Invalid offset: {e}"))
102        }
103        '0'..='9' => {
104            let offset = u32::from(c).saturating_sub(u32::from('0'));
105            u8::try_from(offset.saturating_add(52))
106                .map_err(|e| anyhow!("Invalid offset: {e}"))
107        }
108        '+' => Ok(62),
109        '/' => Ok(63),
110        '=' => Ok(64),
111        _ => bail!(
112            "Character '{c}' is not a valid standard Base64 digit or padding character"
113        ),
114    }
115}
116
117fn digit_to_base64_char(digit: u8) -> Result<char> {
118    match digit {
119        0..=25 => {
120            let code = u32::from(b'A').saturating_add(u32::from(digit));
121            char::from_u32(code)
122                .ok_or_else(|| anyhow!("Invalid char code {code}"))
123        }
124        26..=51 => {
125            let offset = u32::from(digit.saturating_sub(26));
126            let code = u32::from(b'a').saturating_add(offset);
127            char::from_u32(code)
128                .ok_or_else(|| anyhow!("Invalid char code {code}"))
129        }
130        52..=61 => {
131            let offset = u32::from(digit.saturating_sub(52));
132            let code = u32::from(b'0').saturating_add(offset);
133            char::from_u32(code)
134                .ok_or_else(|| anyhow!("Invalid char code {code}"))
135        }
136        62 => Ok('+'),
137        63 => Ok('/'),
138        64 => Ok('='),
139        _ => bail!("Invalid Base64 digit {digit}"),
140    }
141}
142
143// ---------------------------------------------------------------------------
144// Base64 Character <-> Short/Global Dc Mappings
145// ---------------------------------------------------------------------------
146
147/// Converts a single standard Base64 character or padding character (`=`) into
148/// its corresponding short Document Character (Dc) ID (127..=190, 195).
149pub fn base64_char_to_short_dc(c: char) -> Result<u32> {
150    let digit = base64_char_to_digit(c)?;
151    dc_base64_digit_to_char(digit).to_short()
152}
153
154/// Converts a single short Document Character (Dc) ID (127..=190, 195) into
155/// its corresponding standard Base64 character or padding character (`=`).
156pub fn short_dc_to_base64_char(dc: u32) -> Result<char> {
157    let digit = dc_base64_char_to_digit(DcChar::from_short(dc))?;
158    digit_to_base64_char(digit)
159}
160
161/// Converts a string of standard Base64 characters and padding into a vector
162/// of short Document Characters (127..=190, 195).
163pub fn base64_str_to_short_dcs(s: &str) -> Result<Vec<u32>> {
164    let mut dcs = Vec::with_capacity(s.len());
165    for c in s.chars() {
166        dcs.push(base64_char_to_short_dc(c)?);
167    }
168    Ok(dcs)
169}
170
171/// Converts a sequence of short Document Characters (127..=190, 195) into
172/// a standard Base64 string.
173pub fn short_dcs_to_base64_str(dcs: &[u32]) -> Result<String> {
174    let mut s = String::with_capacity(dcs.len());
175    for &dc in dcs {
176        s.push(short_dc_to_base64_char(dc)?);
177    }
178    Ok(s)
179}
180
181/// Converts a single standard Base64 character or padding character (`=`) into
182/// its corresponding Global Graph ID.
183pub fn base64_char_to_global_dc(c: char) -> Result<u128> {
184    let digit = base64_char_to_digit(c)?;
185    Ok(dc_base64_digit_to_char(digit).to_long())
186}
187
188/// Converts a single Global Graph ID (in the Base64 encapsulation range) into
189/// its corresponding standard Base64 character or padding character (`=`).
190pub fn global_dc_to_base64_char(gid: u128) -> Result<char> {
191    let resolver = ctb_formats_dcdata::syntax::default_syntax_resolver();
192    let digit = gid_to_base64_digit(gid, &**resolver).ok_or_else(|| {
193        anyhow!("Global ID {gid} is not a valid Base64 encapsulation Dc")
194    })?;
195    digit_to_base64_char(digit)
196}
197
198/// Converts a string of standard Base64 characters into Global Graph IDs.
199pub fn base64_str_to_global_dcs(s: &str) -> Result<Vec<u128>> {
200    let mut gids = Vec::with_capacity(s.len());
201    for c in s.chars() {
202        gids.push(base64_char_to_global_dc(c)?);
203    }
204    Ok(gids)
205}
206
207/// Converts a sequence of Global Graph IDs into a standard Base64 string.
208pub fn global_dcs_to_base64_str(gids: &[u128]) -> Result<String> {
209    let mut s = String::with_capacity(gids.len());
210    for &gid in gids {
211        s.push(global_dc_to_base64_char(gid)?);
212    }
213    Ok(s)
214}
215
216// ---------------------------------------------------------------------------
217// Dc Number Serialization
218// ---------------------------------------------------------------------------
219
220/// Converts a [`Natural`] number (with an optional negative sign flag) into
221/// a sequence of [`DcChar`]s.
222pub fn natural_to_dc_number_chars(
223    val: &Natural,
224    is_negative: bool,
225) -> Result<Vec<DcChar>> {
226    let b64_base = Base::new(64)?;
227    let b64_str = format_natural(val, b64_base, 0)?;
228
229    let mut result = Vec::with_capacity(b64_str.len().saturating_add(4));
230    result.push(DC_BEGIN_NUMBER);
231    result.push(DC_INTEGER);
232    if is_negative {
233        result.push(DC_NEGATIVE);
234    }
235    for c in b64_str.chars() {
236        let digit = base64_char_to_digit(c)?;
237        result.push(dc_base64_digit_to_char(digit));
238    }
239    result.push(DC_END_NUMBER);
240    Ok(result)
241}
242
243/// Converts a [`Natural`] number (with an optional negative sign flag) into
244/// a sequence of short Document Characters (Dcs).
245///
246/// Structure:
247/// `[Dc 6, Format 199, (optional Dc 11 if negative), ...Base64 encapsulation Dcs..., Dc 7]`
248pub fn natural_to_dc_number_short(
249    val: &Natural,
250    is_negative: bool,
251) -> Result<Vec<u32>> {
252    let chars = natural_to_dc_number_chars(val, is_negative)?;
253    let mut out = Vec::with_capacity(chars.len());
254    for ch in chars {
255        if ch == DC_INTEGER {
256            out.push(ch.to_format()?);
257        } else {
258            out.push(ch.to_short()?);
259        }
260    }
261    Ok(out)
262}
263
264/// Converts a [`Natural`] number (with an optional negative sign flag) into
265/// a sequence of Global Graph IDs (`DcList`).
266///
267/// Structure:
268/// `[GID 1114118 (Dc 6), GID 2228423 (Format 199), (optional GID 1114123 if negative), ...Base64 encapsulation GIDs..., GID 1114119 (Dc 7)]`
269pub fn natural_to_dc_number_global(
270    val: &Natural,
271    is_negative: bool,
272) -> Result<Vec<u128>> {
273    let chars = natural_to_dc_number_chars(val, is_negative)?;
274    Ok(chars.into_iter().map(DcChar::to_long).collect())
275}
276
277/// Converts an [`Integer`] into a sequence of short Document Characters (Dcs).
278pub fn integer_to_dc_number_short(val: &Integer) -> Result<Vec<u32>> {
279    let is_negative = *val < 0;
280    let abs_val = val.unsigned_abs_ref();
281    natural_to_dc_number_short(abs_val, is_negative)
282}
283
284/// Converts an [`Integer`] into a sequence of Global Graph IDs (`DcList`).
285pub fn integer_to_dc_number_global(val: &Integer) -> Result<Vec<u128>> {
286    let is_negative = *val < 0;
287    let abs_val = val.unsigned_abs_ref();
288    natural_to_dc_number_global(abs_val, is_negative)
289}
290
291/// Converts an `i128` integer into a sequence of short Document Characters (Dcs).
292pub fn i128_to_dc_number_short(val: i128) -> Result<Vec<u32>> {
293    integer_to_dc_number_short(&Integer::from(val))
294}
295
296/// Converts an `i128` integer into a sequence of Global Graph IDs (`DcList`).
297pub fn i128_to_dc_number_global(val: i128) -> Result<Vec<u128>> {
298    integer_to_dc_number_global(&Integer::from(val))
299}
300
301/// Converts a `u128` unsigned integer into a sequence of short Document Characters (Dcs).
302pub fn u128_to_dc_number_short(val: u128) -> Result<Vec<u32>> {
303    natural_to_dc_number_short(&Natural::from(val), false)
304}
305
306/// Converts a `u128` unsigned integer into a sequence of Global Graph IDs (`DcList`).
307pub fn u128_to_dc_number_global(val: u128) -> Result<Vec<u128>> {
308    natural_to_dc_number_global(&Natural::from(val), false)
309}
310
311/// Converts an [`Integer`] into a sequence of [`DcChar`]s.
312pub fn integer_to_dc_number_chars(val: &Integer) -> Result<Vec<DcChar>> {
313    let is_negative = *val < 0;
314    let abs_val = val.unsigned_abs_ref();
315    natural_to_dc_number_chars(abs_val, is_negative)
316}
317
318/// Converts an `i128` integer into a sequence of [`DcChar`]s.
319pub fn i128_to_dc_number_chars(val: i128) -> Result<Vec<DcChar>> {
320    integer_to_dc_number_chars(&Integer::from(val))
321}
322
323/// Converts a `u128` unsigned integer into a sequence of [`DcChar`]s.
324pub fn u128_to_dc_number_chars(val: u128) -> Result<Vec<DcChar>> {
325    natural_to_dc_number_chars(&Natural::from(val), false)
326}
327
328// ---------------------------------------------------------------------------
329// Dc Number Deserialization / Reading
330// ---------------------------------------------------------------------------
331
332/// Reads a single Dc number from a reader closure yielding [`DcChar`]s.
333pub fn read_dc_number_from_reader<F>(next_char: F) -> Result<Integer>
334where
335    F: FnMut() -> Result<DcChar>,
336{
337    let resolver = ctb_formats_dcdata::syntax::default_syntax_resolver();
338    read_dc_number_from_reader_with_resolver(next_char, &**resolver)
339}
340
341pub fn read_dc_number_from_reader_with_resolver<F>(
342    mut next_char: F,
343    resolver: &dyn SyntaxRuleResolver,
344) -> Result<Integer>
345where
346    F: FnMut() -> Result<DcChar>,
347{
348    let first = next_char()?;
349    ensure!(
350        resolver.token_fills_role(first.to_u128(), DcRole::BeginNumber),
351        "Expected Dc 6 (Begin number), found {first:?}"
352    );
353
354    let second = next_char()?;
355    ensure!(
356        resolver.is_equivalent_to(second.to_u128(), DC_INTEGER.to_u128()),
357        "Expected format 199 indicator after Dc 6, found {second:?}"
358    );
359
360    let mut is_negative = false;
361    let mut ch = next_char()?;
362    if resolver.token_fills_role(ch.to_u128(), DcRole::Negative) {
363        is_negative = true;
364        ch = next_char()?;
365    } else if resolver.token_fills_role(ch.to_u128(), DcRole::Positive) {
366        ch = next_char()?;
367    }
368
369    let mut b64_str = String::new();
370    while !resolver.token_fills_role(ch.to_u128(), DcRole::EndNumber) {
371        let digit = resolver
372            .base64_digit_value(ch.to_u128())
373            .ok_or_else(|| anyhow!("Expected Base64 digit Dc, found {ch}"))?;
374        let c = digit_to_base64_char(digit)?;
375        b64_str.push(c);
376        ch = next_char()?;
377    }
378
379    ensure!(
380        !b64_str.is_empty(),
381        "Dc number contains no digit characters"
382    );
383    let b64_base = Base::new(64)?;
384    let nat = parse_natural(&b64_str, b64_base).with_context(|| {
385        format!("Failed to parse Base64 number string '{b64_str}'")
386    })?;
387
388    Ok(Integer::from_sign_and_abs(!is_negative, nat))
389}
390
391/// Parses a slice of `DcChar` digits (with optional leading `DC_NEGATIVE` or
392/// `DC_POSITIVE` sign indicator, excluding the outer `DC_BEGIN_NUMBER`, format
393/// indicator, and `DC_END_NUMBER` delimiters) into an [`Integer`].
394pub fn parse_dc_number_digits(digits: &[DcChar]) -> Result<Integer> {
395    let resolver = ctb_formats_dcdata::syntax::default_syntax_resolver();
396    parse_dc_number_digits_with_resolver(digits, &**resolver)
397}
398
399/// Parses a slice of `DcChar` digits using the provided [`SyntaxRuleResolver`].
400pub fn parse_dc_number_digits_with_resolver(
401    digits: &[DcChar],
402    resolver: &dyn SyntaxRuleResolver,
403) -> Result<Integer> {
404    let mut is_negative = false;
405    let mut b64_str = String::new();
406    for (idx, &ch) in digits.iter().enumerate() {
407        if idx == 0 && resolver.token_fills_role(ch.to_u128(), DcRole::Negative)
408        {
409            is_negative = true;
410            continue;
411        }
412        if idx == 0 && resolver.token_fills_role(ch.to_u128(), DcRole::Positive)
413        {
414            continue;
415        }
416        let digit = resolver
417            .base64_digit_value(ch.to_u128())
418            .ok_or_else(|| anyhow!("Expected Base64 digit Dc, found {ch}"))?;
419        let c = digit_to_base64_char(digit)?;
420        b64_str.push(c);
421    }
422    ensure!(
423        !b64_str.is_empty(),
424        "Dc number contains no digit characters"
425    );
426    let b64_base = Base::new(64)?;
427    let nat = parse_natural(&b64_str, b64_base).with_context(|| {
428        format!("Failed to parse Base64 number string '{b64_str}'")
429    })?;
430    Ok(Integer::from_sign_and_abs(!is_negative, nat))
431}
432
433/// Reads a single Dc number from a slice of short Document Characters (Dcs),
434/// returning the parsed [`Integer`] and the number of tokens consumed from the slice.
435pub fn read_dc_number_short(dcs: &[u32]) -> Result<(Integer, usize)> {
436    let resolver = ctb_formats_dcdata::syntax::default_syntax_resolver();
437    read_dc_number_short_with_resolver(dcs, &**resolver)
438}
439
440/// Reads a single Dc number from a slice of short Document Characters (Dcs)
441/// using the provided [`SyntaxRuleResolver`].
442pub fn read_dc_number_short_with_resolver(
443    dcs: &[u32],
444    resolver: &dyn SyntaxRuleResolver,
445) -> Result<(Integer, usize)> {
446    let first = dcs
447        .first()
448        .copied()
449        .ok_or_else(|| anyhow!("Empty Dc stream"))?;
450    let first_dc = DcChar::from_short(first);
451    ensure!(
452        resolver.token_fills_role(first_dc.to_u128(), DcRole::BeginNumber),
453        "Expected Dc 6 (Begin number), found Dc {first}"
454    );
455
456    let second = dcs
457        .get(1)
458        .copied()
459        .ok_or_else(|| anyhow!("Unexpected end of stream after Dc 6"))?;
460    let second_format = DcChar::from_format(second);
461    let second_short = DcChar::from_short(second);
462    ensure!(
463        resolver.is_equivalent_to(second_format.to_u128(), DC_INTEGER.to_u128())
464            || resolver.is_equivalent_to(
465                second_short.to_u128(),
466                DC_INTEGER.to_u128(),
467            ),
468        "Expected format 199 indicator after Dc 6, found Dc {second}"
469    );
470
471    let mut idx = 2usize;
472    let mut is_negative = false;
473
474    if let Some(&third) = dcs.get(idx) {
475        let third_dc = DcChar::from_short(third);
476        if resolver.token_fills_role(third_dc.to_u128(), DcRole::Negative) {
477            is_negative = true;
478            idx = idx.saturating_add(1);
479        } else if resolver
480            .token_fills_role(third_dc.to_u128(), DcRole::Positive)
481        {
482            idx = idx.saturating_add(1);
483        }
484    }
485
486    let mut b64_str = String::new();
487    let mut found_end = false;
488
489    while idx < dcs.len() {
490        let Some(&raw_dc) = dcs.get(idx) else { break };
491        idx = idx.saturating_add(1);
492
493        let dc = DcChar::from_short(raw_dc);
494        if resolver.token_fills_role(dc.to_u128(), DcRole::EndNumber) {
495            found_end = true;
496            break;
497        }
498
499        let digit = resolver
500            .base64_digit_value(dc.to_u128())
501            .ok_or_else(|| anyhow!("Expected Base64 digit Dc, found {dc}"))?;
502        let ch = digit_to_base64_char(digit)?;
503        b64_str.push(ch);
504    }
505
506    ensure!(found_end, "Missing Dc 7 (End number) terminating Dc number");
507    ensure!(
508        !b64_str.is_empty(),
509        "Dc number contains no digit characters"
510    );
511
512    let b64_base = Base::new(64)?;
513    let nat = parse_natural(&b64_str, b64_base).with_context(|| {
514        format!("Failed to parse Base64 number string '{b64_str}'")
515    })?;
516
517    let int_val = Integer::from_sign_and_abs(!is_negative, nat);
518
519    Ok((int_val, idx))
520}
521
522/// Reads a single Dc number from a slice of Global Graph IDs (`DcList`),
523/// returning the parsed [`Integer`] and the number of tokens consumed from the slice.
524pub fn read_dc_number_global(gids: &[u128]) -> Result<(Integer, usize)> {
525    let resolver = ctb_formats_dcdata::syntax::default_syntax_resolver();
526    read_dc_number_global_with_resolver(gids, &**resolver)
527}
528
529/// Reads a single Dc number from a slice of Global Graph IDs (`DcList`)
530/// using the provided [`SyntaxRuleResolver`].
531pub fn read_dc_number_global_with_resolver(
532    gids: &[u128],
533    resolver: &dyn SyntaxRuleResolver,
534) -> Result<(Integer, usize)> {
535    let first = gids
536        .first()
537        .copied()
538        .ok_or_else(|| anyhow!("Empty GID stream"))?;
539    ensure!(
540        gid_fills_role(first, DcRole::BeginNumber, resolver),
541        "Expected GID 1114118 / Dc 6 (Begin number), found {first}"
542    );
543
544    let second = gids
545        .get(1)
546        .copied()
547        .ok_or_else(|| anyhow!("Unexpected end of stream after Dc 6"))?;
548    ensure!(
549        resolver.is_equivalent_to(second, DC_INTEGER.to_u128()),
550        "Expected format 199 indicator after Dc 6, found {second}"
551    );
552
553    let mut idx = 2usize;
554    let mut is_negative = false;
555
556    if let Some(&third) = gids.get(idx) {
557        if gid_fills_role(third, DcRole::Negative, resolver) {
558            is_negative = true;
559            idx = idx.saturating_add(1);
560        } else if gid_fills_role(third, DcRole::Positive, resolver) {
561            idx = idx.saturating_add(1);
562        }
563    }
564
565    let mut b64_str = String::new();
566    let mut found_end = false;
567
568    while idx < gids.len() {
569        let Some(&gid) = gids.get(idx) else { break };
570        idx = idx.saturating_add(1);
571
572        if gid_fills_role(gid, DcRole::EndNumber, resolver) {
573            found_end = true;
574            break;
575        }
576
577        let digit = gid_to_base64_digit(gid, resolver).ok_or_else(|| {
578            anyhow!("Global ID {gid} is not a valid Base64 encapsulation Dc")
579        })?;
580        let ch = digit_to_base64_char(digit)?;
581        b64_str.push(ch);
582    }
583
584    ensure!(
585        found_end,
586        "Missing GID 1114119 / Dc 7 (End number) terminating Dc number"
587    );
588    ensure!(
589        !b64_str.is_empty(),
590        "Dc number contains no digit characters"
591    );
592
593    let b64_base = Base::new(64)?;
594    let nat = parse_natural(&b64_str, b64_base).with_context(|| {
595        format!("Failed to parse Base64 number string '{b64_str}'")
596    })?;
597
598    let int_val = Integer::from_sign_and_abs(!is_negative, nat);
599
600    Ok((int_val, idx))
601}
602
603/// Parses an entire sequence of short Document Characters (Dcs) as a single Dc number.
604pub fn parse_dc_number_short(dcs: &[u32]) -> Result<Integer> {
605    let resolver = ctb_formats_dcdata::syntax::default_syntax_resolver();
606    parse_dc_number_short_with_resolver(dcs, &**resolver)
607}
608
609/// Parses an entire sequence of short Document Characters (Dcs) as a single Dc number
610/// using the provided [`SyntaxRuleResolver`].
611pub fn parse_dc_number_short_with_resolver(
612    dcs: &[u32],
613    resolver: &dyn SyntaxRuleResolver,
614) -> Result<Integer> {
615    let (val, consumed) = read_dc_number_short_with_resolver(dcs, resolver)?;
616    ensure!(
617        consumed == dcs.len(),
618        "Trailing tokens after Dc number: consumed {consumed} of {} tokens",
619        dcs.len()
620    );
621    Ok(val)
622}
623
624/// Parses an entire sequence of Global Graph IDs (`DcList`) as a single Dc number.
625pub fn parse_dc_number_global(gids: &[u128]) -> Result<Integer> {
626    let resolver = ctb_formats_dcdata::syntax::default_syntax_resolver();
627    parse_dc_number_global_with_resolver(gids, &**resolver)
628}
629
630/// Parses an entire sequence of Global Graph IDs (`DcList`) as a single Dc number
631/// using the provided [`SyntaxRuleResolver`].
632pub fn parse_dc_number_global_with_resolver(
633    gids: &[u128],
634    resolver: &dyn SyntaxRuleResolver,
635) -> Result<Integer> {
636    let (val, consumed) = read_dc_number_global_with_resolver(gids, resolver)?;
637    ensure!(
638        consumed == gids.len(),
639        "Trailing tokens after Dc number: consumed {consumed} of {} tokens",
640        gids.len()
641    );
642    Ok(val)
643}
644
645/// Parses an entire sequence of short Document Characters (Dcs) as an `i128`.
646pub fn parse_dc_number_short_i128(dcs: &[u32]) -> Result<i128> {
647    let val = parse_dc_number_short(dcs)?;
648    i128::try_from(&val)
649        .map_err(|e| anyhow!("Parsed Dc number exceeds i128 range: {e:?}"))
650}
651
652/// Parses an entire sequence of Global Graph IDs (`DcList`) as an `i128`.
653pub fn parse_dc_number_global_i128(gids: &[u128]) -> Result<i128> {
654    let val = parse_dc_number_global(gids)?;
655    i128::try_from(&val)
656        .map_err(|e| anyhow!("Parsed Dc number exceeds i128 range: {e:?}"))
657}
658
659#[cfg(test)]
660#[allow(
661    clippy::panic,
662    clippy::expect_used,
663    clippy::unwrap_used,
664    clippy::unwrap_in_result,
665    clippy::panic_in_result_fn,
666    clippy::indexing_slicing,
667    clippy::arithmetic_side_effects,
668    reason = "Standard repository test boilerplate"
669)]
670mod tests {
671    use super::*;
672
673    #[crate::ctb_test]
674    fn test_base64_char_to_short_dc_mappings() {
675        assert_eq!(base64_char_to_short_dc('A').unwrap(), 127);
676        assert_eq!(base64_char_to_short_dc('B').unwrap(), 128);
677        assert_eq!(base64_char_to_short_dc('Z').unwrap(), 152);
678        assert_eq!(base64_char_to_short_dc('a').unwrap(), 153);
679        assert_eq!(base64_char_to_short_dc('z').unwrap(), 178);
680        assert_eq!(base64_char_to_short_dc('0').unwrap(), 179);
681        assert_eq!(base64_char_to_short_dc('9').unwrap(), 188);
682        assert_eq!(base64_char_to_short_dc('+').unwrap(), 189);
683        assert_eq!(base64_char_to_short_dc('/').unwrap(), 190);
684        assert_eq!(base64_char_to_short_dc('=').unwrap(), 195);
685        base64_char_to_short_dc('$').unwrap_err();
686    }
687
688    #[crate::ctb_test]
689    fn test_short_dc_to_base64_char_mappings() {
690        assert_eq!(short_dc_to_base64_char(127).unwrap(), 'A');
691        assert_eq!(short_dc_to_base64_char(128).unwrap(), 'B');
692        assert_eq!(short_dc_to_base64_char(152).unwrap(), 'Z');
693        assert_eq!(short_dc_to_base64_char(153).unwrap(), 'a');
694        assert_eq!(short_dc_to_base64_char(178).unwrap(), 'z');
695        assert_eq!(short_dc_to_base64_char(179).unwrap(), '0');
696        assert_eq!(short_dc_to_base64_char(188).unwrap(), '9');
697        assert_eq!(short_dc_to_base64_char(189).unwrap(), '+');
698        assert_eq!(short_dc_to_base64_char(190).unwrap(), '/');
699        assert_eq!(short_dc_to_base64_char(195).unwrap(), '=');
700        short_dc_to_base64_char(191).unwrap_err();
701        short_dc_to_base64_char(126).unwrap_err();
702    }
703
704    #[crate::ctb_test]
705    fn test_base64_string_conversion_roundtrip() {
706        let text = "Hello+World/123==";
707        let dcs = base64_str_to_short_dcs(text).unwrap();
708        let roundtrip = short_dcs_to_base64_str(&dcs).unwrap();
709        assert_eq!(roundtrip, text);
710
711        let gids = base64_str_to_global_dcs(text).unwrap();
712        let g_roundtrip = global_dcs_to_base64_str(&gids).unwrap();
713        assert_eq!(g_roundtrip, text);
714    }
715
716    #[crate::ctb_test]
717    fn test_dc_number_short_roundtrip() {
718        // Zero: [6, 199, 127 ('A'), 7]
719        let zero_dcs = i128_to_dc_number_short(0).unwrap();
720        assert_eq!(zero_dcs, vec![6, 199, 127, 7]);
721        assert_eq!(parse_dc_number_short_i128(&zero_dcs).unwrap(), 0);
722
723        // 42: in base64 'q' (digit 42) -> short Dc 127 + 42 = 169
724        let dcs_42 = i128_to_dc_number_short(42).unwrap();
725        assert_eq!(dcs_42, vec![6, 199, 169, 7]);
726        assert_eq!(parse_dc_number_short_i128(&dcs_42).unwrap(), 42);
727
728        // -42: [6, 199, 11 (negative), 169 ('q'), 7]
729        let dcs_neg_42 = i128_to_dc_number_short(-42).unwrap();
730        assert_eq!(dcs_neg_42, vec![6, 199, 11, 169, 7]);
731        assert_eq!(parse_dc_number_short_i128(&dcs_neg_42).unwrap(), -42);
732
733        // Large number: 1_000_000
734        let dcs_large = i128_to_dc_number_short(1_000_000).unwrap();
735        assert_eq!(parse_dc_number_short_i128(&dcs_large).unwrap(), 1_000_000);
736    }
737
738    #[crate::ctb_test]
739    fn test_dc_number_global_roundtrip() {
740        // 42: [GID 1114118, GID 2228423, GID 1114281, GID 1114119]
741        let gids_42 = i128_to_dc_number_global(42).unwrap();
742        assert_eq!(gids_42, vec![1_114_118, 2_228_423, 1_114_281, 1_114_119]);
743        assert_eq!(parse_dc_number_global_i128(&gids_42).unwrap(), 42);
744
745        // -42: [GID 1114118, GID 2228423, GID 1114123 (neg), GID 1114281, GID 1114119]
746        let gids_neg = i128_to_dc_number_global(-42).unwrap();
747        assert_eq!(
748            gids_neg,
749            vec![1_114_118, 2_228_423, 1_114_123, 1_114_281, 1_114_119]
750        );
751        assert_eq!(parse_dc_number_global_i128(&gids_neg).unwrap(), -42);
752
753        // Read stream with trailing tokens
754        let mut stream = gids_42.clone();
755        stream.push(65); // Unicode 'A'
756        let (val, consumed) = read_dc_number_global(&stream).unwrap();
757        assert_eq!(val, Integer::from(42));
758        assert_eq!(consumed, 4);
759    }
760
761    #[crate::ctb_test]
762    fn test_dc_number_chars_and_reader_roundtrip() {
763        let test_cases = [
764            0i128,
765            1,
766            -1,
767            42,
768            -42,
769            64,
770            -64,
771            1_000_000,
772            -1_000_000,
773            i128::from(i64::MAX),
774            i128::from(i64::MIN),
775        ];
776        for &tc in &test_cases {
777            let chars = i128_to_dc_number_chars(tc).unwrap();
778            let mut it = chars.into_iter();
779            let parsed_int = read_dc_number_from_reader(|| {
780                it.next().ok_or_else(|| anyhow!("Unexpected end of stream"))
781            })
782            .unwrap();
783            assert_eq!(i128::try_from(&parsed_int).unwrap(), tc);
784        }
785
786        let u_cases = [
787            0u128,
788            1,
789            42,
790            64,
791            127,
792            255,
793            65535,
794            1_000_000,
795            u128::from(u64::MAX),
796            u128::MAX,
797        ];
798        for &tc in &u_cases {
799            let chars = u128_to_dc_number_chars(tc).unwrap();
800            let mut it = chars.into_iter();
801            let parsed_int = read_dc_number_from_reader(|| {
802                it.next().ok_or_else(|| anyhow!("Unexpected end of stream"))
803            })
804            .unwrap();
805            let nat = parsed_int.unsigned_abs_ref();
806            assert_eq!(u128::try_from(nat).unwrap(), tc);
807        }
808    }
809
810    #[crate::ctb_test]
811    fn test_dc_number_positive_sign_parsing() {
812        // [6, 199, 10 (positive), 169 ('q'), 7] -> 42
813        let dcs = vec![6, 199, 10, 169, 7];
814        assert_eq!(parse_dc_number_short_i128(&dcs).unwrap(), 42);
815
816        // Global graph GIDs
817        let gids = vec![1_114_118, 2_228_423, 1_114_122, 1_114_281, 1_114_119];
818        assert_eq!(parse_dc_number_global_i128(&gids).unwrap(), 42);
819
820        // parse_dc_number_digits with positive sign Dc 10
821        let digits_pos = vec![DcChar::from_short(10), DcChar::from_short(169)];
822        assert_eq!(
823            i128::try_from(&parse_dc_number_digits(&digits_pos).unwrap())
824                .unwrap(),
825            42
826        );
827
828        // parse_dc_number_digits with negative sign Dc 11
829        let digits_neg = vec![DcChar::from_short(11), DcChar::from_short(169)];
830        assert_eq!(
831            i128::try_from(&parse_dc_number_digits(&digits_neg).unwrap())
832                .unwrap(),
833            -42
834        );
835    }
836}