ctb_formats_dcstring/converters/
dcal.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Implementation of Format 340 (Dcal: Dc ASCII List).
21//!
22//! ASCII text containing a list of integers representing long Dcs. Strictly, one
23//! space after every int, and no newlines. Loosely, with newlines or multiple
24//! spaces, or no end space.
25
26#[allow(
27    unused_imports,
28    clippy::wildcard_imports,
29    reason = "Standard workspace module prelude"
30)]
31use crate::utilities::*;
32
33use anyhow::Result;
34use ctb_formats_utilities::{ConversionOutput, FormatLog};
35
36use super::dctext::DcList;
37
38/// Converts a Dcal document (`&[u8]`) into a `DcList` (`Vec<u128>`).
39///
40/// Strictly: ASCII decimal integers with one space after every integer.
41/// Loosely: ASCII text containing decimal integers separated by whitespace.
42pub fn dcal_to_dclist(document: &[u8]) -> Result<ConversionOutput<DcList>> {
43    let mut log = FormatLog::default();
44    let text = match std::str::from_utf8(document) {
45        Ok(s) => s,
46        Err(e) => {
47            log.warn(&format!("Invalid UTF-8 in Dcal input: {e}"));
48            return Ok(ConversionOutput::new(Vec::new(), log));
49        }
50    };
51
52    let mut list = Vec::new();
53    for token in text.split_ascii_whitespace() {
54        if !token.bytes().all(|b| b.is_ascii_digit()) {
55            log.warn(&format!("Skipping non-integer Dcal token '{token}'"));
56            continue;
57        }
58        match token.parse::<u128>() {
59            Ok(id) => list.push(id),
60            Err(e) => {
61                log.warn(&format!("Failed to parse integer '{token}': {e}"));
62            }
63        }
64    }
65
66    Ok(ConversionOutput::new(list, log))
67}
68
69/// Serializes a `DcList` (`&[u128]`) to Dcal format bytes (`Vec<u8>`).
70///
71/// Strictly outputs one space after every integer in standard decimal format.
72pub fn dclist_to_dcal(dclist: &[u128]) -> Vec<u8> {
73    let mut output = String::new();
74    for &id in dclist {
75        output.push_str(&format!("{id} "));
76    }
77    output.into_bytes()
78}
79
80/// Converts a Dcal document to `DcMstring`.
81pub fn dcal_to_dcmstring(
82    bytes: &[u8],
83) -> Result<(crate::DcMstring, FormatLog)> {
84    dcal_to_dcmstring_with_options(bytes, false)
85}
86
87/// Converts a Dcal document to `DcMstring`, optionally in permissive mode.
88pub fn dcal_to_dcmstring_with_options(
89    bytes: &[u8],
90    permissive: bool,
91) -> Result<(crate::DcMstring, FormatLog)> {
92    if !permissive {
93        let text = std::str::from_utf8(bytes)
94            .map_err(|e| anyhow::anyhow!("Invalid UTF-8 in Dcal input: {e}"))?;
95        let mut list = Vec::new();
96        for token in text.split_ascii_whitespace() {
97            if !token.bytes().all(|b| b.is_ascii_digit()) {
98                bail!("Invalid non-integer Dcal token '{token}'");
99            }
100            let id = token.parse::<u128>().with_context(|| {
101                format!("Failed to parse Dcal integer '{token}'")
102            })?;
103            list.push(id);
104        }
105        let dctf_bytes = super::dctext::dclist_to_dctf(&list);
106        let dc_str = crate::DcStr::from_bytes(&dctf_bytes)
107            .context("Converting dcal list to valid DcTF DcStr")?;
108        let doc = crate::DcMstring::from_dc_str(dc_str)?;
109        return Ok((doc, FormatLog::default()));
110    }
111
112    let conv = dcal_to_dclist(bytes)?;
113    let dctf_bytes = super::dctext::dclist_to_dctf(&conv.result);
114    let dc_str = crate::DcStr::from_bytes(&dctf_bytes)
115        .context("Converting dcal list to valid DcTF DcStr")?;
116    let doc = crate::DcMstring::from_dc_str(dc_str)?;
117    Ok((doc, conv.log))
118}
119
120/// Converts a `DcMstring` to Dcal bytes.
121pub fn dcmstring_to_dcal(
122    doc: &crate::DcMstring,
123) -> Result<(Vec<u8>, FormatLog)> {
124    let dc_string = super::document_dc_string(doc)?;
125    let dclist = dc_string.to_dclist();
126    let bytes = dclist_to_dcal(&dclist);
127    Ok((bytes, FormatLog::default()))
128}
129
130/// Converts a Csdl (Format 344: comma-separated Dc list of long Dcs) document to `DcMstring`.
131pub fn csdl_to_dcmstring(
132    bytes: &[u8],
133) -> Result<(crate::DcMstring, FormatLog)> {
134    csdl_to_dcmstring_with_options(bytes, false)
135}
136
137/// Converts a Csdl document to `DcMstring`, optionally in permissive mode.
138pub fn csdl_to_dcmstring_with_options(
139    bytes: &[u8],
140    permissive: bool,
141) -> Result<(crate::DcMstring, FormatLog)> {
142    let mut log = FormatLog::default();
143    let text_cow = if permissive {
144        match std::str::from_utf8(bytes) {
145            Ok(s) => std::borrow::Cow::Borrowed(s),
146            Err(e) => {
147                log.warn(&format!("Invalid UTF-8 in Csdl input: {e}"));
148                String::from_utf8_lossy(bytes)
149            }
150        }
151    } else {
152        let s = std::str::from_utf8(bytes)
153            .map_err(|e| anyhow::anyhow!("Invalid UTF-8 in Csdl input: {e}"))?;
154        std::borrow::Cow::Borrowed(s)
155    };
156
157    if !text_cow.contains(',') {
158        return dcal_to_dcmstring_with_options(bytes, permissive);
159    }
160
161    let mut list = Vec::new();
162    for segment in text_cow.split(',') {
163        let trimmed = segment.trim();
164        if trimmed.is_empty() {
165            continue;
166        }
167        let sub_tokens: Vec<&str> = trimmed.split_ascii_whitespace().collect();
168        if sub_tokens.len() > 1 {
169            if !permissive {
170                bail!(
171                    "Csdl input mixes comma-separated and space-separated tokens without commas: '{trimmed}'"
172                );
173            }
174            log.warn(&format!(
175                "Csdl segment '{trimmed}' mixes spaces without commas; parsing tokens permissively"
176            ));
177        }
178        for tok in sub_tokens {
179            if !tok.bytes().all(|b| b.is_ascii_digit()) {
180                if !permissive {
181                    bail!("Invalid non-integer Csdl token '{tok}'");
182                }
183                log.warn(&format!("Skipping non-integer Csdl token '{tok}'"));
184                continue;
185            }
186            match tok.parse::<u128>() {
187                Ok(id) => list.push(id),
188                Err(e) => {
189                    if !permissive {
190                        return Err(e).with_context(|| {
191                            format!("Failed to parse Csdl integer '{tok}'")
192                        });
193                    }
194                    log.warn(&format!(
195                        "Failed to parse Csdl integer '{tok}': {e}"
196                    ));
197                }
198            }
199        }
200    }
201
202    let dctf_bytes = super::dctext::dclist_to_dctf(&list);
203    let dc_str = crate::DcStr::from_bytes(&dctf_bytes)
204        .context("Converting csdl list to valid DcTF DcStr")?;
205    let doc = crate::DcMstring::from_dc_str(dc_str)?;
206    Ok((doc, log))
207}
208
209/// Converts a `DcMstring` to Csdl (comma-separated long Dcs) bytes.
210pub fn dcmstring_to_csdl(
211    doc: &crate::DcMstring,
212) -> Result<(Vec<u8>, FormatLog)> {
213    let dc_string = super::document_dc_string(doc)?;
214    let dclist = dc_string.to_dclist();
215    let mut output = String::new();
216    for (idx, &id) in dclist.iter().enumerate() {
217        if idx > 0 {
218            output.push(',');
219        }
220        output.push_str(&id.to_string());
221    }
222    Ok((output.into_bytes(), FormatLog::default()))
223}
224
225fn push_shorthand_token_to_dcmstring(
226    doc: &mut crate::DcMstring,
227    log: &mut FormatLog,
228    shorthand: ctb_storage_minimal::shorthand::DcShorthand,
229    raw_tok: &str,
230    permissive: bool,
231) -> Result<()> {
232    use ctb_storage_minimal::shorthand::DcShorthand;
233
234    match shorthand {
235        DcShorthand::Local(int_val) => {
236            let malachite_val = malachite::Integer::from(int_val);
237            match crate::dc_number::integer_to_dc_number_global(&malachite_val)
238            {
239                Ok(dc_num_gids) => {
240                    doc.push_char(crate::DcChar(1_114_408u128));
241                    for gid in dc_num_gids {
242                        doc.push_char(crate::DcChar(gid));
243                    }
244                }
245                Err(e) => {
246                    if !permissive {
247                        return Err(e).with_context(|| {
248                            format!("Failed to encode local node shorthand '{raw_tok}'")
249                        });
250                    }
251                    log.warn(&format!(
252                        "Failed to encode local node shorthand '{raw_tok}': {e}"
253                    ));
254                }
255            }
256        }
257        other => match other.to_global_id() {
258            Ok(gid) => doc.push_char(crate::DcChar(gid)),
259            Err(e) => {
260                if !permissive {
261                    return Err(e).with_context(|| {
262                        format!("Invalid Dc shorthand token '{raw_tok}'")
263                    });
264                }
265                log.warn(&format!(
266                    "Skipping out-of-range Dc shorthand token '{raw_tok}': {e}"
267                ));
268            }
269        },
270    }
271    Ok(())
272}
273
274/// Converts a Dcsh (Format 635: Dc shorthand ASCII list) document to `DcMstring`.
275pub fn dcsh_to_dcmstring(
276    bytes: &[u8],
277) -> Result<(crate::DcMstring, FormatLog)> {
278    dcsh_to_dcmstring_with_options(bytes, false)
279}
280
281/// Converts a Dcsh document to `DcMstring`, optionally in permissive mode.
282pub fn dcsh_to_dcmstring_with_options(
283    bytes: &[u8],
284    permissive: bool,
285) -> Result<(crate::DcMstring, FormatLog)> {
286    use ctb_storage_minimal::shorthand::DcShorthand;
287
288    let mut log = FormatLog::default();
289    let text_cow = if permissive {
290        match std::str::from_utf8(bytes) {
291            Ok(s) => std::borrow::Cow::Borrowed(s),
292            Err(e) => {
293                log.warn(&format!("Invalid UTF-8 in Dcsh input: {e}"));
294                String::from_utf8_lossy(bytes)
295            }
296        }
297    } else {
298        let s = std::str::from_utf8(bytes)
299            .map_err(|e| anyhow::anyhow!("Invalid UTF-8 in Dcsh input: {e}"))?;
300        std::borrow::Cow::Borrowed(s)
301    };
302
303    let mut doc = crate::DcMstring::new();
304    for line in text_cow.lines() {
305        let code_part = if permissive {
306            match line.split_once('#') {
307                Some((before, _)) => before,
308                None => line,
309            }
310        } else {
311            line
312        };
313        for tok in code_part.split_ascii_whitespace() {
314            match DcShorthand::parse(tok) {
315                Ok(shorthand) => {
316                    push_shorthand_token_to_dcmstring(
317                        &mut doc, &mut log, shorthand, tok, permissive,
318                    )?;
319                }
320                Err(e) => {
321                    if !permissive {
322                        return Err(e).with_context(|| {
323                            format!("Invalid Dc shorthand token '{tok}' in Dcsh input")
324                        });
325                    }
326                    log.warn(&format!(
327                        "Skipping invalid Dcsh token '{tok}': {e}"
328                    ));
329                }
330            }
331        }
332    }
333
334    Ok((doc, log))
335}
336
337/// Converts a `.ctbnode-incoming` (Format 651: Collective Toolbox incoming graph node shorthand text)
338/// document to `DcMstring`.
339pub fn ctbnode_incoming_to_dcmstring(
340    bytes: &[u8],
341) -> Result<(crate::DcMstring, FormatLog)> {
342    ctbnode_incoming_to_dcmstring_with_options(bytes, false)
343}
344
345/// Converts a `.ctbnode-incoming` document to `DcMstring`, optionally in permissive mode.
346pub fn ctbnode_incoming_to_dcmstring_with_options(
347    bytes: &[u8],
348    permissive: bool,
349) -> Result<(crate::DcMstring, FormatLog)> {
350    use ctb_formats_dcdata::graph_ledger::parse_ctbnode_incoming_file;
351    use ctb_storage_minimal::shorthand::DcShorthand;
352
353    let mut log = FormatLog::default();
354    let text_cow = if permissive {
355        match std::str::from_utf8(bytes) {
356            Ok(s) => std::borrow::Cow::Borrowed(s),
357            Err(e) => {
358                log.warn(&format!(
359                    "Invalid UTF-8 in .ctbnode-incoming input: {e}"
360                ));
361                String::from_utf8_lossy(bytes)
362            }
363        }
364    } else {
365        let s = std::str::from_utf8(bytes).map_err(|e| {
366            anyhow::anyhow!("Invalid UTF-8 in .ctbnode-incoming input: {e}")
367        })?;
368        std::borrow::Cow::Borrowed(s)
369    };
370
371    match parse_ctbnode_incoming_file(&text_cow, "<ctbnode-incoming>") {
372        Ok(parsed) => {
373            let mut doc = crate::DcMstring::new();
374            for sh_tok in parsed.tokens {
375                let raw_str = sh_tok.to_string();
376                push_shorthand_token_to_dcmstring(
377                    &mut doc, &mut log, sh_tok, &raw_str, permissive,
378                )?;
379            }
380            Ok((doc, log))
381        }
382        Err(e) => {
383            if !permissive {
384                return Err(e);
385            }
386            log.warn(&format!(
387                "Invalid .ctbnode-incoming structure ({e:#}); decoding shorthand tokens permissively"
388            ));
389            let mut doc = crate::DcMstring::new();
390            for line in text_cow.lines() {
391                let code_part = match line.split_once('#') {
392                    Some((before, _)) => before,
393                    None => line,
394                };
395                for tok in code_part.split_ascii_whitespace() {
396                    match DcShorthand::parse(tok) {
397                        Ok(shorthand) => {
398                            push_shorthand_token_to_dcmstring(
399                                &mut doc, &mut log, shorthand, tok, true,
400                            )?;
401                        }
402                        Err(err) => {
403                            log.warn(&format!(
404                                "Skipping invalid .ctbnode-incoming token '{tok}': {err}"
405                            ));
406                        }
407                    }
408                }
409            }
410            Ok((doc, log))
411        }
412    }
413}
414
415/// Converts a `DcMstring` to Dcsh (Dc shorthand ASCII list) bytes.
416pub fn dcmstring_to_dcsh(
417    doc: &crate::DcMstring,
418) -> Result<(Vec<u8>, FormatLog)> {
419    use ctb_storage_minimal::shorthand::DcShorthand;
420
421    let dc_string = super::document_dc_string(doc)?;
422    let dclist = dc_string.to_dclist();
423    let mut output = String::new();
424    for (idx, &gid) in dclist.iter().enumerate() {
425        if idx > 0 {
426            output.push(' ');
427        }
428        output.push_str(&DcShorthand::from_global_id(gid).to_string());
429    }
430    Ok((output.into_bytes(), FormatLog::default()))
431}
432
433/// Converts a `.ctbnodes` (Format 639: Collective Toolbox graph nodes shorthand text)
434/// document into its corresponding `DcMstring` (`Dc 617 .. Dc 618` node definitions).
435pub fn ctbnodes_to_dcmstring(
436    bytes: &[u8],
437) -> Result<(crate::DcMstring, FormatLog)> {
438    ctbnodes_to_dcmstring_with_options(bytes, false)
439}
440
441/// Converts a `.ctbnodes` document into its corresponding `DcMstring` (`Dc 617 .. Dc 618`
442/// node definitions), optionally in permissive mode.
443pub fn ctbnodes_to_dcmstring_with_options(
444    bytes: &[u8],
445    permissive: bool,
446) -> Result<(crate::DcMstring, FormatLog)> {
447    use ctb_formats_dcdata::graph_ledger::{
448        DCMM_HEADER, LedgerNode, default_ctbnbdl_framing_dcs,
449        encode_node_definition_dcmm2_bytes_with,
450    };
451
452    let mut log = FormatLog::default();
453    let text_cow = if permissive {
454        match std::str::from_utf8(bytes) {
455            Ok(s) => std::borrow::Cow::Borrowed(s),
456            Err(e) => {
457                log.warn(&format!("Invalid UTF-8 in .ctbnodes input: {e}"));
458                String::from_utf8_lossy(bytes)
459            }
460        }
461    } else {
462        let s = std::str::from_utf8(bytes).map_err(|e| {
463            anyhow::anyhow!("Invalid UTF-8 in .ctbnodes input: {e}")
464        })?;
465        std::borrow::Cow::Borrowed(s)
466    };
467
468    let framing = default_ctbnbdl_framing_dcs();
469    let mut raw_dcmm2 = Vec::with_capacity(DCMM_HEADER.len().saturating_add(bytes.len()));
470    raw_dcmm2.extend_from_slice(&DCMM_HEADER);
471    for (idx, line) in text_cow.lines().enumerate() {
472        let line_no = idx.saturating_add(1);
473        let code_part = match line.split_once('#') {
474            Some((before, _)) => before.trim(),
475            None => line.trim(),
476        };
477        if code_part.is_empty() {
478            continue;
479        }
480        match LedgerNode::parse_line(line, "<ctbnodes>", line_no) {
481            Ok(node) => {
482                let sec_bytes =
483                    encode_node_definition_dcmm2_bytes_with(&node, framing)?;
484                raw_dcmm2.extend_from_slice(&sec_bytes);
485            }
486            Err(e) => {
487                if !permissive {
488                    return Err(e);
489                }
490                log.warn(&format!(
491                    "Skipping malformed .ctbnodes line {line_no}: {e:#}"
492                ));
493            }
494        }
495    }
496
497    let opts = crate::DcmmStreamOptions {
498        best_effort: permissive,
499    };
500    let (doc, dcmm_log) = crate::dcmm2_to_dcmstring_with_options(&raw_dcmm2, &opts)?;
501    for w in dcmm_log.get_warnings() {
502        log.warn(&w);
503    }
504    Ok((doc, log))
505}
506
507/// Converts a `DcMstring` containing `Dc 617 .. Dc 618` node definitions to `.ctbnodes` text bytes.
508pub fn dcmstring_to_ctbnodes(
509    doc: &crate::DcMstring,
510) -> Result<(Vec<u8>, FormatLog)> {
511    use ctb_formats_dcdata::graph_ledger::{
512        CTBNBDL_MAGIC, decode_ctbnbdl_bundle_resilient_with,
513        decode_nodes_from_ctbnbdl_bytes_with, default_ctbnbdl_framing_dcs,
514    };
515
516    let mut bundle_bytes =
517        Vec::with_capacity(CTBNBDL_MAGIC.len().saturating_add(doc.len()));
518    bundle_bytes.extend_from_slice(&CTBNBDL_MAGIC);
519    bundle_bytes.extend_from_slice(doc.as_bytes());
520    let framing = default_ctbnbdl_framing_dcs();
521    let mut log = FormatLog::default();
522    let nodes = if ctb_utilities::invocation_settings::get_settings()
523        .recover_graph
524    {
525        let (_, recovered, warnings) =
526            decode_ctbnbdl_bundle_resilient_with(&bundle_bytes, framing)?;
527        for warning in &warnings {
528            log.warn(warning);
529        }
530        recovered
531    } else {
532        decode_nodes_from_ctbnbdl_bytes_with(&bundle_bytes, framing)?
533    };
534    let mut out = String::new();
535    for node in &nodes {
536        out.push_str(&node.format_line());
537        out.push('\n');
538    }
539    Ok((out.into_bytes(), log))
540}
541
542const CTBNBDL_MAGIC_V1: [u8; 8] = *b"CTBNBDL\x01";
543const CTBNBDL_MAGIC_V2: [u8; 8] = *b"CTBNBDL\x02";
544
545/// Converts a `.ctbnbdl` (Format 640: Collective Toolbox Node Bundle, v1 or v2) to `DcMstring`.
546pub fn ctbnbdl_to_dcmstring(
547    bytes: &[u8],
548) -> Result<(crate::DcMstring, FormatLog)> {
549    ctbnbdl_to_dcmstring_with_options(bytes, false)
550}
551
552/// Converts a `.ctbnbdl` (v1 or v2) to `DcMstring`, optionally in permissive mode.
553pub fn ctbnbdl_to_dcmstring_with_options(
554    bytes: &[u8],
555    permissive: bool,
556) -> Result<(crate::DcMstring, FormatLog)> {
557    let opts = crate::DcmmStreamOptions {
558        best_effort: permissive,
559    };
560    if let Some(payload) = bytes.strip_prefix(&CTBNBDL_MAGIC_V2) {
561        return crate::dcmm2_to_dcmstring_with_options(payload, &opts).context(
562            "Input bytes do not conform to valid Collective Toolbox Node Bundle v2 (.ctbnbdl) format",
563        );
564    }
565    if let Some(payload) = bytes.strip_prefix(&CTBNBDL_MAGIC_V1) {
566        return crate::dcmm1_to_dcmstring_with_options(payload, &opts).context(
567            "Input bytes do not conform to valid Collective Toolbox Node Bundle v1 (.ctbnbdl) format",
568        );
569    }
570    if !permissive {
571        bail!(
572            "Input bytes do not start with valid CTBNBDL\\x01 or CTBNBDL\\x02 magic header"
573        );
574    }
575    let (doc, mut log) = crate::dcmm_to_dcmstring_with_options(bytes, &opts)
576        .context(
577            "Input bytes do not conform to valid Collective Toolbox Node Bundle (.ctbnbdl) format",
578        )?;
579    log.warn("Missing or invalid CTBNBDL magic header; decoded payload in permissive mode");
580    Ok((doc, log))
581}
582
583/// Converts a `.ctbnbdl` version 1 (Format 644, `CTBNBDL\x01` + `DcMixed1`) to `DcMstring`.
584pub fn ctbnbdl1_to_dcmstring_with_options(
585    bytes: &[u8],
586    permissive: bool,
587) -> Result<(crate::DcMstring, FormatLog)> {
588    let opts = crate::DcmmStreamOptions {
589        best_effort: permissive,
590    };
591    if let Some(payload) = bytes.strip_prefix(&CTBNBDL_MAGIC_V1) {
592        return crate::dcmm1_to_dcmstring_with_options(payload, &opts).context(
593            "Input bytes do not conform to valid Collective Toolbox Node Bundle v1 (.ctbnbdl) format",
594        );
595    }
596    if !permissive {
597        bail!("Input bytes do not start with valid CTBNBDL\\x01 magic header");
598    }
599    // Reason for fallback: in permissive mode, if the input has a v2 magic header instead of v1, strip it; otherwise decode the raw bytes as payload.
600    let payload = bytes.strip_prefix(&CTBNBDL_MAGIC_V2).unwrap_or(bytes);
601    let (doc, mut log) =
602        crate::dcmm1_to_dcmstring_with_options(payload, &opts).context(
603            "Input bytes do not conform to valid Collective Toolbox Node Bundle v1 (.ctbnbdl) format",
604        )?;
605    log.warn("Missing or mismatched CTBNBDL\\x01 magic header; decoded payload in permissive mode");
606    Ok((doc, log))
607}
608
609/// Converts a `.ctbnbdl` version 2 (Format 645, `CTBNBDL\x02` + `DcMixed2`) to `DcMstring`.
610pub fn ctbnbdl2_to_dcmstring_with_options(
611    bytes: &[u8],
612    permissive: bool,
613) -> Result<(crate::DcMstring, FormatLog)> {
614    let opts = crate::DcmmStreamOptions {
615        best_effort: permissive,
616    };
617    if let Some(payload) = bytes.strip_prefix(&CTBNBDL_MAGIC_V2) {
618        return crate::dcmm2_to_dcmstring_with_options(payload, &opts).context(
619            "Input bytes do not conform to valid Collective Toolbox Node Bundle v2 (.ctbnbdl) format",
620        );
621    }
622    if !permissive {
623        bail!("Input bytes do not start with valid CTBNBDL\\x02 magic header");
624    }
625    // Reason for fallback: in permissive mode, if the input has a v1 magic header instead of v2, strip it; otherwise decode the raw bytes as payload.
626    let payload = bytes.strip_prefix(&CTBNBDL_MAGIC_V1).unwrap_or(bytes);
627    let (doc, mut log) =
628        crate::dcmm2_to_dcmstring_with_options(payload, &opts).context(
629            "Input bytes do not conform to valid Collective Toolbox Node Bundle v2 (.ctbnbdl) format",
630        )?;
631    log.warn("Missing or mismatched CTBNBDL\\x02 magic header; decoded payload in permissive mode");
632    Ok((doc, log))
633}
634
635/// Converts a `DcMstring` to `.ctbnbdl` (version 2) bytes.
636pub fn dcmstring_to_ctbnbdl(
637    doc: &crate::DcMstring,
638) -> Result<(Vec<u8>, FormatLog)> {
639    dcmstring_to_ctbnbdl2(doc)
640}
641
642/// Converts a `DcMstring` to `.ctbnbdl` version 1 (`CTBNBDL\x01` + `DcMixed1`) bytes.
643pub fn dcmstring_to_ctbnbdl1(
644    doc: &crate::DcMstring,
645) -> Result<(Vec<u8>, FormatLog)> {
646    let (dcmm1, log) = crate::dcmstring_to_dcmm1(doc)?;
647    let mut out =
648        Vec::with_capacity(CTBNBDL_MAGIC_V1.len().saturating_add(dcmm1.len()));
649    out.extend_from_slice(&CTBNBDL_MAGIC_V1);
650    out.extend_from_slice(&dcmm1);
651    Ok((out, log))
652}
653
654/// Converts a `DcMstring` to `.ctbnbdl` version 2 (`CTBNBDL\x02` + `DcMixed2`) bytes.
655pub fn dcmstring_to_ctbnbdl2(
656    doc: &crate::DcMstring,
657) -> Result<(Vec<u8>, FormatLog)> {
658    let mut out =
659        Vec::with_capacity(CTBNBDL_MAGIC_V2.len().saturating_add(doc.len()));
660    out.extend_from_slice(&CTBNBDL_MAGIC_V2);
661    out.extend_from_slice(doc.as_bytes());
662    Ok((out, FormatLog::default()))
663}
664
665#[cfg(test)]
666#[allow(
667    clippy::panic,
668    clippy::expect_used,
669    clippy::unwrap_used,
670    clippy::unwrap_in_result,
671    clippy::panic_in_result_fn,
672    clippy::indexing_slicing,
673    clippy::arithmetic_side_effects,
674    reason = "Standard repository test boilerplate"
675)]
676mod tests {
677    use super::*;
678
679    #[crate::ctb_test]
680    fn test_dcal_serialization() {
681        let list = vec![65, 1114408, 2228304];
682        let bytes = dclist_to_dcal(&list);
683        assert_eq!(std::str::from_utf8(&bytes).unwrap(), "65 1114408 2228304 ");
684    }
685
686    #[crate::ctb_test]
687    fn test_dcal_parsing_loose() {
688        let input = b"65 1114408  2228304\n1234\t5678 ";
689        let conv = dcal_to_dclist(input).expect("Parse dcal");
690        assert!(!conv.log.has_warnings());
691        assert_eq!(conv.result, vec![65, 1114408, 2228304, 1234, 5678]);
692    }
693
694    #[crate::ctb_test]
695    fn test_dcal_skips_non_digits() {
696        let input = b"65 invalid 1114408";
697        let conv = dcal_to_dclist(input).expect("Parse dcal");
698        assert!(conv.log.has_warnings());
699        assert_eq!(conv.result, vec![65, 1114408]);
700    }
701}