flpdf 0.5.1

A pure-Rust PDF toolkit modeled on qpdf — read, rewrite, linearize, and inspect PDFs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
//! qpdf correspondence: QPDFWriter.cc plain object-body emission split from planning and xref output.
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Seek};
use std::rc::Rc;

use crate::writer::object_streams;
use crate::writer::plain::plan::{PlainWritePlan, PlannedIndirectObject};
use crate::writer::plain::xref::{BodyLayout, CompressedLocation};
use crate::writer::WriterOptions;
use crate::writer::{serialize, CompressStreams, ObjectWriterEmission, QPDF_BINARY_MARKER};
use crate::{ObjectHandle, ObjectRef, Pdf};

/// Emit every body placement already chosen by `plan`.
///
/// This stage resolves, rewrites, re-encodes, and serializes planned objects.
/// Numbering, membership, trailer construction, and xref output remain the
/// responsibility of the plan and xref stages.
pub(crate) fn emit_bodies<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    options: &WriterOptions,
    plan: &PlainWritePlan,
) -> crate::Result<(Vec<u8>, BodyLayout)> {
    validate_objstm_member_bodies(pdf, plan)?;

    let mut bytes = Vec::new();
    bytes.extend_from_slice(format!("%PDF-{}\n", plan.version).as_bytes());
    bytes.extend_from_slice(QPDF_BINARY_MARKER);

    let mut layout = BodyLayout::default();
    for planned in &plan.objects {
        match planned {
            PlannedIndirectObject::Source { source, output } => {
                let offset = bytes.len();
                bytes.extend_from_slice(
                    format!("{} {} obj\n", output.number, output.generation).as_bytes(),
                );
                emit_source_from_handle(pdf, options, plan, *source, &mut bytes)?;
                bytes.extend_from_slice(b"\nendobj\n");
                layout
                    .uncompressed
                    .insert(output.number, (output.generation, offset));
                crate::writer::report_progress_event(options)?;
            }
            PlannedIndirectObject::ObjectStream {
                origin,
                output,
                members,
            } => {
                let mut handles = Vec::with_capacity(members.len());
                for member in members {
                    let handle = pdf.get_object_handle(member.source);
                    pdf.resolve(&handle)?;
                    handles.push((member.output, handle));
                }
                let map = |object_ref| {
                    plan.new_for_original(object_ref).ok_or_else(|| {
                        crate::Error::Unsupported(format!(
                            "plain writer: reference {} {} R absent from renumber map",
                            object_ref.number, object_ref.generation
                        ))
                    })
                };
                let body = object_streams::emit_objstm_body_from_handles_with_writer(
                    &handles,
                    &mut |out, _member_index, _member_ref, handle| {
                        let result = handle.write_object_with_ref_map_and_removed(
                            out,
                            &map,
                            &plan.removed_refs,
                        );
                        if result.is_ok() {
                            crate::writer::report_progress_event(options)?;
                        }
                        result
                    },
                )?;
                let offset = bytes.len();
                bytes.extend_from_slice(
                    format!("{} {} obj\n", output.number, output.generation).as_bytes(),
                );
                let structural_compress = if plan.trailer.structural_filtered {
                    CompressStreams::Yes
                } else {
                    CompressStreams::No
                };
                let extends = match origin {
                    crate::writer::plain::plan::PlannedObjectStreamOrigin::SourceBacked(source) => {
                        let source_handle = pdf.get_object_handle(*source);
                        pdf.resolve(&source_handle)?;
                        if let Some(source_dict) = source_handle.as_stream_dict() {
                            let extends = source_dict.try_get_key(b"/Extends")?;
                            match extends.object_ref() {
                                Some(extends) => Some(
                                    plan.old_to_new.get(&extends).copied().ok_or_else(|| {
                                        crate::Error::Unsupported(format!(
                                            "plain writer: source ObjStm /Extends {} {} R is absent from renumber map",
                                            extends.number, extends.generation
                                        ))
                                    })?,
                                ),
                                _ => None,
                            }
                        } else {
                            // qpdf permits a null or otherwise non-stream source
                            // identity here as a placeholder for a reconstructed
                            // object stream. The rebuilt container still carries
                            // the surviving members, but has no /Extends key.
                            None
                        }
                    }
                    crate::writer::plain::plan::PlannedObjectStreamOrigin::Synthetic => None,
                };
                serialize::write_objstm_stream_with_extends(
                    &mut bytes,
                    &body,
                    structural_compress,
                    options.newline_before_endstream,
                    extends,
                )?; // cov:ignore: error arm requires an in-memory zlib encoder failure
                bytes.extend_from_slice(b"\nendobj\n");
                layout
                    .uncompressed
                    .insert(output.number, (output.generation, offset));
                for (index, member) in members.iter().enumerate() {
                    layout.compressed.insert(
                        member.output.number,
                        CompressedLocation {
                            container: output.number,
                            index: u32::try_from(index).unwrap_or(u32::MAX),
                        },
                    );
                }
            }
        }
    }

    Ok((bytes, layout))
}

fn emit_source_from_handle<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    options: &WriterOptions,
    plan: &PlainWritePlan,
    source: crate::ObjectRef,
    bytes: &mut Vec<u8>,
) -> crate::Result<()> {
    let handle = pdf.get_object_handle(source);
    pdf.resolve(&handle)?;
    let map = |object_ref| {
        plan.new_for_original(object_ref).ok_or_else(|| {
            crate::Error::Unsupported(format!(
                "plain writer: reference {} {} R absent from renumber map",
                object_ref.number, object_ref.generation
            ))
        })
    };

    if handle.as_stream_dict().is_some() {
        let cached = if let Some(cached) = plan.cached_stream_outputs.get(&source) {
            if cached.fingerprint == crate::writer::plain::plan::stream_cache_fingerprint(&handle)?
            {
                Some(cached)
            } else {
                None
            }
        } else {
            None // cov:ignore: every planned indirect source stream receives a cache entry; structural streams bypass this emitter
        };
        let (dict, data, refiltered) = if let Some(cached) = cached {
            (cached.dict.clone(), cached.data.clone(), cached.refiltered)
        } else {
            canonical_stream_output(&handle, options)?
        };
        dict.write_stream_body_with_ref_map_and_removed(
            bytes,
            refiltered,
            &map,
            &plan.removed_refs,
        )?; // cov:ignore: LLVM attributes the validated success continuation to the call lines above
        serialize::write_stream_payload(bytes, &data, options.newline_before_endstream);
    } else {
        handle.write_object_with_ref_map_and_removed(bytes, &map, &plan.removed_refs)?;
    }
    Ok(())
}

pub(crate) fn canonical_stream_output(
    handle: &ObjectHandle,
    options: &WriterOptions,
) -> crate::Result<(ObjectHandle, Vec<u8>, bool)> {
    let (dict, data, refiltered, _) =
        canonical_stream_output_with_status(handle, options, true, false)?;
    Ok((dict, data, refiltered))
}

pub(crate) fn canonical_stream_output_with_status(
    handle: &ObjectHandle,
    options: &WriterOptions,
    apply_full_rewrite_metadata_policy: bool,
    normalize_content: bool,
) -> crate::Result<(ObjectHandle, Vec<u8>, bool, bool)> {
    canonical_stream_output_with_rewrite_policy(
        handle,
        options,
        apply_full_rewrite_metadata_policy,
        normalize_content,
    )
}

/// Full-rewrite variant of [`canonical_stream_output`]. The legacy writer
/// applies the same qpdf filter/provider pipeline and the cleartext-metadata
/// policy that belongs to encrypted output. The live handle's source pipe owns
/// recovered stream framing for these non-PCLm routes; the PCLm writer selects
/// its own qpdf `pipeStreamData` length boundary around its queue. The writer
/// must never append scan framing a second time.
pub(crate) fn canonical_stream_output_for_rewrite(
    handle: &ObjectHandle,
    options: &WriterOptions,
    normalize_content: bool,
) -> crate::Result<(ObjectHandle, Vec<u8>, bool)> {
    let (dict, data, refiltered, _) =
        canonical_stream_output_for_rewrite_with_status(handle, options, normalize_content)?;
    Ok((dict, data, refiltered))
}

pub(crate) fn canonical_stream_output_for_rewrite_with_status(
    handle: &ObjectHandle,
    options: &WriterOptions,
    normalize_content: bool,
) -> crate::Result<(ObjectHandle, Vec<u8>, bool, bool)> {
    canonical_stream_output_with_status(handle, options, true, normalize_content)
}

/// Emit a page or indirect `/Contents` array holder that owns direct stream
/// values. qpdf's stream branch still applies to those nested streams even
/// though the enclosing object is a page dictionary or array, while the
/// ordinary ObjectHandle serializer deliberately emits only a stream's
/// dictionary in a child position. Keep this exceptional framing in the
/// writer consumer rather than changing the generic ObjectHandle contract.
pub(crate) fn emit_content_container_from_handle_with_ref_map(
    container: &ObjectHandle,
    options: &WriterOptions,
    out: &mut Vec<u8>,
    map: &dyn Fn(ObjectRef) -> crate::Result<ObjectRef>,
    removed_refs: &BTreeSet<ObjectRef>,
) -> crate::Result<()> {
    let mut write_string = |out: &mut Vec<u8>, value: &[u8]| {
        crate::pdf_syntax::write_string_value(out, value);
        Ok(())
    };
    emit_content_container_from_handle_with_ref_map_and_string_writer(
        container,
        options,
        out,
        map,
        removed_refs,
        &mut write_string,
    )
}

/// Encrypted-string sibling of
/// [`emit_content_container_from_handle_with_ref_map`]. The callback is kept
/// at the same boundary as ObjectHandle's canonical writer methods so direct
/// stream dictionaries do not need a separate value materialization bridge.
pub(crate) fn emit_content_container_from_handle_with_ref_map_and_string_writer<F>(
    container: &ObjectHandle,
    options: &WriterOptions,
    out: &mut Vec<u8>,
    map: &dyn Fn(ObjectRef) -> crate::Result<ObjectRef>,
    removed_refs: &BTreeSet<ObjectRef>,
    write_string: &mut F,
) -> crate::Result<()>
where
    F: FnMut(&mut Vec<u8>, &[u8]) -> crate::Result<()>,
{
    let container = if options.content_normalization {
        normalize_content_container(container, options)?
    } else {
        container.clone()
    };
    let mut emitter = ContentEmitter {
        qdf: options.qdf,
        out,
        map,
        removed_refs,
        write_string,
    };
    emitter.emit_value(&container, true, 0)
}

// Stack-safety constants for this module's recursive `ObjectHandle` walkers
// (`ContentEmitter::emit_value`, `has_direct_stream_in_value`,
// `normalize_content_value`), mirroring `object_handle.rs`'s own
// `UNPARSE_STACK_RED_ZONE`/`UNPARSE_STACK_GROWTH_SIZE` (which itself mirrors
// `parser.rs`'s `STACK_RED_ZONE`/`STACK_GROWTH_SIZE`). Kept as a local
// mirror rather than imported cross-module, matching that file's own
// established precedent for this exact constant pair (see its own doc
// comment on why). A container reached here may be built directly through
// the public `ObjectHandle::array`/`dictionary`/`stream` factories (see
// the direct stream factory in `reader.rs`), which -- like
// every other `ObjectHandle` tree those factories build -- carries no depth
// bound the way parsed input does.
const CONTENT_EMIT_STACK_RED_ZONE: usize = 32 * 1024;
const CONTENT_EMIT_STACK_GROWTH_SIZE: usize = 1024 * 1024;

/// Replace only direct stream values in a page's `/Contents` value or an
/// indirect array holder. Indirect children retain identity and are never
/// chased: their terminal streams remain ordinary planned objects, exactly as
/// in the shared page-content resolver.
fn normalize_content_container(
    container: &ObjectHandle,
    options: &WriterOptions,
) -> crate::Result<ObjectHandle> {
    container.try_dereference()?;
    if let Some(entries) = container.as_dictionary() {
        let entries = entries
            .into_iter()
            .map(|(key, value)| {
                if key.as_slice() == b"/Contents" {
                    Ok((key, normalize_content_value(&value, options)?))
                } else {
                    Ok((key, value))
                }
            })
            .collect::<crate::Result<Vec<_>>>()?;
        return Ok(ObjectHandle::dictionary(entries));
    }
    if let Some(items) = container.as_array() {
        let items = items
            .into_iter()
            .map(|item| normalize_content_value(&item, options))
            .collect::<crate::Result<Vec<_>>>()?;
        return Ok(ObjectHandle::array(items));
    } // cov:ignore: LLVM does not attribute this successful array normalization continuation
    Ok(container.clone()) // cov:ignore: the pre-scan records only page dictionaries and array holders
}

// The recursion hub for this function's own `Array` arm below -- every
// nested descent funnels back through this same entry point, so wrapping
// here bounds the whole walk the same way `object_handle.rs`'s own
// single-hub recursive walkers do. See `CONTENT_EMIT_STACK_RED_ZONE`'s doc
// for why this needs the same protection those walkers already have.
fn normalize_content_value(
    value: &ObjectHandle,
    options: &WriterOptions,
) -> crate::Result<ObjectHandle> {
    stacker::maybe_grow(
        CONTENT_EMIT_STACK_RED_ZONE,
        CONTENT_EMIT_STACK_GROWTH_SIZE,
        || {
            if value.is_indirect() {
                return Ok(value.clone());
            }
            value.try_dereference()?;
            if value.as_stream_dict().is_some() {
                let (dict, data, _) = canonical_stream_output_for_rewrite(value, options, true)?;
                return Ok(ObjectHandle::stream(dict, Rc::new(data)));
            }
            if let Some(items) = value.as_array() {
                let items = items
                    .into_iter()
                    .map(|item| normalize_content_value(&item, options))
                    .collect::<crate::Result<Vec<_>>>()?;
                return Ok(ObjectHandle::array(items));
            }
            Ok(value.clone())
        },
    )
}

struct ContentEmitter<'a, F>
where
    F: FnMut(&mut Vec<u8>, &[u8]) -> crate::Result<()>,
{
    qdf: bool,
    out: &'a mut Vec<u8>,
    map: &'a dyn Fn(ObjectRef) -> crate::Result<ObjectRef>,
    removed_refs: &'a BTreeSet<ObjectRef>,
    write_string: &'a mut F,
}

impl<F> ContentEmitter<'_, F>
where
    F: FnMut(&mut Vec<u8>, &[u8]) -> crate::Result<()>,
{
    // The recursion hub for this impl's `emit_array`/`emit_dictionary`
    // arms below -- every nested descent (including `has_direct_stream_in_value`'s
    // own separate probe walk) funnels back through this same entry point
    // before recursing further, so wrapping here bounds the whole emission
    // walk the same way `object_handle.rs`'s own single-hub recursive
    // walkers do. See `CONTENT_EMIT_STACK_RED_ZONE`'s doc for why this
    // needs the same protection those walkers already have.
    //
    // A direct stream value gets full `stream ... endstream` framing
    // ([`Self::emit_direct_stream`]) wherever it is reached while walking
    // this container -- not only nested under `/Contents` -- because the
    // ordinary per-object `ObjectHandle` serializer this call falls back to
    // otherwise (`write_object_with_ref_map_and_removed_with_string_writer`
    // and its QDF sibling) deliberately inlines only a stream's dictionary
    // at a child position (`unparse_container`'s own doc,
    // `crate::object_handle`). The pre-existing materialized-`Object`
    // writer path this replaced framed every direct stream node uniformly
    // regardless of nesting position, so
    // restoring that framing for any direct stream this walk reaches keeps
    // parity with it rather than reintroducing a silent data-loss gap for
    // a direct stream sibling outside `/Contents`.
    fn emit_value(&mut self, value: &ObjectHandle, root: bool, indent: usize) -> crate::Result<()> {
        stacker::maybe_grow(
            CONTENT_EMIT_STACK_RED_ZONE,
            CONTENT_EMIT_STACK_GROWTH_SIZE,
            || {
                if !root {
                    if let Some(object_ref) = value.object_ref() {
                        if object_ref.number == 0 || self.removed_refs.contains(&object_ref) {
                            self.out.extend_from_slice(b"null");
                        } else {
                            self.out
                                .extend_from_slice((self.map)(object_ref)?.to_string().as_bytes());
                        }
                        return Ok(());
                    }
                }

                value.try_dereference()?;
                if value.as_stream_dict().is_some() {
                    return self.emit_direct_stream(value, indent);
                }

                if root {
                    if value.as_array().is_some() && has_direct_stream_in_value(value)? {
                        let items = value.as_array().ok_or_else(|| {
                            // cov:ignore-start: the handle cannot change between the shape probe and this read
                            crate::Error::Internal(
                                "content array disappeared during emission".into(),
                            )
                            // cov:ignore-end
                        })?; // cov:ignore: the preceding shape probe makes this defensive error unreachable
                        return self.emit_array(&items, indent);
                    }
                    if let Some(entries) = value.as_dictionary() {
                        let has_contents_stream = entries
                            .get(b"/Contents".as_slice())
                            .map(has_direct_stream_in_value)
                            .transpose()?
                            .unwrap_or(false);
                        if has_contents_stream {
                            return self.emit_dictionary(&entries, indent);
                        }
                    }
                } else if has_direct_stream_in_value(value)? {
                    if let Some(items) = value.as_array() {
                        return self.emit_array(&items, indent);
                    }
                    if let Some(entries) = value.as_dictionary() {
                        return self.emit_dictionary(&entries, indent);
                    } // cov:ignore: LLVM does not attribute this successful nested dictionary continuation
                }

                if self.qdf {
                    value.write_object_qdf_with_ref_map_and_removed_with_string_writer(
                        self.out,
                        indent,
                        self.map,
                        self.removed_refs,
                        self.write_string,
                    )
                } else {
                    value.write_object_with_ref_map_and_removed_with_string_writer(
                        self.out,
                        self.map,
                        self.removed_refs,
                        self.write_string,
                    )
                }
            },
        )
    }

    fn emit_array(&mut self, items: &[ObjectHandle], indent: usize) -> crate::Result<()> {
        if self.qdf {
            self.out.extend_from_slice(b"[\n");
            for item in items {
                push_spaces(self.out, indent + 2);
                self.emit_value(item, false, indent + 2)?;
                self.out.push(b'\n');
            }
            push_spaces(self.out, indent);
            self.out.push(b']');
        } else {
            self.out.push(b'[');
            for item in items {
                self.out.push(b' ');
                self.emit_value(item, false, indent)?;
            }
            self.out.extend_from_slice(b" ]");
        }
        Ok(())
    }

    fn emit_dictionary(
        &mut self,
        entries: &BTreeMap<Vec<u8>, ObjectHandle>,
        indent: usize,
    ) -> crate::Result<()> {
        if self.qdf {
            self.out.extend_from_slice(b"<<\n");
        } else {
            self.out.extend_from_slice(b"<<");
        }

        for (key, value) in entries {
            if value.try_is_null()? || is_removed_content_reference(value, self.removed_refs) {
                continue;
            }
            if self.qdf {
                push_spaces(self.out, indent + 2);
            } else {
                self.out.push(b' ');
            }
            write_content_key(self.out, key);
            self.out.push(b' ');
            self.emit_value(value, false, indent + 2)?; // cov:ignore: LLVM does not attribute the successful nested emitter continuation
            if self.qdf {
                self.out.push(b'\n');
            }
        }

        if self.qdf {
            push_spaces(self.out, indent);
            self.out.extend_from_slice(b">>");
        } else {
            self.out.extend_from_slice(b" >>");
        }
        Ok(())
    }

    fn emit_direct_stream(&mut self, stream: &ObjectHandle, indent: usize) -> crate::Result<()> {
        let dict = stream.as_stream_dict().ok_or_else(|| {
            // cov:ignore-start: emit_direct_stream is called only after the stream shape probe
            crate::Error::Internal("direct content stream dictionary is missing".into())
            // cov:ignore-end
        })?; // cov:ignore: the preceding stream shape probe makes this defensive error unreachable
        if self.qdf {
            dict.write_object_qdf_with_ref_map_and_removed_with_string_writer(
                self.out,
                indent,
                self.map,
                self.removed_refs,
                self.write_string,
            )?; // cov:ignore: LLVM does not attribute the successful QDF dictionary continuation
        } else {
            dict.write_object_with_ref_map_and_removed_with_string_writer(
                self.out,
                self.map,
                self.removed_refs,
                self.write_string,
            )?; // cov:ignore: LLVM does not attribute the successful compact dictionary continuation
        }
        self.out.extend_from_slice(b"\nstream\n");
        self.out
            .extend_from_slice(stream.get_raw_stream_data()?.as_ref());
        self.out.extend_from_slice(b"\nendstream");
        Ok(())
    }
}

// The recursion hub for this function's own `Array`/`Dictionary` arms --
// every nested descent funnels back through this same entry point, so
// wrapping here bounds the whole probe walk the same way
// `object_handle.rs`'s own single-hub recursive walkers do. See
// `CONTENT_EMIT_STACK_RED_ZONE`'s doc for why this needs the same
// protection those walkers already have.
fn has_direct_stream_in_value(value: &ObjectHandle) -> crate::Result<bool> {
    stacker::maybe_grow(
        CONTENT_EMIT_STACK_RED_ZONE,
        CONTENT_EMIT_STACK_GROWTH_SIZE,
        || {
            if value.is_indirect() {
                return Ok(false);
            }
            value.try_dereference()?;
            if value.as_stream_dict().is_some() {
                return Ok(true);
            }
            if let Some(items) = value.as_array() {
                for item in items {
                    if has_direct_stream_in_value(&item)? {
                        return Ok(true);
                    }
                }
            } else if let Some(entries) = value.as_dictionary() {
                for (_, child) in entries {
                    if has_direct_stream_in_value(&child)? {
                        return Ok(true);
                    } // cov:ignore: LLVM does not attribute this successful nested dictionary scan continuation
                }
            }
            Ok(false)
        },
    )
}

fn is_removed_content_reference(value: &ObjectHandle, removed_refs: &BTreeSet<ObjectRef>) -> bool {
    value
        .object_ref()
        .is_some_and(|object_ref| removed_refs.contains(&object_ref))
}

fn write_content_key(out: &mut Vec<u8>, key: &[u8]) {
    out.push(b'/');
    let key = key.strip_prefix(b"/").unwrap_or(key);
    crate::pdf_syntax::write_name_escaped(out, key);
}

fn push_spaces(out: &mut Vec<u8>, count: usize) {
    out.resize(out.len().saturating_add(count), b' ');
}

/// Canonical stream output for qpdf's linearized body route.
///
/// `QPDFWriter::writeLinearized` uses the same metadata decision in its
/// `willFilterStream` probe and its final emission (`QPDFWriter.cc:1234-1314`),
/// so planning and writing must share the full-rewrite metadata policy here.
///
/// `normalize_content` must be the caller's own per-stream identity
/// decision (matching qpdf's `m->normalize_content &&
/// m->normalized_streams.count(old_og)` gate, `QPDFWriter.cc:1277`), not a
/// blanket `options.content_normalization` -- normalization applies only to
/// actual page-content streams, never document-wide.
pub(crate) fn canonical_stream_output_for_linearization(
    handle: &ObjectHandle,
    options: &WriterOptions,
    normalize_content: bool,
) -> crate::Result<(ObjectHandle, Vec<u8>, bool)> {
    let (dict, data, refiltered, _) =
        canonical_stream_output_for_linearization_with_status(handle, options, normalize_content)?;
    Ok((dict, data, refiltered))
}

pub(crate) fn canonical_stream_output_for_linearization_with_status(
    handle: &ObjectHandle,
    options: &WriterOptions,
    normalize_content: bool,
) -> crate::Result<(ObjectHandle, Vec<u8>, bool, bool)> {
    canonical_stream_output_with_status(handle, options, true, normalize_content)
}

/// Return whether the qpdf-shaped stream pipeline will replace the source
/// `/Filter` and `/DecodeParms` entries for a plain rewrite.
///
/// The plain writer must know this before it assigns object numbers: qpdf's
/// `unparseObject` removes those entries before it enqueues dictionary
/// children (`QPDFWriter.cc:1438-1455`); the dictionary child walk is
/// `QPDFWriter.cc:1490-1503`. This helper probes the same pipeline
/// with a discard sink for writer routes that cannot retain the produced
/// buffer. A failed filter probe follows qpdf's retry-to-raw path and
/// therefore returns `false`. The plain planner instead retains the complete
/// output through [`canonical_stream_output_with_status`] so providers are not
/// run again during emission.
pub(crate) fn canonical_stream_will_be_refiltered(
    handle: &ObjectHandle,
    options: &WriterOptions,
) -> crate::Result<bool> {
    canonical_stream_will_be_refiltered_with_policy(handle, options, true, false)
}

/// Probe whether a writer-owned stream will replace its source filter
/// parameters under a specific qpdf writer policy.
///
/// `QPDFWriter::willFilterStream` is called with the state of the writer that
/// will emit the stream. Planning callers must therefore pass the same
/// metadata and content-normalization policy as their emission route; a
/// document-wide default is not equivalent when linearization and full
/// rewrite have different metadata handling.
pub(crate) fn canonical_stream_will_be_refiltered_with_policy(
    handle: &ObjectHandle,
    options: &WriterOptions,
    apply_full_rewrite_metadata_policy: bool,
    normalize_content: bool,
) -> crate::Result<bool> {
    // Token filters are stateful qpdf ValueSetter-style consumers. The plain
    // planner caches their complete output before walking references; callers
    // that cannot retain that output must leave the stream edge intact rather
    // than consuming the filter and running it again during emission.
    if handle.is_data_modified() {
        return Ok(false);
    }
    canonical_stream_filter_probe(
        handle,
        options,
        apply_full_rewrite_metadata_policy,
        normalize_content,
    )
}

/// Consume the writer's qpdf-shaped stream probe without retaining its bytes.
///
/// `QPDFWriter::writeLinearized` calls `QPDF::optimize` with a
/// `skip_stream_parameters` callback. That callback delegates to
/// `willFilterStream`, which pipes a token-filtered stream once before either
/// outer linearization pass (`QPDFWriter.cc:2543-2553`, `1239-1314`). qpdf's
/// `ValueSetter` is stateful, so the later pass observes the filter's consumed
/// state. The linearized route must preserve that ownership and timing; the
/// plain writer instead caches the produced bytes and therefore must continue
/// to use [`canonical_stream_will_be_refiltered_with_policy`].
pub(crate) fn canonical_stream_filter_probe_for_linearization(
    handle: &ObjectHandle,
    options: &WriterOptions,
    normalize_content: bool,
) -> crate::Result<bool> {
    canonical_stream_filter_probe(handle, options, true, normalize_content)
}

fn canonical_stream_filter_probe(
    handle: &ObjectHandle,
    options: &WriterOptions,
    apply_full_rewrite_metadata_policy: bool,
    normalize_content: bool,
) -> crate::Result<bool> {
    let Some((encode_flags, decode_level, _normalized_content)) = canonical_stream_filter_plan(
        handle,
        options,
        apply_full_rewrite_metadata_policy,
        normalize_content,
    )?
    else {
        return Ok(false);
    };

    for attempt in 1..=2 {
        let mut discard = crate::pipeline::Discard;
        let mut filtering_attempted = false;
        let (attempt_encode_flags, attempt_decode_level) = if attempt == 1 {
            (encode_flags, decode_level)
        } else {
            (0, crate::writer::DecodeLevel::None)
        };
        let success = handle
            .pipe_stream_data(
                &mut discard,
                &mut filtering_attempted,
                attempt_encode_flags,
                attempt_decode_level,
                true,
                attempt == 1,
            )
            .map_err(|error| stream_data_error(handle, error))?;
        if success || attempt == 2 {
            return Ok(filtering_attempted && success);
        }
    }

    unreachable!("the two-attempt stream filter probe always returns") // cov:ignore: the bounded two-attempt loop returns from both attempts
}

fn canonical_stream_output_with_rewrite_policy(
    handle: &ObjectHandle,
    options: &WriterOptions,
    apply_full_rewrite_metadata_policy: bool,
    normalize_content: bool,
) -> crate::Result<(ObjectHandle, Vec<u8>, bool, bool)> {
    let stream_dict = handle
        .as_stream_dict()
        .ok_or_else(|| crate::Error::Internal("canonical stream dictionary is missing".into()))?;
    // The CLI's page-content normalizer records its completed transform on
    // the live handle. Generic `replaceStreamData` calls remain eligible for
    // QDF normalization, because replacement bytes alone do not establish
    // that this particular consumer has already normalized them. The filter
    // plan still treats the marker as an effective normalization request so
    // those already-raw bytes are not recompressed.
    // QPDFWriter.cc:1251-1278 gives cleartext /Type /Metadata streams their
    // own policy: decode fully and emit without a filter, even when the global
    // writer policy would preserve or compress a lone-Flate source. The plain
    // route is unencrypted, so this exception always applies here.
    let is_metadata_stream = apply_full_rewrite_metadata_policy
        && stream_dict.try_is_dictionary_of_type(b"Metadata", b"")?
        && options
            .encrypt
            .as_ref()
            .is_none_or(|params| !params.encrypt_metadata)
        && options
            .copy_encryption
            .as_ref()
            .is_none_or(|source| !crate::writer::copy_encryption_encrypts_metadata(source));
    // qpdf's `willFilterStream` treats the cleartext-metadata and
    // content-normalization branches as mutually exclusive: an `if
    // (is_metadata) ... else if (normalize_content) ...` chain
    // (`QPDFWriter.cc:1274-1284`), so `normalize` never becomes true once
    // `is_metadata` wins it. Metadata is not page content, so it must never
    // receive content-token normalization, mirroring the same guard
    // `reencode_stream_for_compress` already applies in `writer.rs`.
    let normalize_content = normalize_content && !is_metadata_stream;
    let policy = if is_metadata_stream {
        Some(CompressStreams::No)
    } else {
        crate::writer::effective_stream_policy(options)
    };
    let source_for_pipe = handle.clone();

    // QPDFWriter::willFilterStream starts with `isDataModified()` before it
    // considers the user compression policy (`QPDFWriter.cc:1234-1245`). A
    // token-filtered stream must therefore take the pipe path even under
    // Preserve mode; only an unmodified stream may be emitted verbatim.
    let filter_plan = canonical_stream_filter_plan(
        handle,
        options,
        apply_full_rewrite_metadata_policy,
        normalize_content,
    )?; // cov:ignore: canonical stream policy validation is exercised by the body tests; llvm-cov attributes this continuation to the defensive error path
    let (data, filtering_attempted, normalized_content) =
        if let Some((encode_flags, decode_level, normalized_content)) = filter_plan {
            let mut attempt = 1_u8;
            let (data, filtering_attempted) = loop {
                let mut buffer =
                    crate::pipeline::buffer::Buffer::new("canonical writer stream", None);
                let mut filtering_attempted = false;
                let (attempt_encode_flags, attempt_decode_level) = if attempt == 1 {
                    (encode_flags, decode_level)
                } else {
                    (0, crate::writer::DecodeLevel::None)
                };
                let success = source_for_pipe
                    .pipe_stream_data(
                        &mut buffer,
                        &mut filtering_attempted,
                        attempt_encode_flags,
                        attempt_decode_level,
                        false,
                        attempt == 1,
                    )
                    .map_err(|error| stream_data_error(&source_for_pipe, error))?; // cov:ignore: filter-pipeline failures are covered at the pipeline boundary, not by this validated emitter

                if success || attempt == 2 {
                    // QPDFWriter retries a failed filter pipeline against a
                    // fresh raw pipe (`QPDFWriter.cc:1287-1314`). The second
                    // attempt's buffer is authoritative even when the
                    // provider reports that no filtering branch was used.
                    break (
                        buffer.take_buffer()?.to_vec(),
                        filtering_attempted && success,
                    );
                }
                attempt = 2;
            };
            (data, filtering_attempted, normalized_content)
        } else {
            (
                canonical_stream_source_data(&source_for_pipe)
                    .map_err(|error| stream_data_error(&source_for_pipe, error))?,
                false,
                false,
            )
        };
    let mut entries = stream_dict.try_as_dictionary()?.unwrap_or_default();
    entries.remove(b"/Length".as_slice());
    if !filtering_attempted {
        remove_crypt_filter_for_unfiltered_stream(&mut entries)?;
    }
    if filtering_attempted {
        entries.retain(|key, _| {
            !matches!(
                key.as_slice(),
                b"/Filter" | b"/DecodeParms" | b"/F" | b"/FFilter" | b"/FDecodeParms"
            )
        });
        // qpdf's normalization branch wins over the ordinary compression
        // branch (`QPDFWriter.cc:1279-1284`): normalized page content is
        // emitted decoded, even when compress_streams is enabled.
        if matches!(policy, Some(CompressStreams::Yes)) && !normalized_content {
            entries.insert(
                b"/Filter".to_vec(),
                ObjectHandle::name(b"FlateDecode".to_vec()),
            );
        }
    }
    entries.insert(
        b"/Length".to_vec(),
        ObjectHandle::integer(i64::try_from(data.len()).unwrap_or(i64::MAX)),
    );
    let dict = ObjectHandle::dictionary(entries.into_iter().collect());
    let refiltered =
        filtering_attempted && matches!(policy, Some(CompressStreams::Yes)) && !normalized_content;
    Ok((dict, data, refiltered, filtering_attempted))
}

/// Read a stream through qpdf's writer-owned unfiltered pipe.
///
/// `QPDFWriter::willFilterStream` still calls `pipeStreamData` once when
/// `filter_on_write` is false, passing `will_retry=true` for that first
/// attempt (`libqpdf/QPDFWriter.cc:1254-1314`). This is observably different
/// from `getRawStreamData`, whose public accessor passes `will_retry=false`
/// (`libqpdf/QPDF_Stream.cc:362-376`). In particular, a retry-aware provider
/// may return `false` after writing its bytes; qpdf's writer keeps that buffer
/// because filtering is already disabled and does not enter the retry branch.
/// Keep the source success bit out of this writer result for the same reason.
fn canonical_stream_source_data(handle: &ObjectHandle) -> crate::Result<Vec<u8>> {
    let mut buffer = crate::pipeline::buffer::Buffer::new("canonical writer stream", None);
    let mut filtering_attempted = false;
    let _source_success = handle.pipe_stream_data(
        &mut buffer,
        &mut filtering_attempted,
        0,
        crate::writer::DecodeLevel::None,
        false,
        true,
    )?; // cov:ignore: LLVM attributes this covered qpdf-shaped multiline call terminator without an executable counter
    Ok(buffer.take_buffer()?.to_vec())
}

fn stream_data_error(handle: &ObjectHandle, error: crate::Error) -> crate::Error {
    if let Some(object_ref) = handle.object_ref() {
        crate::Error::System(format!(
            "error while getting stream data for {object_ref}: {error}"
        ))
    } else {
        // cov:ignore: qpdf writer stream errors are always attributed to indirect object handles
        error
    }
}

fn canonical_stream_filter_plan(
    handle: &ObjectHandle,
    options: &WriterOptions,
    apply_full_rewrite_metadata_policy: bool,
    normalize_content: bool,
) -> crate::Result<Option<(u32, crate::writer::DecodeLevel, bool)>> {
    let stream_dict = handle
        .as_stream_dict()
        .ok_or_else(|| crate::Error::Internal("canonical stream dictionary is missing".into()))?;
    // QPDFWriter::willFilterStream first derives a filter request from the
    // stream and writer state, then lets QPDF_Stream::filter_on_write veto
    // every filtering branch (`QPDFWriter.cc:1254-1285`). Keep that veto
    // ahead of metadata, normalization, and compression policy construction:
    // false means raw source dispatch regardless of any of those settings.
    if !handle.get_filter_on_write()? {
        return Ok(None);
    }
    // The CLI may have already normalized and replaced this stream's bytes.
    // Keep that state as an effective normalization request so qpdf's
    // normalization branch still suppresses compression, while avoiding a
    // second tokenizer pass on the same bytes.
    let normalization_applied = normalize_content && handle.content_normalization_applied();
    let normalize_content = normalize_content && !normalization_applied;
    let source_has_lone_flate = canonical_is_lone_flate(&stream_dict)?;
    let is_metadata_stream = apply_full_rewrite_metadata_policy
        && stream_dict.try_is_dictionary_of_type(b"Metadata", b"")?
        && options
            .encrypt
            .as_ref()
            .is_none_or(|params| !params.encrypt_metadata)
        && options
            .copy_encryption
            .as_ref()
            .is_none_or(|source| !crate::writer::copy_encryption_encrypts_metadata(source));
    let normalize_content = normalize_content && !is_metadata_stream;
    let normalized_content = (normalize_content || normalization_applied) && !is_metadata_stream;
    let policy = if is_metadata_stream {
        Some(CompressStreams::No)
    } else {
        crate::writer::effective_stream_policy(options)
    };
    let decode_level = if is_metadata_stream {
        crate::writer::DecodeLevel::All
    } else {
        options.decode_level
    };
    let preserve_lone_flate = matches!(policy, Some(CompressStreams::Yes))
        && source_has_lone_flate
        && !handle.is_data_modified()
        && !options.recompress_flate
        && !normalized_content
        && !stream_dict.try_has_key(b"/F")?;
    if !handle.is_data_modified() && (policy.is_none() || preserve_lone_flate) {
        return Ok(None);
    }

    // qpdf's `normalize_content` branch is an `else if` before the ordinary
    // `compress_streams` branch (`QPDFWriter.cc:1279-1284`), so normalization
    // must not also request Flate re-encoding.
    let mut encode_flags = if matches!(policy, Some(CompressStreams::Yes)) && !normalized_content {
        crate::object_handle::STREAM_ENCODE_COMPRESS
    } else {
        0
    };
    if normalize_content {
        encode_flags |= crate::object_handle::STREAM_ENCODE_NORMALIZE;
    }
    Ok(Some((encode_flags, decode_level, normalized_content)))
}

/// Mirror `QPDFWriter::unparseObject`'s unfiltered-stream cleanup
/// (`libqpdf/QPDFWriter.cc:1446-1478`): source encryption is applied by the
/// resolver pipe, so the writer never carries an explicit `/Crypt` stage into
/// a rewritten stream dictionary. A direct `/Crypt` removes both filter keys;
/// an array removes the first `/Crypt` item and its paired `/DecodeParms` slot,
/// preserving the remaining filter representation byte-for-byte.
fn remove_crypt_filter_for_unfiltered_stream(
    entries: &mut std::collections::BTreeMap<Vec<u8>, ObjectHandle>,
) -> crate::Result<()> {
    let Some(filter) = entries.get(b"/Filter".as_slice()).cloned() else {
        return Ok(());
    };

    if filter.try_is_name_and_equals(b"Crypt")? {
        entries.remove(b"/Filter".as_slice());
        entries.remove(b"/DecodeParms".as_slice());
        return Ok(());
    }

    let Some(filters) = filter.try_as_array()? else {
        return Ok(());
    };
    let mut crypt_index = None;
    for (index, item) in filters.iter().enumerate() {
        if item.try_is_name_and_equals(b"Crypt")? {
            crypt_index = Some(index);
            break;
        }
    }
    let Some(crypt_index) = crypt_index else {
        return Ok(());
    };

    let mut remaining_filters = filters;
    remaining_filters.remove(crypt_index);
    entries.insert(b"/Filter".to_vec(), ObjectHandle::array(remaining_filters));

    let Some(decode_parms) = entries.get(b"/DecodeParms".as_slice()).cloned() else {
        return Ok(());
    };
    let Some(mut decode_items) = decode_parms.try_as_array()? else {
        return Ok(());
    };
    if decode_items.len() > crypt_index {
        decode_items.remove(crypt_index);
        entries.insert(b"/DecodeParms".to_vec(), ObjectHandle::array(decode_items));
    }
    Ok(())
}

fn canonical_is_lone_flate(dict: &ObjectHandle) -> crate::Result<bool> {
    let filter = dict.try_get_key(b"/Filter")?;
    if filter.try_is_null()? {
        return Ok(false);
    }
    if filter.try_is_name_and_equals(b"FlateDecode")? || filter.try_is_name_and_equals(b"Fl")? {
        return Ok(true);
    }
    Ok(false)
}

fn validate_objstm_member_bodies<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    plan: &PlainWritePlan,
) -> crate::Result<()> {
    if !plan
        .objects
        .iter()
        .any(|object| matches!(object, PlannedIndirectObject::ObjectStream { .. }))
    {
        return Ok(());
    }

    let context = object_streams::eligibility_context(pdf)?;
    for planned in &plan.objects {
        let PlannedIndirectObject::ObjectStream { members, .. } = planned else {
            continue;
        };
        for member in members {
            let member_handle = pdf.get_object_handle(member.source);
            pdf.resolve(&member_handle)?;
            let is_signature = object_streams::is_qpdf_signature_dict(pdf, &member_handle)?;
            let violation = planned_member_body_violation(
                member.source,
                member.output,
                &member_handle,
                &context,
            )? // cov:ignore: trailing `)?` on a multi-line validation call — llvm-cov attributes the validated continuation to the Err path
            .or(is_signature.then_some("signature dictionary"));
            if let Some(kind) = violation {
                return Err(crate::Error::Unsupported(format!(
                    "plain writer body invariant: source {} planned as ObjStm member {} \
                     resolves to forbidden {kind}",
                    member.source, member.output
                )));
            }
        }
    }
    Ok(())
}

fn planned_member_body_violation(
    source: crate::ObjectRef,
    output: crate::ObjectRef,
    object: &ObjectHandle,
    context: &object_streams::EligibilityContext,
) -> crate::Result<Option<&'static str>> {
    if output.generation != 0 {
        return Ok(Some("nonzero output generation"));
    }
    if object.as_stream_dict().is_some() {
        return Ok(Some("stream body"));
    }
    if object.try_is_dictionary_of_type(b"XRef", b"")? {
        return Ok(Some("/Type /XRef dictionary"));
    }
    if object.try_is_dictionary_of_type(b"ObjStm", b"")? {
        return Ok(Some("/Type /ObjStm dictionary"));
    }
    if context.encryption_ref == Some(source) {
        return Ok(Some("encryption dictionary"));
    }
    Ok(None)
}

#[cfg(test)]
mod final_handle_tests {
    use super::emit_content_container_from_handle_with_ref_map;
    use crate::writer::{NewlineBeforeEndstream, WriterOptions};
    use crate::ObjectHandle;
    use std::collections::BTreeSet;
    use std::rc::Rc;

    #[test]
    fn content_container_emits_direct_streams_and_uses_the_handle_string_writer() {
        let stream = ObjectHandle::stream(
            ObjectHandle::dictionary(vec![
                (b"/Length".to_vec(), ObjectHandle::integer(4)),
                (b"/Label".to_vec(), ObjectHandle::string(b"data".to_vec())),
            ]),
            Rc::new(b"data".to_vec()),
        );
        let container = ObjectHandle::dictionary(vec![(b"/Contents".to_vec(), stream)]);
        let options = WriterOptions {
            newline_before_endstream: NewlineBeforeEndstream::Never,
            ..WriterOptions::default()
        };
        let map = |object_ref| Ok(object_ref);
        let mut output = Vec::new();

        emit_content_container_from_handle_with_ref_map(
            &container,
            &options,
            &mut output,
            &map,
            &BTreeSet::new(),
        )
        .expect("direct content stream emission");

        assert!(output
            .windows(b"/Contents".len())
            .any(|window| window == b"/Contents"));
        assert!(output
            .windows(b"stream\ndata\nendstream".len())
            .any(|window| { window == b"stream\ndata\nendstream" }));
    }
}