ctb_formats_conversion/
convert_stream.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//! Streaming converters for translating input byte streams into framed `.dcmm` output,
21//! and streaming `.dcmm` input into target format streams.
22//!
23//! ## Streaming & Memory Characteristics
24//! Bounded-memory streaming (via 64 KiB chunks) is currently supported for UTF-8
25//! inputs and pass-through `DcMixed` streams. While Dc formats are architecturally
26//! designed to be streamable representations in principle (and capable of being
27//! transformed as streams), the current converter implementation buffers whole inputs
28//! for structured document formats (e.g. `DcIntegerList`, `Sems`, `DcText`, `CscJournal`)
29//! and non-`DcMixed` exports to perform document-level parsing and serialization.
30
31#[allow(
32    unused_imports,
33    clippy::wildcard_imports,
34    reason = "Standard workspace module prelude"
35)]
36use crate::utilities::*;
37
38use std::fs::File;
39use std::io::{BufRead, BufReader, Read, Write};
40use std::path::Path;
41
42use anyhow::{Context, Result, bail};
43use ctb_formats_dcstring::{DCMM_HEADER_LEN, DCMM_MAGIC, DCMM_UUID, DcMstring};
44use ctb_formats_utilities::FormatLog;
45use ctb_utilities::FormatId;
46use ctb_utilities::format_support::{
47    SupportedDcInputFormat, SupportedDcOutputFormat,
48};
49
50use crate::convert_bytes::{
51    DcConversionOptions, DcExportOptions, FormatSpec,
52    convert_bytes_to_dcmstring, convert_dcmstring_to_bytes,
53    format_supported_input_formats_table,
54};
55
56/// Summary of a completed streaming conversion operation to `DcMixed` (.dcmm).
57#[derive(Debug)]
58pub struct StreamConversionReceipt {
59    /// The detected or specified format ID.
60    pub detected_format: FormatId,
61    /// Total bytes written to the `.dcmm` destination stream.
62    pub bytes_written: u64,
63    /// Format conversion log containing diagnostics and notices.
64    pub log: FormatLog,
65}
66
67/// Summary of a completed streaming export operation from `DcMixed` (.dcmm) to a target format.
68#[derive(Debug)]
69pub struct StreamExportReceipt {
70    /// Target output format ID.
71    pub target_format: FormatId,
72    /// Total bytes written to the destination stream.
73    pub bytes_written: u64,
74    /// Format export log containing diagnostics and notices.
75    pub log: FormatLog,
76}
77
78/// Streams an input file to a framed `.dcmm` writer.
79///
80/// Bounded-memory chunked streaming is active for UTF-8 and pass-through `DcMixed`
81/// inputs; structured document formats currently buffer into memory for parsing.
82pub fn stream_file_to_dcmwriter<W: Write>(
83    input_path: &Path,
84    writer: &mut W,
85    options: &DcConversionOptions,
86) -> Result<StreamConversionReceipt> {
87    if input_path == Path::new("-") {
88        let mut stdin = std::io::stdin().lock();
89        stream_reader_to_dcmwriter(&mut stdin, writer, None, options)
90    } else {
91        let file = File::open(input_path).with_context(|| {
92            format!(
93                "Failed to open input file for streaming: {}",
94                input_path.display()
95            )
96        })?;
97        let filename = input_path
98            .file_name()
99            .map(|n| n.to_string_lossy().into_owned());
100        let mut reader = BufReader::new(file);
101        stream_reader_to_dcmwriter(
102            &mut reader,
103            writer,
104            filename.as_deref(),
105            options,
106        )
107    }
108}
109
110/// Streams an input `Read` source to a framed `.dcmm` writer.
111///
112/// Bounded-memory chunked streaming is active for UTF-8 and pass-through `DcMixed`
113/// inputs; structured document formats currently buffer into memory for parsing.
114pub fn stream_reader_to_dcmwriter<R: Read, W: Write>(
115    reader: &mut R,
116    writer: &mut W,
117    filename_hint: Option<&str>,
118    options: &DcConversionOptions,
119) -> Result<StreamConversionReceipt> {
120    let mut buf_reader = BufReader::new(reader);
121    let peek_bytes = buf_reader.fill_buf().context("Peeking input stream")?;
122
123    let resolved_format: SupportedDcInputFormat = match options.format {
124        FormatSpec::Format(fmt) => fmt,
125        FormatSpec::FormatId(id) => {
126            if let Some(supported) = SupportedDcInputFormat::from_format_id(id)
127            {
128                supported
129            } else {
130                bail!(
131                    "{}",
132                    format_supported_input_formats_table(&format!(
133                        "Format {id:?} is not supported for streaming conversion to DcMstring. Specify --from with one of:"
134                    ))
135                );
136            }
137        }
138        FormatSpec::Auto => {
139            let fid = ctb_formats_detection::detect_format_id_in_categories(
140                Some(peek_bytes),
141                filename_hint,
142                &[
143                    ctb_utilities::FormatCategory::Document,
144                    ctb_utilities::FormatCategory::Encoding,
145                    ctb_utilities::FormatCategory::Database,
146                ],
147            );
148            let detected = match fid {
149                Some(FormatId::Text) => Some(SupportedDcInputFormat::Utf8),
150                Some(id) => SupportedDcInputFormat::from_format_id(id),
151                None => None,
152            };
153            if let Some(fmt) = detected {
154                fmt
155            } else if peek_bytes.is_empty() {
156                SupportedDcInputFormat::Utf8
157            } else if options.allow_binary_encapsulation {
158                writer.write_all(&DCMM_MAGIC)?;
159                writer.write_all(&DCMM_UUID)?;
160                let mut bytes_written = u64::try_from(DCMM_HEADER_LEN)?;
161
162                let mut all_bytes = Vec::new();
163                buf_reader.read_to_end(&mut all_bytes)?;
164
165                let mut doc = DcMstring::new();
166                doc.push_binary(&all_bytes);
167                let payload = doc.payload_bytes();
168                writer.write_all(payload)?;
169                let payload_len = u64::try_from(payload.len())?;
170                bytes_written = bytes_written.saturating_add(payload_len);
171
172                return Ok(StreamConversionReceipt {
173                    detected_format: FormatId::DcMixed,
174                    bytes_written,
175                    log: FormatLog::default(),
176                });
177            } else {
178                bail!(
179                    "{}",
180                    format_supported_input_formats_table(
181                        "Unable to autodetect document format for streaming input. Specify --from with one of:"
182                    )
183                );
184            }
185        }
186    };
187
188    let is_dcmm1_header = peek_bytes.len() >= DCMM_HEADER_LEN
189        && peek_bytes.get(..5) == Some(DCMM_MAGIC.as_slice())
190        && peek_bytes.get(5..21)
191            == Some(ctb_formats_dcstring::DCMM_UUID_V1.as_slice());
192
193    if resolved_format == SupportedDcInputFormat::DcMixed2
194        || (resolved_format == SupportedDcInputFormat::DcMixed
195            && !is_dcmm1_header)
196    {
197        let (bytes_written, log) =
198            ctb_formats_dcstring::validate_and_copy_dcmm_stream_with_options(
199                &mut buf_reader,
200                writer,
201                &ctb_formats_dcstring::DcmmStreamOptions {
202                    best_effort: options.permissive,
203                },
204            )?;
205        return Ok(StreamConversionReceipt {
206            detected_format: resolved_format.to_format_id(),
207            bytes_written,
208            log,
209        });
210    }
211
212    writer.write_all(&DCMM_MAGIC)?;
213    writer.write_all(&DCMM_UUID)?;
214    let mut bytes_written = u64::try_from(DCMM_HEADER_LEN)?;
215
216    let mut log = FormatLog::default();
217
218    match resolved_format {
219        SupportedDcInputFormat::Utf8 => {
220            let mut chunk = vec![0u8; 64 * 1024];
221            let mut remainder = Vec::new();
222
223            loop {
224                let n = buf_reader.read(&mut chunk)?;
225                if n == 0 {
226                    break;
227                }
228                let mut valid_bytes = remainder.clone();
229                if let Some(slice) = chunk.get(..n) {
230                    valid_bytes.extend_from_slice(slice);
231                }
232                remainder.clear();
233
234                let mut cursor = valid_bytes.as_slice();
235                while !cursor.is_empty() {
236                    match std::str::from_utf8(cursor) {
237                        Ok(text) => {
238                            writer.write_all(text.as_bytes())?;
239                            let written_len = u64::try_from(text.len())?;
240                            bytes_written =
241                                bytes_written.saturating_add(written_len);
242                            break;
243                        }
244                        Err(e) => {
245                            let valid_up_to = e.valid_up_to();
246                            if valid_up_to > 0 {
247                                if let Some(valid_slice) =
248                                    cursor.get(..valid_up_to)
249                                {
250                                    writer.write_all(valid_slice)?;
251                                    let written_len =
252                                        u64::try_from(valid_slice.len())?;
253                                    bytes_written = bytes_written
254                                        .saturating_add(written_len);
255                                }
256                            }
257                            if let Some(error_len) = e.error_len() {
258                                if !options.permissive {
259                                    bail!(
260                                        "Encountered invalid UTF-8 sequence at offset {valid_up_to}"
261                                    );
262                                }
263                                log.warn("Invalid UTF-8 byte sequence replaced with U+FFFD in permissive mode");
264                                let rep = "\u{FFFD}".as_bytes();
265                                writer.write_all(rep)?;
266                                bytes_written = bytes_written
267                                    .saturating_add(u64::try_from(rep.len())?);
268                                let next =
269                                    valid_up_to.saturating_add(error_len);
270                                if let Some(rest) = cursor.get(next..) {
271                                    cursor = rest;
272                                } else {
273                                    break;
274                                }
275                            } else {
276                                if let Some(rem_slice) =
277                                    cursor.get(valid_up_to..)
278                                {
279                                    remainder.extend_from_slice(rem_slice);
280                                }
281                                break;
282                            }
283                        }
284                    }
285                }
286            }
287
288            if !remainder.is_empty() {
289                if !options.permissive {
290                    bail!("Incomplete UTF-8 sequence at end of stream");
291                }
292                log.warn("Incomplete UTF-8 sequence at end of stream replaced with U+FFFD in permissive mode");
293                let rep = "\u{FFFD}".as_bytes();
294                writer.write_all(rep)?;
295                bytes_written =
296                    bytes_written.saturating_add(u64::try_from(rep.len())?);
297            }
298        }
299        SupportedDcInputFormat::DcMixed2 => unreachable!(),
300        _ => {
301            let mut all_bytes = Vec::new();
302            buf_reader.read_to_end(&mut all_bytes)?;
303
304            let res = convert_bytes_to_dcmstring(
305                &all_bytes,
306                filename_hint,
307                &DcConversionOptions {
308                    format: FormatSpec::Format(resolved_format),
309                    allow_binary_encapsulation: options
310                        .allow_binary_encapsulation,
311                    permissive: options.permissive,
312                },
313            )?;
314            log = res.log;
315
316            let payload = res.document.payload_bytes();
317            writer.write_all(payload)?;
318            let payload_len = u64::try_from(payload.len())?;
319            bytes_written = bytes_written.saturating_add(payload_len);
320        }
321    }
322
323    Ok(StreamConversionReceipt {
324        detected_format: resolved_format.to_format_id(),
325        bytes_written,
326        log,
327    })
328}
329
330/// Streams a `.dcmm` source `Read` to a writer in the specified `SupportedDcOutputFormat`.
331///
332/// Bounded-memory pass-through streaming is active for `DcMixed` output; other target
333/// formats currently buffer the `.dcmm` payload in memory to serialize the output.
334pub fn stream_dcmreader_to_writer<R: Read, W: Write>(
335    reader: &mut R,
336    writer: &mut W,
337    format: SupportedDcOutputFormat,
338    options: &DcExportOptions,
339) -> Result<StreamExportReceipt> {
340    if matches!(
341        format,
342        SupportedDcOutputFormat::DcMixed | SupportedDcOutputFormat::DcMixed2
343    ) {
344        let (bytes_written, log) =
345            ctb_formats_dcstring::validate_and_copy_dcmm_stream_with_options(
346                reader,
347                writer,
348                &ctb_formats_dcstring::DcmmStreamOptions::default(),
349            )?;
350        return Ok(StreamExportReceipt {
351            target_format: format.to_format_id(),
352            bytes_written,
353            log,
354        });
355    }
356
357    let mut buf_reader = BufReader::new(reader);
358    let mut header = [0u8; DCMM_HEADER_LEN];
359    buf_reader
360        .read_exact(&mut header)
361        .context("Reading DcMixed header")?;
362
363    let mut payload = Vec::new();
364    buf_reader.read_to_end(&mut payload)?;
365
366    let mut dcmm_bytes =
367        Vec::with_capacity(header.len().saturating_add(payload.len()));
368    dcmm_bytes.extend_from_slice(&header);
369    dcmm_bytes.extend_from_slice(&payload);
370
371    let (doc, mut log) =
372        ctb_formats_dcstring::dcmm_to_dcmstring(&dcmm_bytes)
373            .context("Parsing DcMixed stream payload into DcMstring")?;
374
375    let export = convert_dcmstring_to_bytes(&doc, format, options)?;
376    log.merge(&export.log);
377    writer.write_all(&export.bytes)?;
378    let bytes_written = u64::try_from(export.bytes.len())?;
379
380    Ok(StreamExportReceipt {
381        target_format: format.to_format_id(),
382        bytes_written,
383        log,
384    })
385}
386
387/// Streams a `.dcmm` file on disk to a writer in the specified `SupportedDcOutputFormat`.
388pub fn stream_dcmfile_to_writer<W: Write>(
389    input_path: &Path,
390    writer: &mut W,
391    format: SupportedDcOutputFormat,
392    options: &DcExportOptions,
393) -> Result<StreamExportReceipt> {
394    if input_path == Path::new("-") {
395        let mut stdin = std::io::stdin().lock();
396        stream_dcmreader_to_writer(&mut stdin, writer, format, options)
397    } else {
398        let file = File::open(input_path).with_context(|| {
399            format!(
400                "Failed to open input file for export streaming: {}",
401                input_path.display()
402            )
403        })?;
404        let mut reader = BufReader::new(file);
405        stream_dcmreader_to_writer(&mut reader, writer, format, options)
406    }
407}
408
409#[cfg(test)]
410#[allow(
411    clippy::panic,
412    clippy::expect_used,
413    clippy::unwrap_used,
414    clippy::unwrap_in_result,
415    clippy::panic_in_result_fn,
416    clippy::indexing_slicing,
417    clippy::arithmetic_side_effects,
418    reason = "Standard repository test boilerplate"
419)]
420mod tests {
421    use super::*;
422
423    #[crate::ctb_test]
424    fn test_streaming_utf8() {
425        let input = b"Streaming UTF-8 text document";
426        let mut cursor = std::io::Cursor::new(input);
427        let mut out = Vec::new();
428
429        let receipt = stream_reader_to_dcmwriter(
430            &mut cursor,
431            &mut out,
432            Some("test.txt"),
433            &DcConversionOptions::default(),
434        )
435        .expect("stream utf8");
436
437        assert_eq!(receipt.detected_format, FormatId::Utf8);
438        assert_eq!(receipt.bytes_written, u64::try_from(out.len()).unwrap());
439
440        let dcmm = DcMstring::from_bytes(out).expect("validate dcmm");
441        assert_eq!(dcmm, "Streaming UTF-8 text document");
442    }
443
444    #[crate::ctb_test]
445    fn test_streaming_export_roundtrip() {
446        let input = b"Stream export test";
447        let mut cursor = std::io::Cursor::new(input);
448        let mut dcmm_out = Vec::new();
449
450        stream_reader_to_dcmwriter(
451            &mut cursor,
452            &mut dcmm_out,
453            Some("test.txt"),
454            &DcConversionOptions::default(),
455        )
456        .expect("stream to dcmm");
457
458        let mut dcmm_cursor = std::io::Cursor::new(dcmm_out);
459        let mut text_out = Vec::new();
460
461        let export_receipt = stream_dcmreader_to_writer(
462            &mut dcmm_cursor,
463            &mut text_out,
464            SupportedDcOutputFormat::Utf8,
465            &DcExportOptions::default(),
466        )
467        .expect("stream export utf8");
468
469        assert_eq!(export_receipt.target_format, FormatId::Utf8);
470        assert_eq!(text_out, input);
471    }
472
473    #[crate::ctb_test]
474    fn test_streaming_dcmm_passthrough() {
475        let mut original = DcMstring::new();
476        original.push_str("Pass-through streaming test");
477        original.push_binary(b"Binary payload in dcmm stream");
478        let input_bytes = original.into_bytes();
479
480        let mut cursor = std::io::Cursor::new(&input_bytes);
481        let mut dcmm_out = Vec::new();
482
483        let receipt = stream_reader_to_dcmwriter(
484            &mut cursor,
485            &mut dcmm_out,
486            Some("doc.dcmm"),
487            &DcConversionOptions::default(),
488        )
489        .expect("stream dcmm passthrough");
490
491        assert_eq!(receipt.detected_format, FormatId::DcMixed2);
492        assert_eq!(
493            receipt.bytes_written,
494            u64::try_from(input_bytes.len()).unwrap()
495        );
496        assert_eq!(dcmm_out, input_bytes);
497
498        // Test stream_dcmreader_to_writer with SupportedDcOutputFormat::DcMixed
499        let mut dcmm_cursor = std::io::Cursor::new(&input_bytes);
500        let mut export_out = Vec::new();
501
502        let export_receipt = stream_dcmreader_to_writer(
503            &mut dcmm_cursor,
504            &mut export_out,
505            SupportedDcOutputFormat::DcMixed,
506            &DcExportOptions::default(),
507        )
508        .expect("stream dcmm export passthrough");
509
510        assert_eq!(export_receipt.target_format, FormatId::DcMixed);
511        assert_eq!(
512            export_receipt.bytes_written,
513            u64::try_from(input_bytes.len()).unwrap()
514        );
515        assert_eq!(export_out, input_bytes);
516    }
517
518    #[crate::ctb_test]
519    fn test_streaming_dcmm1_export() {
520        let mut doc = DcMstring::new();
521        doc.push_str("Legacy DcMixed1 stream ");
522        doc.push_char(ctb_formats_dcstring::DcChar(1_114_112));
523        doc.push_binary(b"\x00\x01\x02");
524        let (dcmm1_bytes, _) =
525            ctb_formats_dcstring::dcmstring_to_dcmm1(&doc).unwrap();
526
527        // 1. Export DcMixed1 stream to DcMixed2
528        let mut cursor_v1 = std::io::Cursor::new(&dcmm1_bytes);
529        let mut out_dcmm2 = Vec::new();
530        let receipt_dcmm2 = stream_dcmreader_to_writer(
531            &mut cursor_v1,
532            &mut out_dcmm2,
533            SupportedDcOutputFormat::DcMixed2,
534            &DcExportOptions::default(),
535        )
536        .expect("stream export dcmm1 -> dcmm2");
537        assert_eq!(receipt_dcmm2.target_format, FormatId::DcMixed2);
538        assert_eq!(out_dcmm2, doc.as_bytes());
539
540        // 2. Export DcMixed1 stream to DcText
541        let mut cursor_v1_text = std::io::Cursor::new(&dcmm1_bytes);
542        let mut out_dctext = Vec::new();
543        let receipt_dctext = stream_dcmreader_to_writer(
544            &mut cursor_v1_text,
545            &mut out_dctext,
546            SupportedDcOutputFormat::DcText,
547            &DcExportOptions::default(),
548        )
549        .expect("stream export dcmm1 -> dctext");
550        assert_eq!(receipt_dctext.target_format, FormatId::DcText);
551        let expected_dctext = convert_dcmstring_to_bytes(
552            &doc,
553            SupportedDcOutputFormat::DcText,
554            &DcExportOptions::default(),
555        )
556        .unwrap();
557        assert_eq!(out_dctext, expected_dctext.bytes);
558    }
559}