ctb_formats_dcstring/
dc_writer.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//! Direct fallible writer and binary source traits for Document Character
21//! (`Dc`) streams and files.
22
23#[allow(
24    unused_imports,
25    clippy::wildcard_imports,
26    reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29
30use crate::{BinaryPayloadRef, DcChar, DcMstring, DcStr, DcString};
31
32use std::io::Write;
33
34/// Supplies nonresident binary data without materializing it in memory.
35pub trait DcBinarySource {
36    fn open<'source>(
37        &'source self,
38        payload: &BinaryPayloadRef<'_>,
39    ) -> Result<DcBinaryReader<'source>>;
40}
41
42pub struct DcBinaryReader<'source> {
43    pub reader: Box<dyn std::io::Read + 'source>,
44    pub sha256: Option<[u8; 32]>,
45}
46
47/// Identifies a binary-source read or verification failure during encoding.
48#[derive(Debug)]
49pub struct DcBinarySourceError;
50
51impl std::fmt::Display for DcBinarySourceError {
52    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        formatter.write_str("Binary source encoding or verification failed")
54    }
55}
56
57impl std::error::Error for DcBinarySourceError {}
58
59/// A headerless DcMM encoder writing directly to a fallible output stream.
60pub struct DcWriter<'output> {
61    output: &'output mut dyn Write,
62    bytes: u64,
63    source: Option<&'output dyn DcBinarySource>,
64    grammar: Option<std::io::BufWriter<std::fs::File>>,
65}
66
67impl<'output> DcWriter<'output> {
68    pub fn new(output: &'output mut dyn Write) -> Self {
69        Self {
70            output,
71            bytes: 0,
72            source: None,
73            grammar: None,
74        }
75    }
76
77    pub fn with_binary_source(
78        output: &'output mut dyn Write,
79        source: &'output dyn DcBinarySource,
80    ) -> Self {
81        Self {
82            output,
83            bytes: 0,
84            source: Some(source),
85            grammar: None,
86        }
87    }
88
89    pub fn push_binary_ref(
90        &mut self,
91        payload: &BinaryPayloadRef<'_>,
92    ) -> Result<()> {
93        if let Some(bytes) = payload.as_resident_bytes() {
94            return self.push_binary_with_sha256(bytes);
95        }
96        let result = (|| -> Result<()> {
97            let source = self
98                .source
99                .context("Lazy binary encoding requires a backing source")?;
100            let mut opened = source.open(payload)?;
101            self.push_binary_from_reader(
102                &mut opened.reader,
103                payload.len(),
104                opened.sha256,
105            )?;
106            let mut extra = [0_u8; 1];
107            ensure!(
108                opened.reader.read(&mut extra)? == 0,
109                "Binary source exceeds its declared length"
110            );
111            Ok(())
112        })();
113        result.context(DcBinarySourceError)
114    }
115
116    pub const fn len(&self) -> u64 {
117        self.bytes
118    }
119
120    pub const fn is_empty(&self) -> bool {
121        self.bytes == 0
122    }
123
124    pub fn push_char(&mut self, character: impl Into<DcChar>) -> Result<()> {
125        let character = character.into();
126        let mut buffer = [0_u8; 24];
127        let length =
128            ctb_formats_dctf::encode_dctf_buf(&mut buffer, character.0);
129        self.emit(
130            buffer
131                .get(..length)
132                .context("Invalid encoded Dc character length")?,
133        )?;
134        Ok(())
135    }
136
137    pub fn push_str(&mut self, text: &str) -> Result<()> {
138        self.emit(text.as_bytes())?;
139        Ok(())
140    }
141
142    pub fn push_dc_str(&mut self, text: &DcStr) -> Result<()> {
143        self.emit(text.as_bytes())?;
144        Ok(())
145    }
146
147    pub fn push_binary(&mut self, bytes: &[u8]) -> Result<()> {
148        self.push_binary_with_metadata(bytes, &DcString::new())
149    }
150
151    pub fn push_binary_with_metadata(
152        &mut self,
153        bytes: &[u8],
154        metadata: &DcStr,
155    ) -> Result<()> {
156        self.push_binary_with_metadata_and_policy(
157            bytes,
158            metadata,
159            &crate::DcProjectionPolicy::strict(),
160        )
161    }
162
163    pub fn push_binary_with_metadata_and_policy(
164        &mut self,
165        bytes: &[u8],
166        metadata: &DcStr,
167        policy: &crate::DcProjectionPolicy,
168    ) -> Result<()> {
169        self.push_binary_with_metadata_policy_and_resolver(
170            bytes,
171            metadata,
172            policy,
173            ctb_formats_dcdata::syntax::default_syntax_resolver().as_ref(),
174        )
175    }
176
177    pub fn push_binary_with_metadata_policy_and_resolver(
178        &mut self,
179        bytes: &[u8],
180        metadata: &DcStr,
181        policy: &crate::DcProjectionPolicy,
182        resolver: &dyn crate::SyntaxRuleResolver,
183    ) -> Result<()> {
184        crate::encapsulation::validate_metadata_with_policy_and_resolver(
185            metadata, bytes, policy, resolver,
186        )?;
187        self.emit(&crate::dc_mixed::DC_203_BYTES)?;
188        self.emit(&[crate::dc_mixed::TYPE_BINARY_METADATA])?;
189        self.emit(&u128::try_from(bytes.len())?.to_be_bytes())?;
190        self.emit(&u128::try_from(metadata.len())?.to_be_bytes())?;
191        self.emit(metadata.as_bytes())?;
192        self.emit(bytes)?;
193        Ok(())
194    }
195
196    pub fn push_binary_with_sha256(&mut self, bytes: &[u8]) -> Result<()> {
197        let digest = ctb_formats_checksum::sha256(bytes);
198        let metadata = crate::encapsulation::checksum_text(
199            ctb_utilities::format_id::DC_SHA256,
200            &digest,
201        )?;
202        self.push_binary_with_metadata(bytes, &metadata)
203    }
204
205    pub fn push_checksum(
206        &mut self,
207        format: impl Into<DcChar>,
208        digest: &[u8],
209    ) -> Result<()> {
210        let mut metadata = DcString::new();
211        metadata.push(format.into());
212        self.push_binary_with_metadata(digest, &metadata)
213    }
214
215    pub fn push_binary_from_reader<R: std::io::Read + ?Sized>(
216        &mut self,
217        reader: &mut R,
218        size: u64,
219        sha256: Option<[u8; 32]>,
220    ) -> Result<()> {
221        DcMstring::write_binary_encapsulation(
222            &mut RawOutput(self),
223            reader,
224            size,
225            sha256,
226        )?;
227        Ok(())
228    }
229
230    fn emit(&mut self, bytes: &[u8]) -> Result<()> {
231        RawOutput(self).write_all(bytes)?;
232        Ok(())
233    }
234}
235
236/// Emits a headerless record and validates its grammar before returning.
237///
238/// Binary framing, lengths and supplied checksums are checked during emission.
239/// Exact emitted bytes are spooled to an anonymous file and checked with the
240/// file-backed navigator, without expanding binary payloads into characters.
241/// This bounds memory but requires temporary disk space proportional to the
242/// record size. Errors can leave partial output; callers must withhold
243/// their transaction footer until this function succeeds.
244/// FIXME: Will break on `csc archive` of large files.
245pub fn validate_and_write_dc_record(
246    output: &mut dyn Write,
247    source: Option<&dyn DcBinarySource>,
248    encode: impl FnOnce(&mut DcWriter<'_>) -> Result<()>,
249) -> Result<()> {
250    let mut grammar = std::io::BufWriter::new(
251        tempfile::tempfile().context("Cannot create Dc validation spool")?,
252    );
253    grammar.write_all(DcMstring::new().as_bytes())?;
254    let mut writer = DcWriter {
255        output,
256        bytes: 0,
257        source,
258        grammar: Some(grammar),
259    };
260    encode(&mut writer)?;
261    let grammar = writer
262        .grammar
263        .take()
264        .context("Missing encoding grammar")?
265        .into_inner()?;
266    crate::DcDocumentNavigator::from_dcmm_file(grammar, 0)?
267        .validate_document_strict()
268}
269
270impl Write for DcWriter<'_> {
271    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
272        if self.grammar.is_some() {
273            return Err(std::io::Error::other(
274                "Raw writes bypass Dc grammar validation",
275            ));
276        }
277        RawOutput(self).write(bytes)
278    }
279
280    fn flush(&mut self) -> std::io::Result<()> {
281        self.output.flush()
282    }
283}
284
285struct RawOutput<'writer, 'output>(&'writer mut DcWriter<'output>);
286
287impl Write for RawOutput<'_, '_> {
288    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
289        let writer = &mut self.0;
290        let count = writer.output.write(bytes)?;
291        if count > bytes.len() {
292            return Err(std::io::Error::other(
293                "Writer returned an invalid byte count",
294            ));
295        }
296        if let Some(grammar) = &mut writer.grammar {
297            grammar.write_all(bytes.get(..count).ok_or_else(|| {
298                std::io::Error::other("Invalid output byte count")
299            })?)?;
300        }
301        writer.bytes = writer
302            .bytes
303            .checked_add(u64::try_from(count).map_err(std::io::Error::other)?)
304            .ok_or_else(|| std::io::Error::other("Dc output size overflow"))?;
305        Ok(count)
306    }
307
308    fn flush(&mut self) -> std::io::Result<()> {
309        self.0.output.flush()
310    }
311}
312
313#[cfg(test)]
314#[allow(
315    clippy::panic,
316    clippy::expect_used,
317    clippy::unwrap_used,
318    clippy::unwrap_in_result,
319    clippy::panic_in_result_fn,
320    clippy::indexing_slicing,
321    clippy::arithmetic_side_effects,
322    reason = "Standard repository test boilerplate"
323)]
324mod tests {
325    use super::*;
326    use crate::{DcMixedEncode, LazyBinaryPayload, dc};
327
328    #[derive(Debug, PartialEq, Eq, crate::DcMixed)]
329    #[dc(begin = 317, end = 318)]
330    struct DerivedPayload {
331        #[dc(392, default, omit_default)]
332        body: Option<LazyBinaryPayload>,
333    }
334
335    struct PayloadSource(Vec<u8>);
336
337    #[crate::ctb_test]
338    fn byte_backed_grammar_preserves_payload_type_and_length_constraints()
339    -> Result<()> {
340        use ctb_formats_dcdata::syntax::{
341            default_syntax_resolver, parse_dc_syntax,
342        };
343        let resolver = default_syntax_resolver();
344        for size in [0, 31, 32, 33, 128 * 1024] {
345            for typed in [false, true] {
346                let mut metadata = DcString::new();
347                if typed {
348                    metadata.push(ctb_utilities::format_id::DC_SHA256);
349                }
350                let payload = vec![42; size];
351                let mut buffered = DcMstring::new();
352                buffered.push_binary_with_metadata(&payload, &metadata)?;
353                let mut output = Vec::new();
354                let mut grammar =
355                    std::io::BufWriter::new(tempfile::tempfile()?);
356                grammar.write_all(DcMstring::new().as_bytes())?;
357                let mut writer = DcWriter {
358                    output: &mut output,
359                    bytes: 0,
360                    source: None,
361                    grammar: Some(grammar),
362                };
363                writer.push_binary_with_metadata(&payload, &metadata)?;
364                let recorded = writer
365                    .grammar
366                    .take()
367                    .context("Missing validation document")?
368                    .into_inner()?;
369                for constraint in [
370                    ":[data:bytes=32]",
371                    ":[data:Sha256;bytes=32]",
372                    ":[data:bytes=131072]",
373                ] {
374                    let pattern = parse_dc_syntax(constraint)?;
375                    let mut expected =
376                        crate::SyntaxEvalContext::new(&**resolver, None);
377                    let mut actual =
378                        crate::SyntaxEvalContext::new(&**resolver, None);
379                    let expected_match =
380                        crate::DcDocumentNavigator::from_mstr(&buffered)
381                            .eval_pattern(&pattern.pattern, &mut expected)?;
382                    let actual_match =
383                        crate::DcDocumentNavigator::from_dcmm_file(
384                            recorded.try_clone()?,
385                            0,
386                        )?
387                        .eval_pattern(&pattern.pattern, &mut actual)?;
388                    ensure!(
389                        actual_match == expected_match,
390                        "Byte-backed grammar differs for size {size}, typed {typed}, constraint {constraint}"
391                    );
392                    if constraint == ":[data:bytes=32]" {
393                        ensure!(actual_match == (size == 32));
394                    }
395                    if constraint == ":[data:Sha256;bytes=32]" {
396                        ensure!(actual_match == (size == 32 && typed));
397                    }
398                }
399            }
400        }
401        Ok(())
402    }
403
404    #[crate::ctb_test]
405    fn byte_backed_grammar_checks_exact_streamed_section_bytes() -> Result<()> {
406        let payload = vec![42_u8; 128 * 1024];
407        for supplied_digest in [false, true] {
408            let payload_digest =
409                supplied_digest.then(|| ctb_formats_checksum::sha256(&payload));
410            let mut body = Vec::new();
411            DcWriter::new(&mut body).push_binary_from_reader(
412                &mut payload.as_slice(),
413                u64::try_from(payload.len())?,
414                payload_digest,
415            )?;
416            let valid_digest = ctb_formats_checksum::sha256(&body);
417            for digest in [valid_digest, [0_u8; 32]] {
418                let mut output = ShortWriter(Vec::new());
419                let result =
420                    validate_and_write_dc_record(&mut output, None, |writer| {
421                        writer.push_char(dc::DC_BEGIN_CHECKSUMMED_SECTION)?;
422                        writer.push_binary_from_reader(
423                            &mut payload.as_slice(),
424                            u64::try_from(payload.len())?,
425                            payload_digest,
426                        )?;
427                        writer.push_char(dc::DC_END_CHECKSUMMED_SECTION)?;
428                        writer.push_char(dc::DC_SECTION_DIGEST)?;
429                        writer.push_checksum(
430                            ctb_utilities::format_id::DC_SHA256,
431                            &digest,
432                        )
433                    });
434                ensure!(
435                    result.is_ok() == (digest == valid_digest),
436                    "Unexpected streamed section result: {result:?}"
437                );
438                let mut document = DcMstring::new().into_bytes();
439                document.extend_from_slice(&output.0);
440                let document = DcMstring::from_bytes(document)?;
441                ensure!(
442                    crate::navigator::validate_dc_mixed_strict(&document)
443                        .is_ok()
444                        == result.is_ok()
445                );
446            }
447        }
448        Ok(())
449    }
450
451    #[derive(crate::DcMixed)]
452    #[dc(encode_only)]
453    #[dc(begin = 317, end = 318)]
454    struct BorrowedPayload<'payload> {
455        #[dc(392)]
456        body: &'payload LazyBinaryPayload,
457    }
458
459    struct FailingWriter {
460        remaining: usize,
461    }
462
463    impl Write for FailingWriter {
464        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
465            if self.remaining == 0 {
466                return Err(std::io::Error::other("Injected output failure"));
467            }
468            let count = bytes.len().min(self.remaining);
469            self.remaining = self.remaining.saturating_sub(count);
470            Ok(count)
471        }
472
473        fn flush(&mut self) -> std::io::Result<()> {
474            Ok(())
475        }
476    }
477
478    #[crate::ctb_test]
479    fn borrowed_derives_propagate_every_output_failure() -> Result<()> {
480        let body =
481            LazyBinaryPayload(BinaryPayloadRef::Inline(b"borrowed".to_vec()));
482        let record = BorrowedPayload { body: &body };
483        let buffered = record.to_dc_mixed()?;
484        let mut output = ShortWriter(Vec::new());
485        record.write_dc_mixed(&mut output)?;
486        ensure!(output.0 == buffered.as_bytes());
487        for remaining in 0..buffered.as_bytes().len() {
488            ensure!(
489                record
490                    .write_dc_mixed(&mut FailingWriter { remaining })
491                    .is_err()
492            );
493        }
494        Ok(())
495    }
496
497    #[crate::ctb_test]
498    fn streamed_grammar_validation_rejects_unclosed_records_and_raw_writes()
499    -> Result<()> {
500        ensure!(
501            validate_and_write_dc_record(&mut Vec::new(), None, |writer| {
502                writer.push_char(dc::DC_BEGIN_LIST)
503            })
504            .is_err()
505        );
506        ensure!(
507            validate_and_write_dc_record(&mut Vec::new(), None, |writer| {
508                writer.write_all(b"unvalidated")?;
509                Ok(())
510            })
511            .is_err()
512        );
513        let payload = DerivedPayload {
514            body: Some(LazyBinaryPayload(BinaryPayloadRef::Inline(
515                vec![42; 128 * 1024],
516            ))),
517        };
518        let mut bytes = DcMstring::new().into_bytes();
519        validate_and_write_dc_record(&mut bytes, None, |writer| {
520            payload.encode_dc_mixed_to(writer)
521        })?;
522        crate::validate_dc_mixed_strict(&DcMstring::from_bytes(bytes)?)?;
523        Ok(())
524    }
525
526    impl DcBinarySource for PayloadSource {
527        fn open<'source>(
528            &'source self,
529            payload: &BinaryPayloadRef<'_>,
530        ) -> Result<DcBinaryReader<'source>> {
531            ensure!(matches!(
532                payload,
533                BinaryPayloadRef::Source { source_id: 0, .. }
534            ));
535            Ok(DcBinaryReader {
536                reader: Box::new(self.0.as_slice()),
537                sha256: Some(ctb_formats_checksum::sha256(&self.0)),
538            })
539        }
540    }
541
542    #[crate::ctb_test]
543    fn derived_lazy_payload_matches_resident_encoding() -> Result<()> {
544        let source = PayloadSource(vec![42; 128 * 1024]);
545        let resident = DerivedPayload {
546            body: Some(LazyBinaryPayload(BinaryPayloadRef::Inline(
547                source.0.clone(),
548            ))),
549        };
550        let lazy = DerivedPayload {
551            body: Some(LazyBinaryPayload(BinaryPayloadRef::Source {
552                source_id: 0,
553                len: u64::try_from(source.0.len())?,
554            })),
555        };
556        let expected = resident.to_dc_mixed()?;
557        let mut output = ShortWriter(Vec::new());
558        lazy.encode_dc_mixed_to(&mut DcWriter::with_binary_source(
559            &mut output,
560            &source,
561        ))?;
562        ensure!(output.0 == expected.payload_bytes());
563        ensure!(lazy.to_dc_mixed().is_err());
564        Ok(())
565    }
566
567    struct ShortWriter(Vec<u8>);
568
569    impl Write for ShortWriter {
570        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
571            let count = bytes.len().min(3);
572            self.0.extend_from_slice(
573                bytes.get(..count).ok_or_else(|| {
574                    std::io::Error::other("Invalid test slice")
575                })?,
576            );
577            Ok(count)
578        }
579
580        fn flush(&mut self) -> std::io::Result<()> {
581            Ok(())
582        }
583    }
584
585    #[crate::ctb_test]
586    fn streaming_primitives_match_buffered_output() -> Result<()> {
587        let mut expected = DcMstring::new();
588        expected.push_char(dc::DC_BEGIN_LIST);
589        expected.push_binary_with_sha256(b"payload")?;
590        expected.push_char(dc::DC_END_LIST);
591        let mut output = ShortWriter(Vec::new());
592        let mut writer = DcWriter::new(&mut output);
593        writer.push_char(dc::DC_BEGIN_LIST)?;
594        writer.push_binary_with_sha256(b"payload")?;
595        writer.push_char(dc::DC_END_LIST)?;
596        ensure!(writer.len() == u64::try_from(expected.payload_bytes().len())?);
597        ensure!(output.0 == expected.payload_bytes());
598        Ok(())
599    }
600}