ferri-pdf 0.1.10

HTML and CSS to PDF renderer for print, in pure Rust
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
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
use crate::{document::BlockBox, layout::LayoutError};
use std::{
    cell::{Cell, RefCell},
    rc::Rc,
};

/// The fractions of a budget, as right shifts of it, whose spending marks the frontier,
/// smallest first.
const MARK_SHIFTS: [u32; 4] = [4, 3, 2, 1];

/// A work budget shared by every clone, each charging the units of work it does.
#[derive(Clone)]
pub(crate) struct Budget {
    limit: usize,
    remaining: Rc<Cell<Option<usize>>>,
    /// Optional work was skipped for want of units.
    declined: Rc<Cell<bool>>,
    /// The formatting box of the document being laid out that layout last started.
    frontier: Rc<Cell<Frontier>>,
    /// The frontier where each of [`MARK_SHIFTS`]'s fractions of the budget was spent, and the
    /// spending that marks the next.
    marks: Rc<RefCell<Vec<Frontier>>>,
    next_mark: Rc<Cell<usize>>,
    /// Lays out a nested document, whose boxes lie inside the frontier's.
    nested: bool,
}

type Frontier = Option<*const BlockBox>;

/// A budget of `limit` units ran out.
#[derive(Debug)]
pub(crate) struct Exhausted {
    pub(crate) limit: usize,
}

impl From<Exhausted> for LayoutError {
    fn from(Exhausted { limit }: Exhausted) -> Self {
        Self::WorkLimit { limit }
    }
}

impl Budget {
    pub(crate) fn new(limit: usize) -> Self {
        Self {
            limit,
            remaining: Rc::new(Cell::new(Some(limit))),
            declined: Rc::new(Cell::new(false)),
            frontier: Rc::default(),
            marks: Rc::default(),
            next_mark: Rc::new(Cell::new(limit >> MARK_SHIFTS[0])),
            nested: false,
        }
    }

    /// Charges `units` of optional work where they remain, else leaves the budget as it is
    /// and records that the work was skipped.
    pub(crate) fn spend_optional(&self, units: usize) -> bool {
        if let Some(left) = self
            .remaining
            .get()
            .and_then(|left| left.checked_sub(units))
        {
            self.remaining.set(Some(left));
            true
        } else {
            self.declined.set(true);
            false
        }
    }

    /// The budget's limit, where optional work was skipped for want of units.
    pub(crate) fn declined(&self) -> Option<usize> {
        self.declined.get().then_some(self.limit)
    }

    /// The budget's limit, once work ran it out.
    pub(crate) fn exhausted(&self) -> Option<usize> {
        self.remaining.get().is_none().then_some(self.limit)
    }

    /// The units charged, all of them once the budget is exhausted.
    pub(crate) fn spent(&self) -> usize {
        self.limit - self.remaining.get().unwrap_or(0)
    }

    /// Charges `units` of work already done; past the limit the budget is exhausted.
    pub(crate) fn charge(&self, units: usize) {
        self.remaining.set(
            self.remaining
                .get()
                .and_then(|left| left.checked_sub(units)),
        );
    }

    /// The budget shared by the layout of a document nested in the box being laid out.
    pub(crate) fn nested(&self) -> Self {
        Self {
            nested: true,
            ..self.clone()
        }
    }

    /// Records that layout starts `block`.
    pub(crate) fn start(&self, block: &BlockBox) {
        if !self.nested {
            self.frontier.set(Some(std::ptr::from_ref(block)));
        }
    }

    /// The box layout last started.
    pub(crate) fn frontier(&self) -> Frontier {
        self.frontier.get()
    }

    /// The boxes layout last started where it had spent each of [`MARK_SHIFTS`]'s fractions of
    /// the budget, smallest first: the content before each took at most that fraction.
    pub(crate) fn marks(&self) -> Vec<Frontier> {
        self.marks.borrow().clone()
    }

    pub(crate) fn spend(&self, units: usize) -> Result<(), Exhausted> {
        let remaining = self
            .remaining
            .get()
            .and_then(|left| left.checked_sub(units));
        self.remaining.set(remaining);
        let spent = self.spent();
        if spent >= self.next_mark.get() {
            let mut marks = self.marks.borrow_mut();
            while let Some(shift) = MARK_SHIFTS.get(marks.len())
                && spent >= self.limit >> shift
            {
                marks.push(self.frontier.get());
            }
            self.next_mark.set(
                MARK_SHIFTS
                    .get(marks.len())
                    .map_or(usize::MAX, |shift| self.limit >> shift),
            );
        }
        remaining.map(|_| ()).ok_or(Exhausted { limit: self.limit })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::document::StyledDocument;
    use crate::layout::{MAX_FAILED_LAYOUT_BUDGETS, MAX_LAYOUT_WORK, layout_with_work_limit};
    use crate::resources::{FileResolver, ResourceBase};

    #[test]
    fn target_stabilization_charges_all_passes_to_one_budget() {
        let resolver = FileResolver::default();
        let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/oracle/fixtures")
            .into();
        let mut document = StyledDocument::parse(
            "<style>@font-face{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}body{font-family:Fixed}p::after{content:target-counter('#target',page)}h2{break-before:page}</style><p>See </p><h2 id=target>Destination</h2>",
            &base, &[], &resolver,
        ).unwrap();
        let measurement = Budget::new(MAX_LAYOUT_WORK);
        crate::layout::layout_pass(&document, &resolver, measurement.clone()).unwrap();
        let first_pass_work = MAX_LAYOUT_WORK - measurement.remaining.get().unwrap();
        assert!(first_pass_work > 0);
        let provisional = crate::layout::stabilize(
            &mut document,
            &resolver,
            &Budget::new(first_pass_work),
            Vec::new(),
        )
        .expect("a budget that only fits the provisional pass keeps that pass");
        let text: Vec<_> = provisional
            .pages
            .iter()
            .flatten()
            .map(|line| line.text.as_str())
            .collect();
        assert_eq!(
            text,
            ["See", "Destination"],
            "the kept pass is the provisional one, whose target counter is not yet resolved"
        );
        let diagnostics = document.into_diagnostics();
        assert_eq!(
            diagnostics
                .iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>(),
            [crate::layout::LayoutDiagnostic::WorkLimit {
                limit: first_pass_work,
                kept: crate::layout::WorkFallback::LastPass,
            }
            .to_string()],
            "the budget is shared by every pass and its exhaustion is reported once"
        );
        assert!(
            crate::checked_diagnostics(diagnostics, crate::ContentLoss::Fail).is_ok(),
            "keeping the last pass loses no content, so the default policy renders it"
        );
    }

    #[test]
    fn a_first_pass_out_of_work_omits_the_content_it_reached_late() {
        const ITEMS: usize = 300;
        let resolver = FileResolver::default();
        let base: ResourceBase = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/oracle/fixtures")
            .into();
        let document = || {
            StyledDocument::parse(
                &format!(
                    "<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:200pt 200pt;margin:10pt}}html,body{{margin:0;font:10pt/10pt Fixed}}</style><p>before</p><section>{}</section><p>after</p>",
                    "<div>item</div>".repeat(ITEMS)
                ),
                &base,
                &[],
                &resolver,
            )
            .unwrap()
        };
        let limit = required_work(&document(), &resolver) / 2;
        let (document, trace) = crate::layout::layout_within(
            document(),
            &resolver,
            limit,
            &Budget::new(limit * MAX_FAILED_LAYOUT_BUDGETS),
        )
        .expect("a document that exceeds its work budget keeps the content laid out within it");
        let text: Vec<_> = trace
            .pages
            .iter()
            .flatten()
            .map(|line| line.text.as_str())
            .collect();
        let items = text.iter().filter(|line| **line == "item").count();
        assert_eq!(text.first(), Some(&"before"), "the content before is kept");
        assert!(
            (1..ITEMS).contains(&items) && !text.contains(&"after"),
            "the content from a box started late in the budget is omitted: \
             {items} of {ITEMS} items kept, text ends {:?}",
            text.last()
        );
        let diagnostics = document.into_diagnostics();
        assert_eq!(
            diagnostics
                .iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>(),
            [crate::layout::LayoutDiagnostic::WorkLimit {
                limit,
                kept: crate::layout::WorkFallback::Truncated,
            }
            .to_string()],
            "the omission is reported once however many layouts it takes"
        );
        match crate::checked_diagnostics(diagnostics, crate::ContentLoss::Fail) {
            Err(crate::Error::ContentLost { diagnostics }) => assert_eq!(
                diagnostics.len(),
                1,
                "the default policy fails with the truncation: {diagnostics:?}"
            ),
            other => panic!(
                "the default policy must fail on the truncated content, got {:?}",
                other.map(|_| ())
            ),
        }
    }

    #[test]
    fn failed_layouts_share_one_bounded_budget_before_all_content_is_omitted() {
        const ITEMS: usize = 40;
        // Each section ends in a box whose padding leaves it no finite geometry, so each
        // layout fails at the next of them and omits it.
        const SECTIONS: usize = crate::layout::MAX_OMITTED_BOXES;
        const FAILING_BOX: &str = "<div class=over></div>";
        let resolver = FileResolver::default();
        let base: ResourceBase = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/oracle/fixtures")
            .into();
        let parse = |failing: &str| {
            StyledDocument::parse(
                &format!(
                    "<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:200pt 200pt;margin:10pt}}html,body{{margin:0;font:10pt/10pt Fixed}}.over{{padding:3e38pt 0}}</style>{}",
                    format!("<section>{}</section>{failing}", "<div>item</div>".repeat(ITEMS))
                        .repeat(SECTIONS)
                ),
                &base,
                &[],
                &resolver,
            )
            .unwrap()
        };
        let omitted = |document: StyledDocument| {
            document.into_diagnostics().into_iter().any(|diagnostic| {
                matches!(
                    diagnostic,
                    crate::RenderDiagnostic::Layout(crate::LayoutDiagnostic::OmittedBox { .. })
                )
            })
        };
        let limit = required_work(&parse(""), &resolver);
        let unbounded = Budget::new(usize::MAX);
        let (document, trace) =
            crate::layout::layout_within(parse(FAILING_BOX), &resolver, limit, &unbounded)
                .expect("omitting each failing box completes the layout");
        let unbounded_work = unbounded.spent();
        assert!(
            unbounded_work > limit && omitted(document),
            "fixture: omitting the {SECTIONS} failing boxes one at a time spends {unbounded_work} \
             units in failed layouts, more than one {limit}-unit layout budget"
        );
        assert!(
            trace.pages.iter().flatten().any(|line| line.text == "item"),
            "fixture: with work to spare for failed layouts the items stay"
        );
        // The failed layouts may share one layout budget here: the charge that spends it is
        // the last, so they spend less than two.
        let failed = Budget::new(limit);
        let (document, trace) =
            crate::layout::layout_within(parse(FAILING_BOX), &resolver, limit, &failed)
                .expect("failed layouts past their shared budget omit all content, not fail");
        assert!(
            failed.exhausted().is_some(),
            "the failed layouts stop once they spend the {limit} units they share"
        );
        let text: Vec<_> = trace
            .pages
            .iter()
            .flatten()
            .map(|line| line.text.as_str())
            .collect();
        assert!(
            text.is_empty(),
            "the layout after them omits all content: {text:?}"
        );
        assert!(omitted(document), "the omitted boxes are reported");
    }

    #[test]
    fn exhaustion_is_inclusive_overflow_safe_and_sticky() {
        let budget = Budget::new(8);
        budget.spend(3).unwrap();
        budget.spend(5).unwrap();
        assert!(matches!(budget.spend(1), Err(Exhausted { limit: 8 })));
        assert!(matches!(budget.spend(0), Err(Exhausted { limit: 8 })));
        let budget = Budget::new(usize::MAX - 1);
        assert!(matches!(budget.spend(usize::MAX), Err(Exhausted { .. })));
        assert!(budget.spend(1).is_err());
    }

    #[test]
    fn column_candidates_share_the_jobs_budget_without_poisoning_later_jobs() {
        const LIMIT: usize = 8192;
        let resolver = FileResolver::default();
        let content = "<div class=item></div>".repeat(320);
        let parse = |columns| {
            StyledDocument::parse(
                &format!(
                    "<!doctype html><style>@page{{size:200pt 200pt;margin:10pt}}html,body{{margin:0}}.item{{height:10pt}}section{{{columns}}}</style><section>{content}</section>"
                ),
                &ResourceBase::default(),
                &[],
                &resolver,
            ).unwrap()
        };
        let ordinary = parse("");
        let columns = parse("column-count:2;column-gap:10pt");
        let expected = layout_with_work_limit(&ordinary, &resolver, LIMIT).unwrap();
        match layout_with_work_limit(&columns, &resolver, LIMIT) {
            Err(LayoutError::WorkLimit { limit }) => assert_eq!(limit, LIMIT),
            Err(error) => panic!("unexpected column failure: {error}"),
            Ok(trace) => panic!(
                "column probes escaped the shared budget: {} pages",
                trace.pages.len()
            ),
        }
        let completed = layout_with_work_limit(&columns, &resolver, MAX_LAYOUT_WORK).unwrap();
        assert!(!completed.pages.is_empty());
        let next = layout_with_work_limit(&ordinary, &resolver, LIMIT).unwrap();
        assert_eq!(expected.pages.len(), next.pages.len());
    }

    #[test]
    fn automatic_columns_resume_each_row_within_the_shared_work_budget() {
        const LIMIT: usize = 16_384;
        const BLOCKS: usize = 256;
        const BLOCKS_PER_PAGE: usize = 8;
        let resolver = FileResolver::default();
        let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/oracle/fixtures")
            .into();
        let content = (0..BLOCKS)
            .map(|index| {
                format!("<div id=item{index}><a href=\"#item{index}\">B{index:03}</a></div>")
            })
            .collect::<String>();
        let document = StyledDocument::parse(
            &format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:200pt 40pt;margin:0}}html,body{{margin:0;font:10pt/10pt Fixed;widows:1;orphans:1}}section{{column-count:2;column-gap:10pt;column-fill:auto}}div{{height:10pt;background:red}}</style><section>{content}</section>"),
            &base, &[], &resolver,
        ).unwrap();
        assert_eq!(
            document.navigation().destinations,
            BLOCKS,
            "fixture must register each linked target"
        );
        let output = layout_with_work_limit(&document, &resolver, LIMIT).unwrap_or_else(|error| {
            panic!("each physical row must resume its source checkpoint: {error}")
        });
        assert_eq!(output.pages.len(), BLOCKS / BLOCKS_PER_PAGE);
        assert_eq!(
            output.destinations.iter().flatten().count(),
            BLOCKS,
            "every source target must be placed exactly once"
        );
        let actual = output
            .pages
            .iter()
            .flatten()
            .map(|line| line.text.as_str())
            .collect::<Vec<_>>();
        let expected = (0..BLOCKS)
            .map(|index| format!("B{index:03}"))
            .collect::<Vec<_>>();
        assert_eq!(
            actual, expected,
            "each visible source label must be preserved once"
        );
        for (index, destination) in output.destinations.iter().enumerate() {
            let destination = destination.as_ref().expect("every block keeps its target");
            assert_eq!(
                destination.page,
                index / BLOCKS_PER_PAGE,
                "item{index} was replayed or placed on the wrong physical page"
            );
        }
    }

    #[test]
    fn mixed_native_css_layout_and_raw_paint_share_a_bounded_measurement_cache() {
        const SEGMENTS: usize = 8;
        const LIMIT: usize = 1_000_000;
        // Formatting flattens orthogonal flows nested deeper, so a smaller budget, not more
        // segments, is what the same measurements must exhaust.
        const SMALLER_LIMIT: usize = LIMIT / 1000;
        let resolver = FileResolver::default();
        let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/oracle/fixtures")
            .into();
        let open = "<mrow><mtext><span style='display:block;writing-mode:vertical-rl'><math>";
        let close = "</math></span></mtext></mrow>";
        let parse = |segments| {
            StyledDocument::parse(
            &format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}math{{font:10pt Fixed}}</style><math>{}<mn>1</mn>{}</math>", open.repeat(segments), close.repeat(segments)),
            &base, &[], &resolver,
        ).unwrap()
        };
        let document = parse(SEGMENTS);
        let check = || {
            let output = layout_with_work_limit(&document, &resolver, LIMIT)
                .unwrap_or_else(|error| panic!("{SEGMENTS} auto-sized mixed native/CSS boundaries must reuse measurement dependencies through raw paint within {LIMIT} shared units: {error}"));
            assert_eq!(
                output
                    .pages
                    .iter()
                    .flatten()
                    .filter(|line| line.text == "1")
                    .count(),
                1,
                "the single retained token must survive every native/CSS transport exactly once"
            );
        };
        check();
        assert!(
            matches!(
                layout_with_work_limit(&document, &resolver, SMALLER_LIMIT),
                Err(LayoutError::WorkLimit {
                    limit: SMALLER_LIMIT
                })
            ),
            "the same auto-sized orthogonal candidates must exhaust a smaller shared budget with the typed error"
        );
        check();
    }

    #[test]
    fn wide_native_math_batches_siblings_under_one_linear_work_budget() {
        const TOKENS: usize = 8192;
        const WORK_PER_TOKEN: usize = 512;
        const LIMIT: usize = TOKENS * WORK_PER_TOKEN;
        let resolver = FileResolver::default();
        let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/oracle/fixtures")
            .into();
        let content = (0..TOKENS)
            .map(|index| format!("<mn id=token{index}>1</mn>"))
            .collect::<String>();
        let document = StyledDocument::parse(
            &format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:100000pt 100pt;margin:0}}html,body{{margin:0}}math{{font:10pt Fixed}}</style><math>{content}</math>"),
            &base, &[], &resolver,
        ).unwrap();
        assert_eq!(document.navigation().destinations, TOKENS);
        for limit in [MAX_LAYOUT_WORK, LIMIT] {
            let output = layout_with_work_limit(&document, &resolver, limit)
                .unwrap_or_else(|error| panic!("{TOKENS} native siblings must batch within {limit} shared work units: {error}"));
            assert_eq!(
                output.pages.len(),
                1,
                "the wide physical page must hold one native row"
            );
            let lines = output.pages[0]
                .iter()
                .filter(|line| line.text == "1")
                .collect::<Vec<_>>();
            assert_eq!(
                lines.len(),
                TOKENS,
                "every canonical token must paint exactly once"
            );
            assert!(
                output.pages[0].iter().all(|line| line.text == "1"
                    || line
                        .text
                        .chars()
                        .all(|ch| ch == crate::document::OBJECT_REPLACEMENT_CHARACTER)),
                "the host atomic placeholder must not introduce additional visible text"
            );
            assert!(
                lines
                    .windows(2)
                    .all(|pair| pair[0].paragraph < pair[1].paragraph)
                    && lines.iter().all(|line| line.width > 0.0),
                "batch replay must preserve canonical sibling order and positive glyph advances"
            );
            let mut paragraphs = lines.iter().map(|line| line.paragraph).collect::<Vec<_>>();
            paragraphs.sort_unstable();
            paragraphs.dedup();
            assert_eq!(
                paragraphs.len(),
                TOKENS,
                "native siblings must retain distinct canonical paragraph identities"
            );
            assert_eq!(
                output.destinations.iter().flatten().count(),
                TOKENS,
                "each canonical target must retain one page location"
            );
        }
        const EXHAUSTED_LIMIT: usize = TOKENS;
        assert!(
            matches!(
                layout_with_work_limit(&document, &resolver, EXHAUSTED_LIMIT),
                Err(LayoutError::WorkLimit {
                    limit: EXHAUSTED_LIMIT
                })
            ),
            "native frame requests must consume the shared job budget"
        );
        assert!(
            layout_with_work_limit(&document, &resolver, LIMIT).is_ok(),
            "a bounded failure must not poison the next render of the same retained source"
        );
    }

    #[test]
    fn balancing_stops_when_adjacent_heights_cannot_be_bisected() {
        const LIMIT: usize = 4096;
        let resolver = FileResolver::default();
        let document = StyledDocument::parse(
            "<!doctype html><style>@page{size:200pt 2000000pt;margin:0}html,body{margin:0}section{column-count:2;column-gap:0}div{height:1000000pt}</style><section><div></div><div></div></section>",
            &ResourceBase::default(),
            &[],
            &resolver,
        ).unwrap();
        let output = layout_with_work_limit(&document, &resolver, LIMIT)
            .unwrap_or_else(|error| panic!("finite two-column balance failed: {error}"));
        assert_eq!(output.pages.len(), 1);
    }

    #[test]
    fn repeated_table_geometry_consumes_the_same_budget() {
        const LIMIT: usize = 1024;
        const ROWS: usize = 32;
        let resolver = FileResolver::default();
        let body = "<tr><td><div></div></td></tr>".repeat(ROWS);
        let document = StyledDocument::parse(
            &format!("<!doctype html><style>@page{{size:200pt 200pt;margin:10pt}}html,body{{margin:0}}table{{border-spacing:0}}td{{padding:0}}thead div{{height:40pt}}tbody div{{height:100pt}}</style><table><thead><tr><td><div></div></td></tr></thead><tbody>{body}</tbody></table>"),
            &ResourceBase::default(), &[], &resolver,
        ).unwrap();
        assert!(
            matches!(
                layout_with_work_limit(&document, &resolver, LIMIT),
                Err(LayoutError::WorkLimit { limit: LIMIT })
            ),
            "repeated table measurement escaped the job budget"
        );
        let output = layout_with_work_limit(&document, &resolver, MAX_LAYOUT_WORK).unwrap();
        assert_eq!(
            output.pages.len(),
            ROWS,
            "each page fits one body row and its repeated header"
        );
    }

    #[test]
    fn generated_margin_text_shares_the_body_budget() {
        const LIMIT: usize = 4096;
        const PAGES: usize = 8;
        let resolver = FileResolver::default();
        let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/oracle/fixtures")
            .into();
        let body = "<div></div>".repeat(PAGES);
        let margin = "A ".repeat(256);
        let parse = |margin_rule| {
            StyledDocument::parse(
            &format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:200pt 200pt;margin:20pt;{margin_rule}}}html,body{{margin:0}}div{{height:160pt;background:#eee}}</style>{body}"),
            &base, &[], &resolver,
        ).unwrap()
        };
        let ordinary = parse("");
        assert_eq!(
            layout_with_work_limit(&ordinary, &resolver, LIMIT)
                .unwrap()
                .pages
                .len(),
            PAGES
        );
        let margins = parse(&format!(
            "@top-center{{font:1pt/1pt Fixed;content:'{margin}'}}"
        ));
        assert!(
            matches!(
                layout_with_work_limit(&margins, &resolver, LIMIT),
                Err(LayoutError::WorkLimit { limit: LIMIT })
            ),
            "generated text escaped the job budget"
        );
        let output = layout_with_work_limit(&margins, &resolver, MAX_LAYOUT_WORK).unwrap();
        assert_eq!(output.pages.len(), PAGES);
        for (page, lines) in output.pages.iter().enumerate() {
            let count = lines
                .iter()
                .flat_map(|line| line.text.split_whitespace())
                .count();
            assert_eq!(count, 256, "margin text lost on page {}", page + 1);
        }
    }
    /// The layout work `document` needs, overestimated by at most a `1 / PRECISION` fraction:
    /// layout charges the same units under every budget.
    fn required_work(document: &StyledDocument, resolver: &FileResolver) -> usize {
        const PRECISION: usize = 64;
        let fits = |limit| match layout_with_work_limit(document, resolver, limit) {
            Ok(_) => true,
            Err(LayoutError::WorkLimit { .. }) => false,
            Err(error) => panic!("layout failed with {error} instead of exhausting its budget"),
        };
        let (mut fails, mut fits_within) = (0, 1);
        while !fits(fits_within) {
            assert!(
                fits_within < MAX_LAYOUT_WORK,
                "the document must lay out within the layout budget"
            );
            fails = fits_within;
            fits_within *= 2;
        }
        while (fits_within - fails) * PRECISION > fits_within {
            let limit = fails + (fits_within - fails) / 2;
            if fits(limit) {
                fits_within = limit;
            } else {
                fails = limit;
            }
        }
        fits_within
    }

    #[test]
    fn footnote_parts_copy_only_the_lines_they_show() {
        const FOOTNOTES: usize = 96;
        let resolver = FileResolver::default();
        let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/oracle/fixtures")
            .into();
        // One inline footnote body, laid out once, continues across every page; each page's
        // part of it copies the lines it shows, not the whole body.
        let work = |count: usize| {
            let calls = (0..count)
                .map(|index| format!("w{index}<span class=fn>note {index}</span> "))
                .collect::<String>();
            let document = StyledDocument::parse(
                &format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:120pt 120pt;margin:10pt}}html,body{{margin:0;font:10pt/10pt Fixed}}.fn{{float:footnote;footnote-display:inline}}</style><p>{calls}</p>"),
                &base, &[], &resolver,
            )
            .unwrap();
            required_work(&document, &resolver)
        };
        let (single, doubled) = (work(FOOTNOTES), work(2 * FOOTNOTES));
        assert!(
            doubled < 3 * single,
            "doubling the footnotes doubles the pages and the body's lines, so copying each part \
             whole would quadruple the charged work: {FOOTNOTES} footnotes need {single} units, \
             {} need {doubled}",
            2 * FOOTNOTES
        );
    }

    /// Pages whose margins leave a content box of no height, so each fragmentainer has the
    /// 1px minimum that guarantees progress (CSS Break 3 §4).
    const NO_ROOM_PAGE: &str = "@page{size:200pt 100pt;margin:50pt 0}";

    /// The text of each page's lines.
    fn page_text(trace: &crate::layout::LayoutTrace) -> Vec<Vec<&str>> {
        trace
            .pages
            .iter()
            .map(|lines| lines.iter().map(|line| line.text.as_str()).collect())
            .collect()
    }

    #[test]
    fn row_lanes_start_fragmentainers_without_room_instead_of_yielding_them_again() {
        const LIMIT: usize = 65_536;
        let resolver = FileResolver::default();
        let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/oracle/fixtures")
            .into();
        // Each flex item lane breaks before its first line, which the body's margin pushes past
        // the 1px fragmentainer; a fragmentainer that holds nothing yet is not left, so the
        // lanes resume on it and start it with their lines.
        let document = StyledDocument::parse(
            &format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}{NO_ROOM_PAGE}body{{margin:10pt 0 0;font:10pt/10pt Fixed}}</style><div style=\"display:flex\"><div>a1<br>a2<br>a3</div><div>b1<br>b2</div></div>"),
            &base, &[], &resolver,
        )
        .unwrap();
        let output = layout_with_work_limit(&document, &resolver, LIMIT).unwrap_or_else(|error| {
            panic!(
                "lanes yielding a fragmentainer that holds no content never progress, so they \
                 exhaust any budget: {error}"
            )
        });
        let pages = page_text(&output);
        let lines: Vec<_> = pages.iter().flatten().copied().collect();
        for lane in [["a1", "a2", "a3"].as_slice(), &["b1", "b2"]] {
            let placed: Vec<_> = lines
                .iter()
                .copied()
                .filter(|text| lane.contains(text))
                .collect();
            assert_eq!(
                placed, lane,
                "each lane places its lines once, in order: {pages:?}"
            );
        }
    }

    #[test]
    fn grid_lanes_in_a_shrink_to_fit_float_of_a_thousand_columns_progress() {
        let resolver = FileResolver::default();
        let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/oracle/fixtures")
            .into();
        // The columns are narrower than any word, and the grid's row lanes break before the
        // words each fragmentainer holds none of yet.
        let document = StyledDocument::parse(
            "<!doctype html><style>@font-face{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}body{font:10pt/10pt Fixed}</style><div style=\"float:left\">words <div style=\"column-count:1000\">column text <div style=\"display:grid\">grid text</div></div></div>",
            &base, &[], &resolver,
        )
        .unwrap();
        const LIMIT: usize = 65_536;
        let output = layout_with_work_limit(&document, &resolver, LIMIT).unwrap_or_else(|error| {
            panic!(
                "lanes yielding columns that hold no content never progress, so they exhaust \
                 any budget: {error}"
            )
        });
        let pages = page_text(&output);
        let mut words: Vec<_> = pages
            .iter()
            .flatten()
            .flat_map(|line| line.split_whitespace())
            .collect();
        words.sort_unstable();
        assert_eq!(
            words,
            ["column", "grid", "text", "text", "words"],
            "every word is placed once: {pages:?}"
        );
    }

    #[test]
    fn floats_across_fragmentainers_measure_their_content_once_per_containing_block() {
        const LINES: usize = 48;
        let resolver = FileResolver::default();
        let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/oracle/fixtures")
            .into();
        // A shrink-to-fit float one line per page tall resolves its width on each page; pages
        // of one containing block reuse the width, so the content is not measured per page.
        let work = |lines: usize| {
            let content = (0..lines)
                .map(|index| format!("<div>line {index}</div>"))
                .collect::<String>();
            let document = StyledDocument::parse(
                &format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:200pt 10pt;margin:0}}html,body{{margin:0;font:10pt/10pt Fixed}}</style><div style=\"float:left\">{content}</div>"),
                &base, &[], &resolver,
            )
            .unwrap();
            required_work(&document, &resolver)
        };
        let (single, doubled) = (work(LINES), work(2 * LINES));
        assert!(
            doubled < 3 * single,
            "doubling the lines doubles the pages and the content, so measuring the content on \
             each page would quadruple the charged work: {LINES} lines need {single} units, {} \
             need {doubled}",
            2 * LINES
        );
    }

    #[test]
    fn table_rows_progress_past_repeated_edges_that_fill_their_fragmentainers() {
        const LIMIT: usize = 65_536;
        let resolver = FileResolver::default();
        let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/oracle/fixtures")
            .into();
        // The cells' padding and the space before the rows exceed the 1px fragmentainer, which
        // still takes 1px of the rows' content.
        let document = StyledDocument::parse(
            &format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}{NO_ROOM_PAGE}body{{font:10pt/10pt Fixed}}td{{padding:10pt}}</style><table><tr><td>r1a</td><td>r1b</td></tr><tr><td>r2a</td><td>r2b</td></tr></table><p>after</p>"),
            &base, &[], &resolver,
        )
        .unwrap();
        let pass = crate::layout::layout_pass(&document, &resolver, Budget::new(LIMIT))
            .unwrap_or_else(|error| panic!("rows on fragmentainers without room failed: {error}"));
        assert_eq!(
            pass.diagnostics,
            [],
            "the rows progress, so no content is omitted at the page limit"
        );
        let pages = page_text(&pass.trace);
        let mut lines: Vec<_> = pages.iter().flatten().copied().collect();
        lines.sort_unstable();
        assert_eq!(
            lines,
            ["after", "r1a", "r1b", "r2a", "r2b"],
            "every cell and the paragraph after the table are placed once: {pages:?}"
        );
    }

    #[test]
    fn fixed_columns_without_room_for_cloned_edges_take_1px_of_content_each() {
        const LIMIT: usize = 4096;
        const CONTENT_HEIGHT: f32 = 100.0;
        let resolver = FileResolver::default();
        // The columns are as tall as the box's cloned padding, so each takes the 1px of its
        // content that guarantees progress (CSS Break 3 §4.4) and the overflow columns
        // continue in the inline direction (CSS Multi-column Layout 1 §8.2).
        let document = StyledDocument::parse(
            &format!("<!doctype html><style>@page{{size:200pt 200pt;margin:10pt}}html,body{{margin:0}}section{{column-count:2;column-gap:10pt;column-fill:auto;height:10pt}}div{{height:{CONTENT_HEIGHT}pt;padding:10pt;box-decoration-break:clone;background:blue}}</style><section><div></div></section>"),
            &ResourceBase::default(), &[], &resolver,
        ).unwrap();
        let pass = crate::layout::layout_pass(&document, &resolver, Budget::new(LIMIT))
            .unwrap_or_else(|error| {
                panic!("fixed columns without room past cloned edges must still progress: {error}")
            });
        assert_eq!(pass.diagnostics, [], "no content is omitted");
        assert_eq!(
            pass.trace.pages.len(),
            1,
            "the columns overflow inline, on one page"
        );
        let blue: Vec<_> = pass.trace.display_lists[0]
            .iter()
            .filter_map(|item| match item {
                crate::graphics::DisplayItem::Box(paint)
                    if paint.decoration.background.rgb == [0, 0, 255] =>
                {
                    Some(paint)
                }
                _ => None,
            })
            .collect();
        let columns = (CONTENT_HEIGHT / crate::graphics::POINTS_PER_PIXEL).ceil() as usize;
        assert!(
            blue.len() >= columns,
            "each column takes at most 1px of the {CONTENT_HEIGHT}pt content, so it needs \
             {columns} columns, got {} fragments",
            blue.len()
        );
        assert!(
            blue.windows(2).all(|pair| pair[0].rect.x < pair[1].rect.x),
            "each fragment lies in the next overflow column: {:?}",
            blue.iter().map(|paint| paint.rect.x).collect::<Vec<_>>()
        );
    }

    #[test]
    fn paginating_a_table_takes_work_linear_in_its_rows() {
        const ROWS: usize = 96;
        let resolver = FileResolver::default();
        let base: ResourceBase = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/oracle/fixtures")
            .into();
        // Each page repeats the header and footer, and two of every three body rows share a
        // row-spanning cell. Resolving the table's column widths or row geometry, aligning all
        // its cells where row heights depend on each other, or searching a row's siblings for
        // the events after it, again for every row placed is quadratic in the rows.
        let work = |collapse: &str, css: &str, rows: usize| {
            let body = "<tr><td rowspan=2>span</td><td>first</td><td>x</td></tr><tr><td>second</td><td>y</td></tr><tr class=third><td>third</td><td>z</td><td>w</td></tr>"
                .repeat(rows / 6);
            let document = StyledDocument::parse(
                &format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:200pt 200pt;margin:10pt}}html,body{{margin:0;font:8pt/10pt Fixed}}table{{width:100%;border-collapse:{collapse}}}td,th{{border:1pt solid;padding:1pt}}{css}</style><table><thead><tr><th>head</th><th>a</th><th>b</th></tr></thead><tfoot><tr><td>foot</td><td>c</td><td>d</td></tr></tfoot><tbody>{body}</tbody><tbody>{body}</tbody></table>"),
                &base, &[], &resolver,
            )
            .unwrap();
            let budget = Budget::new(MAX_LAYOUT_WORK);
            let trace = crate::layout::layout_pass(&document, &resolver, budget.clone())
                .unwrap_or_else(|error| {
                    panic!("{collapse} table of {rows} rows with `{css}` failed: {error}")
                })
                .trace;
            let heads = trace
                .pages
                .iter()
                .filter(|page| page.iter().any(|line| line.text == "head"))
                .count();
            assert!(
                trace.pages.len() > 1 && heads == trace.pages.len(),
                "fixture: the {collapse} table of {rows} rows with `{css}` spans pages that \
                 each repeat its header, but {heads} of {} pages show it",
                trace.pages.len()
            );
            budget.spent()
        };
        for (collapse, css) in [
            ("separate", ""),
            ("collapse", ""),
            ("separate", "td{height:12pt}"),
            ("collapse", ".third{visibility:collapse}"),
        ] {
            crate::work::assert_linear(
                &format!("rows of a {collapse} table with `{css}`"),
                ROWS,
                |rows| work(collapse, css, rows),
            );
        }
    }

    /// `body` on small pages, which it must span.
    fn paged_document(body: &str, resolver: &FileResolver) -> StyledDocument {
        let base: ResourceBase = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/oracle/fixtures")
            .into();
        StyledDocument::parse(
            &format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:200pt 200pt;margin:10pt}}html,body{{margin:0;font:8pt/10pt Fixed}}</style>{body}"),
            &base, &[], resolver,
        )
        .unwrap()
    }

    /// Lays out `document`, made by [`paged_document`], under `budget`; `what` names it.
    fn paged_pass(
        what: &str,
        document: &StyledDocument,
        resolver: &FileResolver,
        budget: Budget,
    ) -> crate::layout::LayoutPass {
        let pass = crate::layout::layout_pass(document, resolver, budget)
            .unwrap_or_else(|error| panic!("{what} failed: {error}"));
        assert!(
            pass.trace.pages.len() > 1,
            "fixture: {what} spans pages, but lays out on {} page",
            pass.trace.pages.len()
        );
        pass
    }

    /// The units of `work` that laying out `body` does on small pages, which it must span.
    fn paged_work(what: &str, body: &str, work: crate::work::Work) -> usize {
        let resolver = FileResolver::default();
        let document = paged_document(body, &resolver);
        let (_, units) = crate::work::measured(work, || {
            paged_pass(what, &document, &resolver, Budget::new(MAX_LAYOUT_WORK))
        });
        units
    }

    #[test]
    fn rows_of_a_row_spanning_band_take_work_linear_in_its_rows() {
        const ROWS: usize = 240;
        // One cell spans every row, joining them into one band across pages. Walking from the
        // band's start to each row, each cell's end or each collapsed cell is quadratic in the
        // band's rows.
        type Collapsed = fn(usize) -> bool;
        let cases: [(&str, Collapsed); 2] = [
            ("every row kept", |_| false),
            ("two of every three rows collapsed", |row| row % 3 != 0),
        ];
        for (rows_kept, gone) in cases {
            crate::work::assert_linear(
                &format!(
                    "fragmentainers visited to place the rows of a row-spanning band, {rows_kept}"
                ),
                ROWS,
                |rows| {
                    let body: String = (1..rows)
                        .map(|row| {
                            let class = if gone(row) { " class=gone" } else { "" };
                            format!("<tr{class}><td>r{row}</td></tr>")
                        })
                        .collect();
                    paged_work(
                        &format!("a band of {rows} rows, {rows_kept}"),
                        &format!(
                            "<style>td{{border:1pt solid}}.gone{{visibility:collapse}}</style><table><tr><td rowspan={rows}>span</td><td>r0</td></tr>{body}</table>"
                        ),
                        crate::work::Work::BandPage,
                    )
                },
            );
        }
    }

    #[test]
    fn laying_out_flex_items_takes_work_linear_in_their_count() {
        const ITEMS: usize = 240;
        // Searching the container's children for the semantic events after each item it
        // places, collapsed or not, is quadratic in the items.
        for (css, collapse) in [
            ("flex-wrap:wrap", ""),
            ("flex-direction:column", ""),
            (
                "flex-wrap:wrap",
                ".tags span:nth-child(3n){visibility:collapse}",
            ),
            ("flex-direction:column;flex-wrap:wrap;height:400pt", ""),
        ] {
            let what = format!("flex items of a container with `{css}` and `{collapse}`");
            crate::work::assert_linear(&what, ITEMS, |items| {
                let tags: String = (0..items)
                    .map(|index| format!("<span>tag {index}</span>"))
                    .collect();
                paged_work(
                    &format!("{what} holding {items} items"),
                    &format!(
                        "<style>.tags{{display:flex;gap:2pt;{css}}}.tags span{{border:1pt solid;padding:1pt}}{collapse}</style><div class=tags>{tags}</div>"
                    ),
                    crate::work::Work::SiblingStep,
                )
            });
        }
    }

    #[test]
    fn laying_out_grid_items_takes_work_linear_in_their_count() {
        const ITEMS: usize = 240;
        // Searching the container's children for the semantic events after each item, or
        // every item for those spanning each auto row, is quadratic in the items.
        for (steps, work) in [
            ("sibling", crate::work::Work::SiblingStep),
            ("single-span", crate::work::Work::SingleSpanStep),
        ] {
            let what = format!("{steps} steps for the items of a four-column grid");
            crate::work::assert_linear(&what, ITEMS, |items| {
                let cards: String = (0..items)
                    .map(|index| format!("<div>card {index}</div>"))
                    .collect();
                paged_work(
                    &format!("{what} holding {items} items"),
                    &format!(
                        "<style>.grid{{display:grid;grid-template-columns:repeat(4,auto);gap:2pt}}.grid div{{border:1pt solid}}</style><div class=grid>{cards}</div>"
                    ),
                    work,
                )
            });
        }
    }

    #[test]
    fn paginating_a_shrink_to_fit_grid_takes_work_linear_in_its_items() {
        const ITEMS: usize = 240;
        // Measuring every item for the grid's width again for each item placed, or charging
        // every row for every item when sizing the rows, is quadratic in the items.
        for css in ["width:fit-content", "width:max-content", "float:left"] {
            let what = format!("layout budget for the items of a four-column grid with `{css}`");
            crate::work::assert_linear(&what, ITEMS, |items| {
                let cards: String = (0..items)
                    .map(|index| format!("<div>card {index}</div>"))
                    .collect();
                let resolver = FileResolver::default();
                let document = paged_document(
                    &format!(
                        "<style>.grid{{display:grid;grid-template-columns:repeat(4,1fr);gap:2pt;{css}}}.grid div{{border:1pt solid}}</style><div class=grid>{cards}</div>"
                    ),
                    &resolver,
                );
                let budget = Budget::new(MAX_LAYOUT_WORK);
                let pass = paged_pass(
                    &format!("{what} holding {items} items"),
                    &document,
                    &resolver,
                    budget.clone(),
                );
                let last = (items - 1).to_string();
                let pages = page_text(&pass.trace);
                assert!(
                    pages
                        .last()
                        .is_some_and(|lines| lines.iter().any(|line| line.ends_with(&last))),
                    "{what}: the last page of {items} items shows card {last}: {:?}",
                    pages.last()
                );
                budget.spent()
            });
        }
    }

    #[test]
    fn measuring_nested_flex_and_grid_items_takes_work_linear_in_their_nesting_and_count() {
        const DEPTH: usize = 8;
        const ITEMS: usize = 4;
        const LEVELS: [&str; 3] = [
            "display:flex;gap:2pt",
            "display:grid;grid-template-columns:auto 1fr",
            "display:flex;flex-direction:column",
        ];
        // Each container measures its items for their sizes and again to place them, at the
        // sizes its own measurements give it, and needs the content widths of their contents
        // for both. Measuring them anew at each level is exponential in the nesting, and
        // measuring their contents' widths anew is quadratic in it.
        let work = |depth: usize, items: usize, kind: crate::work::Work| {
            let mut nested = "<span>innermost</span>".to_owned();
            for level in 0..depth {
                let siblings = |side: &str| -> String {
                    (0..items / 2)
                        .map(|item| format!("<span>{side}{level}.{item}</span>"))
                        .collect()
                };
                nested = format!(
                    "<div style='{}'>{}{nested}{}</div>",
                    LEVELS[level % LEVELS.len()],
                    siblings("before"),
                    siblings("after")
                );
            }
            let resolver = FileResolver::default();
            let base: ResourceBase = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("tests/oracle/fixtures")
                .into();
            let document = StyledDocument::parse(
                &format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}body{{font:8pt Fixed}}</style>{nested}"),
                &base, &[], &resolver,
            )
            .unwrap();
            let (pass, units) = crate::work::measured(kind, || {
                crate::layout::layout_pass(&document, &resolver, Budget::new(MAX_LAYOUT_WORK))
                    .unwrap_or_else(|error| {
                        panic!("{depth} levels of {items} items failed: {error}")
                    })
            });
            let text = page_text(&pass.trace).concat().concat();
            assert!(
                text.contains("innermost") && text.contains(&format!("after{}.0", depth - 1)),
                "fixture: {depth} levels of {items} items lay out every level: {text}"
            );
            units
        };
        for (what, kind) in [
            ("item measurements", crate::work::Work::ItemMeasurement),
            (
                "content width computations",
                crate::work::Work::ContentSizes,
            ),
        ] {
            crate::work::assert_linear(
                &format!("{what} for flex and grid containers nested in each other"),
                DEPTH,
                |depth| work(depth, ITEMS, kind),
            );
            crate::work::assert_linear(
                &format!("{what} for {DEPTH} levels of flex and grid containers"),
                ITEMS,
                |items| work(DEPTH, items, kind),
            );
        }
    }

    #[test]
    fn multicolumn_layout_takes_work_linear_in_its_content() {
        // Multiples of the one-line paragraphs a page of two (8) or three (12) columns holds,
        // so that the last row, which balancing lays out repeatedly, is alike at both sizes.
        const TWO_COLUMN_PARAGRAPHS: usize = 144;
        const THREE_COLUMN_PARAGRAPHS: usize = 96;
        const BANNER_AFTER: usize = 8;
        let resolver = FileResolver::default();
        let base: ResourceBase = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/oracle/fixtures")
            .into();
        // Each row of columns is laid out from a copy of the layout before it, which balancing
        // keeps should the content end in the row. Copying the flow left, or the rows already
        // laid out, for every row is quadratic in the content.
        let work = |css: &str, banner: bool, wrapper: bool, paragraphs: usize| {
            let mut content = (0..paragraphs)
                .map(|index| format!("<p>p{index:04} words</p>"))
                .collect::<Vec<_>>();
            if banner {
                content.insert(BANNER_AFTER, "<h2>Banner</h2>".to_owned());
            }
            let content = content.concat();
            let content = if wrapper {
                format!("<div>{content}</div>")
            } else {
                content
            };
            let document = StyledDocument::parse(
                &format!("<!doctype html><style>@font-face{{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}}@page{{size:200pt 40pt;margin:0}}html,body{{margin:0;font:10pt/10pt Fixed}}p{{margin:0}}h2{{column-span:all;margin:0;font-size:10pt}}{css}</style><section>{content}</section>"),
                &base, &[], &resolver,
            )
            .unwrap();
            let budget = Budget::new(MAX_LAYOUT_WORK);
            let trace = crate::layout::layout_pass(&document, &resolver, budget.clone())
                .unwrap_or_else(|error| {
                    panic!("{paragraphs} paragraphs in `{css}` failed: {error}")
                })
                .trace;
            let labels: Vec<_> = trace
                .pages
                .iter()
                .flatten()
                .flat_map(|line| line.text.split_whitespace())
                .filter(|word| word.starts_with('p') && word.len() == 5)
                .collect();
            let expected: Vec<_> = (0..paragraphs)
                .map(|index| format!("p{index:04}"))
                .collect();
            assert_eq!(
                labels, expected,
                "fixture: every paragraph in `{css}` is placed once, in order"
            );
            let offsets = trace
                .pages
                .last()
                .into_iter()
                .flatten()
                .map(|line| line.x.to_bits())
                .collect::<std::collections::BTreeSet<_>>()
                .len();
            assert!(
                trace.pages.len() > 2 && offsets > 1,
                "fixture: {paragraphs} paragraphs in `{css}` fill pages of columns, but they \
                 take {} pages and the last holds lines at {offsets} offsets",
                trace.pages.len()
            );
            budget.spent()
        };
        for (css, banner, wrapper, paragraphs) in [
            (
                "section{columns:2;column-gap:10pt}",
                false,
                false,
                TWO_COLUMN_PARAGRAPHS,
            ),
            (
                "section{columns:2;column-gap:10pt}",
                false,
                true,
                TWO_COLUMN_PARAGRAPHS,
            ),
            (
                "section{columns:3;column-gap:6pt}",
                false,
                false,
                THREE_COLUMN_PARAGRAPHS,
            ),
            (
                "section{columns:2;column-gap:10pt}",
                true,
                false,
                TWO_COLUMN_PARAGRAPHS,
            ),
            (
                "section{columns:2;column-gap:10pt;column-fill:auto;padding-bottom:20pt;border-bottom:1pt solid}",
                false,
                false,
                TWO_COLUMN_PARAGRAPHS,
            ),
        ] {
            crate::work::assert_linear(
                &format!(
                    "columns `{css}`{}{}",
                    if banner {
                        " after a spanning banner"
                    } else {
                        ""
                    },
                    if wrapper { " in one wrapper" } else { "" }
                ),
                paragraphs,
                |paragraphs| work(css, banner, wrapper, paragraphs),
            );
        }
    }
}