ctb_formats_dcstring/converters/
dctext.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//! Implements DcText and related formats DcList and DcUTF. These formats are
21//! encodings for sequences of integer global graph IDs (which are long Dcs).
22//! Format looks like (w/o backticks): `Unicode (UTF-8) text @123@miesu@214748364@@L662@`
23//! where `Unicode text` is actual unicode text, and between each pair of @ signs, is a DcId. A DcId can be any int 128 bits (u128) in decimal, and it may have an `L` prefix.
24//! Output format is sort of UTF-8 text. For normal Unicode input characters, the output character is the same. For DcIds less than or equal to 1114111 (the largest Unicode character, I believe), the output character is the corresponding "generalized UTF-8", the numeric value encoded in the same underlying algorithm as UTF-8. For DcIds greater than 1114111 and not prefixed with an L, the output character is the decimal DcId represented by extending the usual algorithm of UTF-8 encoding, but for those larger numbers. For DcIds prefixed with an L, the output is equivalent to @1114408@ (short Dc 296) followed by a Dc number for the number that followed the L (the L is just a shorthand for that 1114408 Dc). That is to say, it's not a true Unicode encoding, it's simply using an extension of the algorithm underlying UTF-8 as a convenient encoding of ints.
25//! Currently, DcList is used as the internal format for pivoting between other formats, but DcUtf might make more sense eventually for space efficiency.
26
27#[allow(
28    unused_imports,
29    clippy::wildcard_imports,
30    reason = "Standard workspace module prelude"
31)]
32use crate::utilities::*;
33
34use crate::DcString;
35use crate::dc_char::DcChar;
36use crate::dc_char::DcCharExt;
37use crate::dc_number::{
38    integer_to_dc_number_global, read_dc_number_global,
39    read_dc_number_global_with_resolver, read_dc_number_short,
40};
41use crate::dc_str::DcStr;
42use anyhow::Result;
43use ctb_formats_dcdata::dc::{DC_ESCAPE, DC_LOCAL_NODE, DC_LONG_DC};
44use ctb_formats_dcdata::syntax::{
45    DcRole, SyntaxRuleResolver, default_syntax_resolver,
46};
47use ctb_formats_dctf::{
48    decode_dctf, decode_utf_8e_128, encode_dctf_buf, encode_utf_8e_128_buf,
49};
50use ctb_formats_utilities::{ConversionOutput, FormatLog};
51
52/// A list of global graph Document Character IDs represented as `u128` values.
53pub type DcList = Vec<u128>;
54
55/// Parses a DcText document (`&[u8]`) into a `DcList` (`Vec<u128>`).
56///
57/// Plain text characters become their corresponding Unicode codepoint IDs (`0..=0x10FFFF`).
58/// Tokens in `@<dcid>@` format are parsed into `u128` values.
59/// `@L<number>@` tokens expand to `1114408` followed by the Dc number representation of `<number>`.
60/// `@@` tokens represent codepoint `64` (`@`).
61///
62/// # Errors
63/// Parses a DcText document (`&[u8]`) directly into a `DcString`.
64///
65/// Plain text characters become their corresponding Unicode codepoint IDs (`0..=0x10FFFF`).
66/// Tokens in `@<dcid>@` format are parsed into `u128` values.
67/// `@L<number>@` tokens expand to `1114408` followed by the Dc number representation of `<number>`.
68/// `@@` tokens represent codepoint `64` (`@`).
69///
70/// # Errors
71/// Returns an error if the document contains invalid UTF-8 or malformed syntax.
72pub fn dctext_to_dcstring(
73    document: &[u8],
74) -> Result<ConversionOutput<DcString>> {
75    let mut log = FormatLog::default();
76    let mut dc_string = DcString::with_capacity(document.len());
77    let mut i = 0usize;
78
79    while i < document.len() {
80        let Some(slice) = document.get(i..) else {
81            break;
82        };
83        let Some(&first_byte) = slice.first() else {
84            break;
85        };
86
87        if first_byte == b'@' {
88            if let Some(rest) = slice.get(1..) {
89                if let Some(end_rel) = rest.iter().position(|&b| b == b'@') {
90                    if let Some(token_bytes) = rest.get(..end_rel) {
91                        if let Ok(token_str) = std::str::from_utf8(token_bytes)
92                        {
93                            if token_str.is_empty() {
94                                // @@ token represents @ (codepoint 64)
95                                dc_string.push(DcChar(64u128));
96                                i = i.saturating_add(2);
97                                continue;
98                            }
99
100                            if let Ok(ctb_storage_minimal::shorthand::DcShorthand::Local(int_val)) =
101                                ctb_storage_minimal::shorthand::DcShorthand::parse(token_str)
102                            {
103                                let malachite_val = malachite::Integer::from(int_val);
104                                match integer_to_dc_number_global(&malachite_val) {
105                                    Ok(dc_num_gids) => {
106                                        dc_string.push(DC_LOCAL_NODE);
107                                        for gid in dc_num_gids {
108                                            dc_string.push(DcChar(gid));
109                                        }
110                                        i = i
111                                            .saturating_add(2)
112                                            .saturating_add(end_rel);
113                                        continue;
114                                    }
115                                    Err(e) => {
116                                        log.warn(&format!(
117                                            "Failed to encode Dc number for local node @{token_str}@: {e}"
118                                        ));
119                                    }
120                                }
121                            } else if let Ok(dcid) = token_str.parse::<u128>() {
122                                dc_string.push(DcChar(dcid));
123                                i = i.saturating_add(2).saturating_add(end_rel);
124                                continue;
125                            }
126                        }
127                    }
128                }
129            }
130        }
131
132        if let Some((codepoint, size)) =
133            ctb_formats_dctf::decode_dctf_buf(slice)
134        {
135            dc_string.push(DcChar(codepoint));
136            i = i.saturating_add(size);
137        } else if let Some((codepoint, size)) =
138            ctb_formats_dctf::decode_utf_8e_128_buf(slice)
139        {
140            dc_string.push(DcChar(codepoint));
141            i = i.saturating_add(size);
142        } else if let Some((codepoint, size)) = decode_dctf(slice) {
143            dc_string.push(DcChar(codepoint));
144            i = i.saturating_add(size);
145        } else {
146            dc_string.push(DcChar(u128::from(first_byte)));
147            i = i.saturating_add(1);
148        }
149    }
150
151    Ok(ConversionOutput::new(dc_string, log))
152}
153
154/// Parses a DcText document (`&[u8]`) into a `DcList` (`Vec<u128>`).
155///
156/// # Errors
157/// Returns an error if the document contains invalid UTF-8 or malformed syntax.
158pub fn dctext_to_dclist(document: &[u8]) -> Result<ConversionOutput<DcList>> {
159    let out = dctext_to_dcstring(document)?;
160    Ok(ConversionOutput::new(out.result.to_dclist(), out.log))
161}
162
163/// Serializes a `DcList` (`&[u128]`) to DcText format bytes (`Vec<u8>`).
164pub fn dclist_to_dctext(dclist: &[u128]) -> Vec<u8> {
165    dclist_to_dctext_with_resolver(dclist, default_syntax_resolver().as_ref())
166}
167
168/// Serializes a `DcList` (`&[u128]`) to DcText format bytes (`Vec<u8>`) using the given resolver.
169pub fn dclist_to_dctext_with_resolver(
170    dclist: &[u128],
171    resolver: &dyn SyntaxRuleResolver,
172) -> Vec<u8> {
173    let mut output = String::new();
174    let mut i = 0;
175    while i < dclist.len() {
176        let Some(&dcid) = dclist.get(i) else { break };
177
178        if dcid == 64 {
179            output.push_str("@@");
180        } else if dcid <= 0x10_FFFF {
181            if let Ok(cp) = u32::try_from(dcid) {
182                if let Some(ch) = char::from_u32(cp) {
183                    output.push(ch);
184                } else {
185                    output.push_str(&format!("@{dcid}@"));
186                }
187            } else {
188                output.push_str(&format!("@{dcid}@"));
189            }
190        } else if resolver.token_fills_role(dcid, DcRole::LocalNode) {
191            if let Some(rest) = dclist.get(i.saturating_add(1)..) {
192                if let Ok((int_val, consumed)) =
193                    read_dc_number_global_with_resolver(rest, resolver)
194                {
195                    output.push_str(&format!("@L{int_val}@"));
196                    i = i.saturating_add(1).saturating_add(consumed);
197                    continue;
198                }
199            }
200            output.push_str(&format!("@{dcid}@"));
201        } else {
202            output.push_str(&format!("@{dcid}@"));
203        }
204        i = i.saturating_add(1);
205    }
206    output.into_bytes()
207}
208
209/// Converts a `DcList` (`&[u128]`) to DcTF bytes.
210pub fn dclist_to_dctf(dclist: &[u128]) -> Vec<u8> {
211    let mut output = Vec::new();
212    let mut buf = [0u8; 24];
213    for &dcid in dclist {
214        let n = encode_dctf_buf(&mut buf, dcid);
215        if let Some(slice) = buf.get(..n) {
216            output.extend_from_slice(slice);
217        }
218    }
219    output
220}
221
222/// Decodes DcTF bytes into a `DcList` (`Vec<u128>`).
223pub fn dctf_to_dclist(document: &[u8]) -> DcList {
224    let mut list = Vec::new();
225    let mut i = 0;
226    while i < document.len() {
227        let Some(slice) = document.get(i..) else {
228            break;
229        };
230        if let Some((codepoint, size)) = decode_dctf(slice) {
231            list.push(codepoint);
232            i = i.saturating_add(size);
233        } else {
234            if let Some(&b) = document.get(i) {
235                list.push(u128::from(b));
236            }
237            i = i.saturating_add(1);
238        }
239    }
240    list
241}
242
243/// Converts a `DcList` (`&[u128]`) to legacy generalized UTF-8 bytes (`DcUtf`).
244pub fn dclist_to_dcutf(dclist: &[u128]) -> Vec<u8> {
245    let mut output = Vec::new();
246    let mut buf = [0u8; 24];
247    for &dcid in dclist {
248        let n = encode_utf_8e_128_buf(&mut buf, dcid);
249        if let Some(slice) = buf.get(..n) {
250            output.extend_from_slice(slice);
251        }
252    }
253    output
254}
255
256/// Decodes generalized UTF-8 bytes (`DcUtf`) into a `DcList` (`Vec<u128>`).
257pub fn dcutf_to_dclist(document: &[u8]) -> DcList {
258    let mut list = Vec::new();
259    let mut i = 0;
260    while i < document.len() {
261        let Some(slice) = document.get(i..) else {
262            break;
263        };
264        if let Some((codepoint, size)) = decode_utf_8e_128(slice) {
265            list.push(codepoint);
266            i = i.saturating_add(size);
267        } else {
268            if let Some(&b) = document.get(i) {
269                list.push(u128::from(b));
270            }
271            i = i.saturating_add(1);
272        }
273    }
274    list
275}
276
277/// Parses a DcText document (`&[u8]`) directly into a `DcString`.
278///
279/// Converts an EITE DcArray (short Dcs, `&[u32]`) to a `DcString`.
280pub fn dcarray_to_dcstring(
281    dc_array: &[u32],
282) -> Result<ConversionOutput<DcString>> {
283    let conv = dcarray_to_dclist(dc_array)?;
284    let mut dc_string = DcString::with_capacity(conv.result.len());
285    for &dc in &conv.result {
286        dc_string.push(DcChar(dc));
287    }
288    Ok(ConversionOutput::new(dc_string, conv.log))
289}
290
291/// Converts a `DcStr` to an EITE DcArray (short Dcs, `Vec<u32>`).
292pub fn dcstring_to_dcarray(s: &DcStr) -> Result<ConversionOutput<Vec<u32>>> {
293    dclist_to_dcarray(&s.to_dclist())
294}
295
296/// Serializes a `DcStr` to DcText format bytes (`Vec<u8>`).
297#[must_use]
298pub fn dcstring_to_dctext(s: &DcStr) -> Vec<u8> {
299    let dclist = s.to_dclist();
300    dclist_to_dctext(&dclist)
301}
302
303/// Converts a DcText document to `DcMstring`.
304pub fn dctext_to_dcmstring(
305    bytes: &[u8],
306) -> Result<(crate::DcMstring, FormatLog)> {
307    dctext_to_dcmstring_with_options(bytes, false)
308}
309
310/// Converts a DcText document to `DcMstring`, optionally in permissive mode.
311pub fn dctext_to_dcmstring_with_options(
312    bytes: &[u8],
313    permissive: bool,
314) -> Result<(crate::DcMstring, FormatLog)> {
315    let conv = dctext_to_dcstring(bytes)?;
316    if !permissive && conv.log.has_errors() {
317        bail!(
318            "Invalid DcText token(s): {}",
319            conv.log.get_errors().join("; ")
320        );
321    }
322    let policy = if permissive {
323        crate::DcProjectionPolicy::forgiving()
324    } else {
325        crate::DcProjectionPolicy::strict()
326    };
327    let doc =
328        crate::DcMstring::from_dc_string_with_policy(&conv.result, &policy)?;
329    Ok((doc, conv.log))
330}
331
332/// Converts a `DcMstring` to DcText bytes.
333pub fn dcmstring_to_dctext(
334    doc: &crate::DcMstring,
335) -> Result<(Vec<u8>, FormatLog)> {
336    let dc_string = super::document_dc_string(doc)?;
337    let bytes = dcstring_to_dctext(&dc_string);
338    Ok((bytes, FormatLog::default()))
339}
340
341/// Converts DcText format bytes to DcTF format bytes.
342///
343/// # Errors
344/// Returns an error if the document cannot be parsed into a `DcString`.
345pub fn dctext_to_dctf(document: Vec<u8>) -> Result<Vec<u8>> {
346    let out = dctext_to_dcstring(&document)?;
347    out.log.auto_log();
348    Ok(out.result.into_bytes())
349}
350
351/// Converts DcTF format bytes to DcText format bytes.
352#[must_use]
353pub fn dctf_to_dctext(document: Vec<u8>) -> Vec<u8> {
354    let dclist = dctf_to_dclist(&document);
355    dclist_to_dctext(&dclist)
356}
357
358/// Converts DcText format bytes to legacy DcUtf format bytes.
359///
360/// # Errors
361/// Returns an error if the document cannot be parsed into a `DcString`.
362pub fn dctext_to_dcutf(document: Vec<u8>) -> Result<Vec<u8>> {
363    let out = dctext_to_dcstring(&document)?;
364    out.log.auto_log();
365    Ok(dclist_to_dcutf(&out.result.to_dclist()))
366}
367
368/// Converts legacy DcUtf format bytes to DcText format bytes.
369#[must_use]
370pub fn dcutf_to_dctext(document: Vec<u8>) -> Vec<u8> {
371    let dclist = dcutf_to_dclist(&document);
372    dclist_to_dctext(&dclist)
373}
374
375/// Converts an EITE DcArray (short Dcs, `&[u32]`) to a `DcList` (`Vec<u128>`).
376///
377/// Handles:
378/// - Escaped Dc 308 (`[255, 308]` -> long Dc `1_114_420`).
379/// - Escaped Dc 255 (`[255, 255]` -> long Dc `1_114_367`).
380/// - Standalone Dc 255 (`[255]` -> long Dc `1_114_367`).
381/// - Embedded long Dc IDs (`[308, ...DcNumber...]` -> decoded `u128` long Dc ID).
382/// - Direct short Dcs `c` -> mapped to `SHORT_DC_OFFSET + c` (`1_114_112 + c`).
383pub fn dcarray_to_dclist(dc_array: &[u32]) -> Result<ConversionOutput<DcList>> {
384    let mut log = FormatLog::default();
385    let mut list = Vec::with_capacity(dc_array.len());
386    let mut i = 0usize;
387
388    while i < dc_array.len() {
389        let Some(&raw_dc) = dc_array.get(i) else {
390            break;
391        };
392        let dc = DcChar::from_short(raw_dc);
393
394        if dc.fills_role(DcRole::Escape) {
395            if let Some(&next_raw) = dc_array.get(i.saturating_add(1)) {
396                let next_dc = DcChar::from_short(next_raw);
397                if next_dc.fills_role(DcRole::LongDc) {
398                    list.push(DC_LONG_DC.to_long());
399                    i = i.saturating_add(2);
400                    continue;
401                }
402                if next_dc.fills_role(DcRole::Escape) {
403                    list.push(DC_ESCAPE.to_long());
404                    i = i.saturating_add(2);
405                    continue;
406                }
407            }
408            list.push(DC_ESCAPE.to_long());
409            i = i.saturating_add(1);
410            continue;
411        }
412
413        if dc.fills_role(DcRole::LongDc) {
414            if let Some(rest) = dc_array.get(i.saturating_add(1)..) {
415                match read_dc_number_short(rest) {
416                    Ok((int_val, consumed)) => {
417                        if int_val >= 0 {
418                            if let Ok(abs_u128) =
419                                u128::try_from(int_val.unsigned_abs_ref())
420                            {
421                                list.push(abs_u128);
422                                i = i
423                                    .saturating_add(1)
424                                    .saturating_add(consumed);
425                                continue;
426                            }
427                        }
428                        log.warn(&format!(
429                            "Embedded long Dc ID {int_val} at index {i} cannot be represented as u128"
430                        ));
431                    }
432                    Err(e) => {
433                        log.warn(&format!(
434                            "Unescaped Dc 308 at index {i} not followed by valid Dc number: {e}"
435                        ));
436                    }
437                }
438            } else {
439                log.warn(&format!(
440                    "Unescaped Dc 308 at end of stream (index {i}) missing Dc number"
441                ));
442            }
443            list.push(DC_LONG_DC.to_long());
444            i = i.saturating_add(1);
445            continue;
446        }
447
448        if raw_dc > ctb_formats_eite::encoding::pack32::PACK32_MAX {
449            log.warn(&format!(
450                "Short Dc ID {raw_dc} at index {i} exceeds pack32 maximum range (1114111)"
451            ));
452        }
453
454        list.push(dc.to_long());
455        i = i.saturating_add(1);
456    }
457
458    Ok(ConversionOutput::new(list, log))
459}
460
461/// Converts an EITE DcArray (short Dcs, `&[u32]`) to the DcText format (`Vec<u8>`).
462pub fn dcarray_to_dctext(
463    dc_array: &[u32],
464) -> Result<ConversionOutput<Vec<u8>>> {
465    let conv = dcarray_to_dclist(dc_array)?;
466    let text_bytes = dclist_to_dctext(&conv.result);
467    Ok(ConversionOutput::new(text_bytes, conv.log))
468}
469
470/// Converts a `DcList` (`&[u128]`) to an EITE DcArray (short Dcs, `Vec<u32>`).
471///
472/// Directly represents Document Characters in range `1_114_112..=2_228_223`
473/// ([`SHORT_DC_REGION_START`]..=[`SHORT_DC_REGION_END`], short IDs `0..=1_114_111`),
474/// with escaping for Dc 308 (`[255, 308]`) and Dc 255 (`[255, 255]`).
475/// All other long Dcs (`<= 0x10_FFFF` Unicode codepoints and `> 2_228_223` out-of-range IDs)
476/// are embedded via Dc 308 (`[308, ...u128_to_dc_number_short(dcid)...]`).
477pub fn dclist_to_dcarray(
478    dclist: &[u128],
479) -> Result<ConversionOutput<Vec<u32>>> {
480    let log = FormatLog::default();
481    let mut result = Vec::new();
482
483    for &dcid in dclist {
484        result.extend(DcChar::from_long(dcid).to_short_vec());
485    }
486
487    Ok(ConversionOutput::new(result, log))
488}
489
490/// Converts a DcText document (`&[u8]`) to an EITE DcArray (short Dcs, `Vec<u32>`).
491pub fn dctext_to_dcarray(
492    document: &[u8],
493) -> Result<ConversionOutput<Vec<u32>>> {
494    let conv = dctext_to_dclist(document)?;
495    let array_conv = dclist_to_dcarray(&conv.result)?;
496    let mut total_log = conv.log;
497    total_log.merge(&array_conv.log);
498    Ok(ConversionOutput::new(array_conv.result, total_log))
499}
500
501/// Formats a byte slice as a displayable preview string.
502/// If `is_dctext` is true, first converts DcText to plain text.
503/// If the text is displayable (only graphic/whitespace chars), truncates it to
504/// 60 chars and returns it. Otherwise, returns a `<binary data: N bytes>` preview.
505pub fn format_blob_preview(data: &[u8], is_dctext: bool) -> String {
506    let raw_bytes = if is_dctext {
507        dctf_to_dctext(data.to_vec())
508    } else {
509        data.to_vec()
510    };
511    if let Ok(s) = String::from_utf8(raw_bytes) {
512        let displayable = s
513            .chars()
514            .all(|c| c.is_ascii_graphic() || c.is_ascii_whitespace());
515        if displayable {
516            if s.len() > 60 {
517                let truncated: String = s.chars().take(60).collect();
518                if s.chars().count() > 60 {
519                    format!("{truncated}...")
520                } else {
521                    truncated
522                }
523            } else {
524                s
525            }
526        } else {
527            format!("<binary data: {} bytes>", data.len())
528        }
529    } else {
530        format!("<binary data: {} bytes>", data.len())
531    }
532}
533
534#[cfg(test)]
535#[allow(
536    clippy::panic,
537    clippy::expect_used,
538    clippy::unwrap_used,
539    clippy::unwrap_in_result,
540    clippy::panic_in_result_fn,
541    clippy::indexing_slicing,
542    clippy::arithmetic_side_effects,
543    reason = "Standard repository test boilerplate"
544)]
545mod tests {
546    use super::*;
547    use ctb_formats_dcdata::DC_INTEGER;
548    use ctb_formats_dcdata::dc::{
549        DC_BASE64_START, DC_BEGIN_NUMBER, DC_END_NUMBER, SHORT_DC_REGION_START,
550    };
551
552    #[crate::ctb_test]
553    fn test_format_blob_preview() {
554        assert_eq!(format_blob_preview(b"hello world", false), "hello world");
555        assert_eq!(
556            format_blob_preview(&[0u8, 1u8, 2u8], false),
557            "<binary data: 3 bytes>"
558        );
559        let long_str = "a".repeat(70);
560        assert_eq!(
561            format_blob_preview(long_str.as_bytes(), false),
562            format!("{}...", "a".repeat(60))
563        );
564        let dctf_redirect = dctext_to_dctf(b"@1114409@@L42@".to_vec()).unwrap();
565        assert_eq!(format_blob_preview(&dctf_redirect, true), "@1114409@@L42@");
566    }
567
568    #[crate::ctb_test]
569    fn test_dctext_to_dcutf() {
570        let text = "hi @64@ @@ @65@ @128@ there 🥴 @L42@ noncharacter @1114111@ surrogate @56191@ unicode null @0@ dc null @1114112@ @2147483648@ 2^128-1 @340282366920938463463374607431768211455@";
571        let dcutf = dctext_to_dcutf(text.as_bytes().to_vec()).unwrap();
572        assert_eq!(
573            "686920402040204120c28020746865726520f09fa5b420ff84849084a8ff8484908086ff8488a08387ff84849082a9ff8484908087206e6f6e63686172616374657220f48fbfbf20737572726f6761746520edadbf20756e69636f6465206e756c6c2000206463206e756c6c20ff848490808020ff8682808080808020325e3132382d3120ff9683bfbfbfbfbfbfbfbfbfbfbfbfbfbfbfbfbfbfbfbfbf",
574            bin2hex(&dcutf)
575        );
576
577        let roundtrip = dcutf_to_dctext(dcutf.clone());
578        let roundtrip_str = String::from_utf8(roundtrip).unwrap();
579
580        // Should match original
581        let expected_roundtrip = "hi @@ @@ A \u{80} there 🥴 @L42@ noncharacter \u{10ffff} surrogate @56191@ unicode null \u{0} dc null @1114112@ @2147483648@ 2^128-1 @340282366920938463463374607431768211455@";
582        assert!(roundtrip_str.eq(expected_roundtrip));
583    }
584
585    #[crate::ctb_test]
586    fn test_dctext_to_dcstring() {
587        let text = "hi @64@ @@ @65@ @128@ there 🥴 @L42@";
588        let out = dctext_to_dcstring(text.as_bytes()).unwrap();
589        let dc_string = out.result;
590        assert_eq!(
591            dc_string.as_bytes(),
592            dctext_to_dctf(text.as_bytes().to_vec()).unwrap().as_slice()
593        );
594
595        let roundtrip = dcstring_to_dctext(&dc_string);
596        let roundtrip_str = String::from_utf8(roundtrip).unwrap();
597        assert_eq!(roundtrip_str, "hi @@ @@ A \u{80} there 🥴 @L42@");
598    }
599
600    #[crate::ctb_test]
601    fn test_dcarray_to_dctext_and_back() {
602        let original_dcarray = vec![0, 1, 18, 50, 200, 297];
603        let converted = dcarray_to_dctext(&original_dcarray)
604            .expect("conversion should succeed");
605        assert!(!converted.log.has_warnings());
606        assert_eq!(
607            String::from_utf8(converted.result.clone()).expect("valid utf-8"),
608            "@1114112@@1114113@@1114130@@1114162@@1114312@@1114409@"
609        );
610
611        let back = dctext_to_dcarray(&converted.result)
612            .expect("reverse conversion should succeed");
613        assert!(!back.log.has_warnings());
614        assert_eq!(back.result, original_dcarray);
615    }
616
617    #[crate::ctb_test]
618    fn test_dctext_to_dcarray_direct_short_dc() {
619        // DcText Dc ID 1114500 (offset 388, valid direct short Dc)
620        let input = b"@1114500@";
621        let out = dctext_to_dcarray(input).expect("conversion should succeed");
622        assert!(!out.log.has_warnings());
623        assert_eq!(out.result, vec![388]);
624
625        let back = dcarray_to_dclist(&out.result)
626            .expect("reverse conversion should succeed");
627        assert_eq!(back.result, vec![1_114_500]);
628    }
629
630    #[crate::ctb_test]
631    fn test_dclist_to_dcarray_dc308_embedding_roundtrip() {
632        // Format ID (2228423), 32-bit+ ID (4294967296), and large global ID (100000000000)
633        let original_dclist = vec![2_228_423, 4_294_967_296, 100_000_000_000];
634        let array_out =
635            dclist_to_dcarray(&original_dclist).expect("should succeed");
636        assert!(!array_out.log.has_warnings());
637        assert!(array_out.result.contains(&DC_LONG_DC.to_short().unwrap()));
638
639        let back = dcarray_to_dclist(&array_out.result)
640            .expect("reverse conversion should succeed");
641        assert!(!back.log.has_warnings());
642        assert_eq!(back.result, original_dclist);
643    }
644
645    #[crate::ctb_test]
646    fn test_dclist_to_dcarray_unicode_lossless_roundtrip() {
647        // Unicode codepoints: 'A' (65), ' ' (32), emoji 🥴 (129396), surrogate 0xD800 (55296)
648        let original_dclist = vec![65, 32, 129_396, 55_296];
649        let array_out =
650            dclist_to_dcarray(&original_dclist).expect("should succeed");
651        assert!(!array_out.log.has_warnings());
652        assert!(array_out.result.contains(&DC_LONG_DC.to_short().unwrap()));
653
654        let back = dcarray_to_dclist(&array_out.result)
655            .expect("reverse conversion should succeed");
656        assert!(!back.log.has_warnings());
657        assert_eq!(back.result, original_dclist);
658    }
659
660    #[crate::ctb_test]
661    fn test_dc308_escaping_roundtrip() {
662        // Long Dc 1114420 (Dc 308) escaped with 255 -> [255, 308]
663        let original_dclist = vec![DC_LONG_DC.to_long()];
664        let array_out =
665            dclist_to_dcarray(&original_dclist).expect("should succeed");
666        assert_eq!(
667            array_out.result,
668            vec![
669                DC_ESCAPE.to_short().unwrap(),
670                DC_LONG_DC.to_short().unwrap()
671            ]
672        );
673
674        let back = dcarray_to_dclist(&array_out.result)
675            .expect("reverse conversion should succeed");
676        assert_eq!(back.result, original_dclist);
677    }
678
679    #[crate::ctb_test]
680    fn test_dc255_escaping_roundtrip() {
681        // Long Dc 1114367 (Dc 255) escaped with 255 -> [255, 255]
682        let original_dclist = vec![DC_ESCAPE.to_long()];
683        let array_out =
684            dclist_to_dcarray(&original_dclist).expect("should succeed");
685        assert_eq!(
686            array_out.result,
687            vec![DC_ESCAPE.to_short().unwrap(), DC_ESCAPE.to_short().unwrap()]
688        );
689
690        let back = dcarray_to_dclist(&array_out.result)
691            .expect("reverse conversion should succeed");
692        assert_eq!(back.result, original_dclist);
693    }
694
695    #[crate::ctb_test]
696    fn test_dc308_followed_by_dc_number_disambiguation() {
697        // Long Dc 1114420 followed by a Dc number in DcList
698        let original_dclist = vec![
699            DC_LONG_DC.to_long(),
700            DC_BEGIN_NUMBER.to_long(),
701            DC_INTEGER.to_long(),
702            DC_BASE64_START.to_long(),
703            DC_END_NUMBER.to_long(),
704        ];
705        let array_out =
706            dclist_to_dcarray(&original_dclist).expect("should succeed");
707        assert_eq!(
708            array_out.result.get(0..2),
709            Some(
710                &[
711                    DC_ESCAPE.to_short().unwrap(),
712                    DC_LONG_DC.to_short().unwrap()
713                ][..]
714            )
715        );
716
717        let back = dcarray_to_dclist(&array_out.result)
718            .expect("reverse conversion should succeed");
719        assert_eq!(back.result, original_dclist);
720    }
721
722    #[crate::ctb_test]
723    fn test_dcarray_to_dclist_standalone_dc308() {
724        // Standalone short Dc 308 not followed by a Dc number (graceful fallback)
725        let dc_array = vec![DC_LONG_DC.to_short().unwrap(), 65];
726        let back = dcarray_to_dclist(&dc_array).expect("should succeed");
727        assert!(back.log.has_warnings());
728        assert_eq!(
729            back.result,
730            vec![
731                DC_LONG_DC.to_long(),
732                SHORT_DC_REGION_START.saturating_add(65)
733            ]
734        );
735    }
736
737    #[crate::ctb_test]
738    fn test_dclist_roundtrip() {
739        let text = b"hi @1114112@ @L42@ @2147483648@";
740        let dclist_out = dctext_to_dclist(text).expect("should succeed");
741        assert!(!dclist_out.log.has_warnings());
742
743        let restored_text = dclist_to_dctext(&dclist_out.result);
744        assert_eq!(
745            std::str::from_utf8(&restored_text).unwrap(),
746            "hi @1114112@ @L42@ @2147483648@"
747        );
748    }
749
750    // #[crate::ctb_test]
751    // fn test_dctext_to_dcarray_lossy_warnings() {
752    //     // Out-of-range DcText Dc ID (e.g. 1114500)
753    //     let lossy_input = b"@1114500@";
754    //     let out =
755    //         dctext_to_dcarray(lossy_input).expect("conversion should succeed");
756    //     assert!(out.log.has_warnings());
757    //     assert_eq!(out.result, vec![207]);
758    // }
759
760    // #[crate::ctb_test]
761    // fn test_dctext_to_dcarray_encapsulated_utf8() {
762    //     // Unmappable UTF-8 character 🥴 (U+1F974)
763    //     let unmappable_input = "hi 🥴 bye".as_bytes();
764    //     let out = dctext_to_dcarray(unmappable_input)
765    //         .expect("conversion should succeed");
766    //     assert!(out.log.has_warnings());
767    //     // Should contain short Dcs for "hi ", then 191 (start encapsulation), Base64 Dcs, 192 (end encapsulation), then " bye"
768    //     assert!(out.result.contains(&191));
769    //     assert!(out.result.contains(&192));
770    // }
771}