nsh-core 0.7.2

Platform-independent core: shadow tree, styles, layout and mount instructions.
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
use std::{io::Write, path::PathBuf, time::Instant};

use super::*;

const ICON: &[u8] = include_bytes!("testdata/icon.svg");
const LOGO: &[u8] = include_bytes!("testdata/logo.svg");
const HALF_ALPHA: &[u8] = include_bytes!("testdata/half-alpha.svg");
const TEXT: &[u8] = include_bytes!("testdata/text.svg");

/// A red square that fills its 10 × 10 viewport.
const RED: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="10" height="10" fill="#f00"/></svg>"##;

fn pt(width: f32, height: f32) -> Size<Points> {
    Size::new(Points(width), Points(height))
}

fn pixel(raster: &Raster, x: u32, y: u32) -> [u8; 4] {
    let i = ((y * raster.width + x) * 4) as usize;
    raster.pixels[i..i + 4].try_into().unwrap()
}

fn transparent(raster: &Raster) -> bool {
    raster.pixels.iter().all(|&b| b == 0)
}

fn svg(attrs: &str) -> Vec<u8> {
    format!(r#"<svg xmlns="http://www.w3.org/2000/svg" {attrs}><rect width="1" height="1"/></svg>"#)
        .into_bytes()
}

fn gzip(bytes: &[u8]) -> Vec<u8> {
    let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
    encoder.write_all(bytes).unwrap();
    encoder.finish().unwrap()
}

/// A directory of its own for one test's files.
fn scratch(test: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("nsh-svg-{}-{test}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

#[test]
fn svg_raster_sniffs_bytes_not_names() {
    assert!(sniff(ICON));
    assert!(
        sniff(LOGO),
        "XML declaration, comment and doctype before <svg"
    );
    assert!(sniff(b"\xEF\xBB\xBF  \n<svg/>"));
    assert!(sniff(b"<!DOCTYPE svg [ <!ENTITY a \"b>\"> ]><svg>"));
    assert!(sniff(&gzip(ICON)), ".svgz");
    assert!(!sniff(b"\x89PNG\r\n\x1a\n"));
    assert!(!sniff(b"\xFF\xD8\xFF\xE0"));
    assert!(!sniff(b"<html><svg></svg></html>"));
    assert!(!sniff(b"<svgx>"));
    assert!(!sniff(b"<?xml version=\"1.0\""));
    assert!(!sniff(b""));
    assert!(!sniff(&gzip(b"not an svg")));
}

#[test]
fn svg_raster_size_from_width_height_and_view_box() {
    assert_eq!(size(ICON).unwrap(), pt(24.0, 24.0), "viewBox only");
    assert_eq!(
        size(LOGO).unwrap(),
        pt(48.0, 24.0),
        "width/height win over the viewBox"
    );
    assert_eq!(
        size(&svg(r#"width="30" height="20""#)).unwrap(),
        pt(30.0, 20.0)
    );
    assert_eq!(
        size(&svg(r#"width="10.5" height="10""#)).unwrap(),
        pt(10.5, 10.0),
        "fractions kept"
    );
    assert_eq!(
        size(&svg(r#"width="30px" height="1in""#)).unwrap(),
        pt(30.0, 96.0),
        "CSS units"
    );
    // One side alone takes the other from the viewBox's aspect ratio.
    assert_eq!(
        size(&svg(r#"width="16" viewBox="0 0 32 64""#)).unwrap(),
        pt(16.0, 32.0)
    );
    assert_eq!(
        size(&svg(r#"height="10" viewBox="0 0 32 64""#)).unwrap(),
        pt(5.0, 10.0)
    );
    assert_eq!(
        size(&svg(r#"width="0.25in" viewBox="0,0,1,2""#)).unwrap(),
        pt(24.0, 48.0)
    );
    assert_eq!(
        size(&svg(r#"height="1e1px" viewBox="0 0 2 1""#)).unwrap(),
        pt(20.0, 10.0)
    );
    // A relative unit, which usvg resolves (12 points a font size).
    assert_eq!(
        size(&svg(r#"width="2em" viewBox="0 0 32 64""#)).unwrap(),
        pt(24.0, 48.0)
    );
    let doc = br##"<svg xmlns="http://www.w3.org/2000/svg" width="16" viewBox="0 0 32 64"><rect width="32" height="64" fill="#f00"/></svg>"##;
    let one_side = rasterize(doc, 32).unwrap();
    assert_eq!((one_side.width, one_side.height), (16, 32));
    assert_eq!(
        pixel(&one_side, 0, 0),
        [255, 0, 0, 255],
        "the drawing fills the box"
    );
    assert_eq!(pixel(&one_side, 15, 31), [255, 0, 0, 255]);
}

#[test]
fn svg_raster_one_side_in_absolute_units() {
    fn side(value: &str) -> OneSide<'_> {
        OneSide {
            width: true,
            value,
            view_box: (1.0, 1.0),
            at: 0,
        }
    }
    assert_eq!(side("16").points(), Some(16.0));
    assert_eq!(side(" 30px ").points(), Some(30.0));
    assert_eq!(side("0.5in").points(), Some(48.0));
    assert_eq!(side("12pt").points(), Some(16.0));
    assert_eq!(side("1pc").points(), Some(16.0));
    assert_eq!(side("2em").points(), None);
    assert_eq!(side("3ex").points(), None);
    assert_eq!(side("inf").points(), None);
    assert_eq!(side("px").points(), None);
    assert_eq!(side(&"9".repeat(64)).points(), None);
}

#[test]
fn svg_raster_size_percentages() {
    assert_eq!(
        size(&svg(r#"width="50%" height="100%" viewBox="0 0 24 12""#)).unwrap(),
        pt(12.0, 12.0)
    );
    assert_eq!(
        size(&svg(r#"width="100%" height="25%" viewBox="0 0 8 8""#)).unwrap(),
        pt(8.0, 2.0)
    );
    // Without a viewBox, percentages and a missing size fall back to the
    // extent of what the SVG draws, from its origin.
    let drawing = |attrs: &str| {
        format!(r#"<svg xmlns="http://www.w3.org/2000/svg" {attrs}><rect x="2" y="3" width="20" height="10"/></svg>"#)
            .into_bytes()
    };
    assert_eq!(
        size(&drawing(r#"width="100%" height="100%""#)).unwrap(),
        pt(22.0, 13.0)
    );
    assert_eq!(size(&drawing("")).unwrap(), pt(22.0, 13.0));
}

#[test]
fn svg_raster_reported_size_is_whole_points() {
    let reported = |w, h| {
        let s = reported_size(pt(w, h));
        (s.width.0, s.height.0)
    };
    assert_eq!(reported(24.0, 24.0), (24, 24));
    assert_eq!(reported(10.5, 10.4), (11, 10));
    assert_eq!(reported(0.2, 3.0), (1, 3), "at least a point");
    assert_eq!(reported(1e30, 2.0), (i32::MAX, 2), "never wraps");
}

#[test]
fn svg_raster_dimensions_fit_the_longest_side() {
    let logo = rasterize(LOGO, 96).unwrap();
    assert_eq!(
        (logo.width, logo.height, logo.size),
        (96, 48, pt(48.0, 24.0))
    );
    assert_eq!(logo.pixels.len(), 96 * 48 * 4);
    let small = rasterize(LOGO, 10).unwrap();
    assert_eq!((small.width, small.height), (10, 5));
    let icon = rasterize(ICON, 54).unwrap();
    assert_eq!((icon.width, icon.height), (54, 54));
    let tall = rasterize(&svg(r#"viewBox="0 0 1 100""#), 50).unwrap();
    assert_eq!(
        (tall.width, tall.height),
        (1, 50),
        "never narrower than a pixel"
    );
    // Colours land where the SVG puts them.
    assert_eq!(pixel(&logo, 10, 10), [255, 0, 0, 255]);
    assert_eq!(pixel(&logo, 80, 40), [0, 0, 255, 255]);
}

#[test]
fn svg_raster_pixel_budget_clamps() {
    let fit = |w: f32, h: f32, longest: f32, max_side| {
        raster_size(usvg::Size::from_wh(w, h).unwrap(), longest, max_side).unwrap()
    };
    assert_eq!(fit(24.0, 24.0, 54.0, MAX_SIDE), (54, 54));
    // Square: the pixel budget decides before the side does.
    assert_eq!(fit(24.0, 24.0, u32::MAX as f32, MAX_SIDE), (4096, 4096));
    // 4:1 at the longest side fills the budget exactly.
    assert_eq!(fit(400.0, 100.0, 1e9, MAX_SIDE), (8192, 2048));
    // Wide: the side decides.
    assert_eq!(fit(100.0, 1.0, 1e9, MAX_SIDE), (8192, 82));
    assert_eq!(fit(1e30, 1.0, 1e9, MAX_SIDE), (8192, 1));
    assert_eq!(fit(24.0, 24.0, 1e9, MAX_OVERSAMPLED_SIDE), (2048, 2048));
    for (w, h) in [(3.0, 2.0), (1000.0, 999.0), (7.0, 13.0), (1e6, 3.0)] {
        let (width, height) = fit(w, h, f32::MAX, MAX_SIDE);
        assert!(
            u64::from(width) * u64::from(height) <= u64::from(MAX_PIXELS),
            "{w}×{h}: {width}×{height}"
        );
        assert!(width <= MAX_SIDE && height <= MAX_SIDE);
    }
    assert_eq!(
        raster_size(usvg::Size::from_wh(1.0, 1.0).unwrap(), 0.0, MAX_SIDE),
        Err(Error::NoPixels)
    );
    let capped = rasterize(&svg(r#"viewBox="0 0 100 1""#), u32::MAX).unwrap();
    assert_eq!((capped.width, capped.height), (MAX_SIDE, 82));
}

#[test]
fn svg_raster_covering() {
    // A 2:1 logo for a view 96 pixels on its longer side: 96 tall, so a
    // square view's `cover` (96 × 96 of it) shows it unscaled.
    let logo = rasterize_covering(LOGO, 96).unwrap();
    assert_eq!((logo.width, logo.height), (192, 96));
    let tall = rasterize_covering(&svg(r#"viewBox="0 0 10 40""#), 30).unwrap();
    assert_eq!((tall.width, tall.height), (30, 120));
    assert_eq!(
        rasterize_covering(ICON, 54).unwrap().width,
        54,
        "square: as rasterize"
    );
    let capped = rasterize_covering(&svg(r#"viewBox="0 0 100 1""#), 1000).unwrap();
    assert_eq!(capped.width, MAX_SIDE);
    assert_eq!(rasterize_covering(ICON, 0), Err(Error::NoPixels));
}

#[test]
fn svg_raster_scaled() {
    let logo = rasterize_scaled(LOGO, 2.0).unwrap();
    assert_eq!((logo.width, logo.height), (96, 48));
    let icon = rasterize_scaled(ICON, 2.625).unwrap();
    assert_eq!((icon.width, icon.height), (63, 63));
    assert_eq!(rasterize_scaled(ICON, 0.0), Err(Error::NoPixels));
    assert_eq!(rasterize_scaled(ICON, f32::NAN), Err(Error::NoPixels));
}

#[test]
fn svg_raster_oversampled() {
    let icon = rasterize_oversampled(ICON).unwrap();
    assert_eq!((icon.width, icon.height), (96, 96));
    let big = rasterize_oversampled(&svg(r#"width="1000" height="500""#)).unwrap();
    assert_eq!(
        (big.width, big.height),
        (MAX_OVERSAMPLED_SIDE, MAX_OVERSAMPLED_SIDE / 2)
    );
}

#[test]
fn svg_raster_premultiplied_alpha() {
    let raster = rasterize(HALF_ALPHA, 10).unwrap();
    let [r, g, b, a] = pixel(&raster, 5, 5);
    assert!((127..=128).contains(&a), "alpha {a}");
    assert_eq!((r, g, b), (a, 0, 0), "red is premultiplied by alpha");
}

#[test]
fn svg_raster_svgz() {
    let raster = rasterize(&gzip(LOGO), 96).unwrap();
    assert_eq!(raster, rasterize(LOGO, 96).unwrap());
    assert_eq!(size(&gzip(LOGO)).unwrap(), pt(48.0, 24.0));
}

#[test]
fn svg_raster_invalid_data_is_an_error() {
    for bytes in [
        &b""[..],
        b"not an svg",
        b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR",
        b"\xff\xfe<\0s\0v\0g\0",
        b"<svg xmlns=\"http://www.w3.org/2000/svg\"><rect",
        b"<html/>",
        &[0x1f, 0x8b, 0x08, 0x00, 0x01],
    ] {
        assert!(matches!(size(bytes), Err(Error::Invalid(_))), "{bytes:?}");
        assert!(
            matches!(rasterize(bytes, 24), Err(Error::Invalid(_))),
            "{bytes:?}"
        );
    }
    let flat = b"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"0\" height=\"10\"/>";
    assert_eq!(size(flat), Err(Error::NoArea));
    assert_eq!(rasterize(ICON, 0), Err(Error::NoPixels));
    for error in [
        rasterize(b"x", 1).unwrap_err(),
        Error::NoArea,
        Error::NoPixels,
        Error::TooLarge,
        Error::OverBudget { pixels: 1 },
        Error::TooManyNodes,
        Error::Panicked,
    ] {
        assert!(!error.to_string().is_empty());
    }
    assert!(
        Error::NoArea.to_string().starts_with("the SVG has no area"),
        "not an invalid SVG"
    );
}

/// `cargo test --release -p nsh-core --features svg bench_svg_icon -- --ignored --nocapture`
#[test]
#[ignore]
fn bench_svg_icon() {
    rasterize(ICON, 54).unwrap();
    let best = (0..20)
        .map(|_| {
            let start = Instant::now();
            rasterize(ICON, 54).unwrap();
            start.elapsed()
        })
        .min()
        .unwrap();
    eprintln!("24×24 icon at 54 px: {best:?}");
}

/// The SVG files the safety tests reference, holding a red square that would
/// show if the reference were followed.
fn sentinel(test: &str) -> PathBuf {
    let path = scratch(test).join("sentinel.svg");
    std::fs::write(&path, RED).unwrap();
    path
}

fn image_href(href: &str) -> Vec<u8> {
    format!(
        r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="10" height="10"><image width="10" height="10" href="{href}"/><image width="10" height="10" xlink:href="{href}"/></svg>"#
    )
    .into_bytes()
}

#[test]
fn svg_safety_file_hrefs_are_not_read() {
    let path = sentinel("file");
    let absolute = image_href(path.to_str().unwrap());
    // usvg's own options would read the file: the test would see a read.
    let tree = usvg::Tree::from_data(&absolute, &usvg::Options::default()).unwrap();
    let mut pixmap = tiny_skia::Pixmap::new(10, 10).unwrap();
    resvg::render(&tree, tiny_skia::Transform::default(), &mut pixmap.as_mut());
    assert_eq!(
        pixmap.pixel(5, 5).unwrap().alpha(),
        255,
        "the sentinel is readable"
    );

    assert!(
        transparent(&rasterize(&absolute, 10).unwrap()),
        "absolute path"
    );
    let file_url = image_href(&format!("file://{}", path.display()));
    assert!(transparent(&rasterize(&file_url, 10).unwrap()), "file URL");
    // A relative path resolves against nothing: there is no resources
    // directory, and the resolver ignores one even where it is set.
    let dir = path.parent().unwrap();
    let relative = image_href("sentinel.svg");
    let in_dir = |options: usvg::Options<'static>| {
        let options = usvg::Options {
            resources_dir: Some(dir.into()),
            ..options
        };
        parse_with(&relative, &options)
            .unwrap()
            .root()
            .has_children()
    };
    assert!(
        in_dir(usvg::Options::default()),
        "the sentinel is reachable relatively"
    );
    assert!(!in_dir(options(false)), "the resolver reads nothing");
    assert!(
        transparent(&rasterize(&relative, 10).unwrap()),
        "relative path"
    );
    let _ = std::fs::remove_dir_all(dir);
}

/// `bytes` as a percent-encoded `mime` data URI.
fn data_uri(mime: &str, bytes: &[u8]) -> String {
    use std::fmt::Write as _;
    let mut uri = format!("data:{mime},");
    for b in bytes {
        write!(uri, "%{b:02X}").unwrap();
    }
    uri
}

#[test]
fn svg_safety_remote_urls_and_nested_svgs_resolve_nothing() {
    // Files and URLs are never read: an image from either draws nothing.
    for href in [
        "http://127.0.0.1:9/a.svg".to_owned(),
        "https://127.0.0.1:9/a.svg".to_owned(),
    ] {
        let raster = rasterize(&image_href(&href), 10).unwrap();
        assert!(transparent(&raster), "{href}");
    }
    // An inline SVG is a document of its own: it would hide its tree and
    // images from the budget, so the resolver refuses it.
    let nested = data_uri("image/svg+xml", RED.as_bytes());
    assert!(transparent(&rasterize(&image_href(&nested), 10).unwrap()));
    // Only the declared MIME counts; SVG bytes declared as text do not.
    let text = data_uri("text/plain", RED.as_bytes());
    assert!(transparent(&rasterize(&image_href(&text), 10).unwrap()));
    // An inline raster image is part of the document (a canvas snapshot's
    // own images are self-contained) and draws.
    let mut pixmap = tiny_skia::Pixmap::new(2, 2).unwrap();
    pixmap.fill(tiny_skia::Color::from_rgba8(255, 0, 0, 255));
    let png = data_uri("image/png", &pixmap.encode_png().unwrap());
    assert!(
        !transparent(&rasterize(&image_href(&png), 10).unwrap()),
        "an inline raster image draws"
    );
}

#[test]
fn svg_safety_inline_raster_area_is_budgeted() {
    // Only the header is needed: the estimate reads the dimensions before
    // resvg decodes, so a small document cannot decode 400 megapixels.
    let mut huge = b"\x89PNG\r\n\x1a\n".to_vec();
    huge.extend_from_slice(&13u32.to_be_bytes());
    huge.extend_from_slice(b"IHDR");
    huge.extend_from_slice(&20_000u32.to_be_bytes());
    huge.extend_from_slice(&20_000u32.to_be_bytes());
    huge.extend_from_slice(&[8, 6, 0, 0, 0]);
    huge.extend_from_slice(&0u32.to_be_bytes());
    let doc = image_href(&data_uri("image/png", &huge));
    assert!(doc.len() < 1000, "{} bytes", doc.len());
    assert!(matches!(rasterize(&doc, 10), Err(Error::OverBudget { .. })));
}

#[test]
fn svg_safety_gif_area_uses_the_frame_not_the_screen() {
    // resvg decodes a GIF's first frame at its Image Descriptor size, which
    // can be larger than the 1x1 logical screen imagesize reports.
    let mut bytes = Vec::new();
    {
        let mut encoder = gif::Encoder::new(&mut bytes, 1, 1, &[0, 0, 0, 255, 0, 0]).unwrap();
        let frame = gif::Frame {
            width: 1000,
            height: 1000,
            buffer: std::borrow::Cow::Owned(vec![0; 1000 * 1000]),
            ..Default::default()
        };
        encoder.write_frame(&frame).unwrap();
    }
    let doc = image_href(&data_uri("image/gif", &bytes));
    let tree = super::parse(&doc).unwrap();
    let pixels = super::layers::peak(&tree, tiny_skia::Transform::identity(), (10, 10)).unwrap();
    // 1000x1000 at 9 bytes a pixel is 2.25M layer pixels.
    assert!(pixels >= 2_250_000.0, "{pixels}");
}

#[test]
fn svg_safety_external_use_resolves_nothing() {
    let path = sentinel("use");
    let doc = format!(
        r##"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><use href="{}#r"/><use href="sentinel.svg#r"/></svg>"##,
        path.display()
    );
    assert!(transparent(&rasterize(doc.as_bytes(), 10).unwrap()));
    let _ = std::fs::remove_dir_all(path.parent().unwrap());
}

#[test]
fn svg_safety_svgz_inflation_is_bounded() {
    // Spaces compress about a thousandfold: a small file, a huge document.
    let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best());
    encoder
        .write_all(b"<svg xmlns=\"http://www.w3.org/2000/svg\"><!--")
        .unwrap();
    let spaces = vec![b' '; 1 << 20];
    for _ in 0..(MAX_BYTES >> 20) + 1 {
        encoder.write_all(&spaces).unwrap();
    }
    encoder.write_all(b"--></svg>").unwrap();
    let bomb = encoder.finish().unwrap();
    assert!(bomb.len() < MAX_BYTES / 100, "{} bytes", bomb.len());
    assert_eq!(size(&bomb), Err(Error::TooLarge));
    assert_eq!(rasterize(&bomb, 24), Err(Error::TooLarge));
}

#[test]
fn svg_safety_documents_are_bounded() {
    let mut doc = br#"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"><!--"#.to_vec();
    doc.resize(MAX_BYTES - 9, b' ');
    doc.extend_from_slice(b"--></svg>");
    assert_eq!(size(&doc).unwrap(), pt(1.0, 1.0), "at the limit");
    doc.insert(doc.len() - 9, b' ');
    assert_eq!(size(&doc), Err(Error::TooLarge));
}

#[test]
fn svg_safety_nested_layers_are_refused() {
    // Each group with opacity is a layer as large as its content (at most
    // 5 × the raster each way), and nested ones coexist.
    let depth = 40;
    let bomb = format!(
        r#"<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512">{}<rect width="1e5" height="1e5"/>{}</svg>"#,
        r#"<g opacity=".9">"#.repeat(depth),
        "</g>".repeat(depth)
    );
    assert!(bomb.len() < 1000, "{} bytes", bomb.len());
    let start = Instant::now();
    assert!(matches!(
        rasterize(bomb.as_bytes(), 2048),
        Err(Error::OverBudget { .. })
    ));
    assert!(matches!(
        rasterize_oversampled(bomb.as_bytes()),
        Err(Error::OverBudget { .. })
    ));
    // At a small size the same document is cheap, and draws.
    rasterize(bomb.as_bytes(), 16).unwrap();
    // As deep, with content inside the canvas: each layer is the canvas.
    let canvas = bomb.replace("1e5", "512");
    let error = rasterize(canvas.as_bytes(), 2048).unwrap_err();
    assert!(matches!(error, Error::OverBudget { .. }), "{error}");
    rasterize(canvas.as_bytes(), 64).unwrap();
    log::info!("layer bombs refused in {:?}", start.elapsed());
}

#[test]
fn svg_safety_huge_filters_and_patterns_are_refused() {
    let doc = |defs: &str, body: &str| {
        format!(
            r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs>{defs}</defs>{body}</svg>"#
        )
    };
    let refused = |doc: String| {
        assert!(doc.len() < 1000, "{} bytes", doc.len());
        let error = rasterize(doc.as_bytes(), 100).unwrap_err();
        assert!(matches!(error, Error::OverBudget { .. }), "{error}: {doc}");
    };
    // A filter region is not clamped to the canvas, and every primitive's
    // result stays until the filter ends.
    refused(doc(
        r#"<filter id="f" filterUnits="userSpaceOnUse" x="-1e5" y="-1e5" width="2e5" height="2e5"><feFlood/><feFlood/></filter>"#,
        r#"<rect width="10" height="10" filter="url(#f)"/>"#,
    ));
    // A pattern's tile is not clamped either.
    refused(doc(
        r#"<pattern id="p" patternUnits="userSpaceOnUse" width="1e5" height="1e5"><rect width="1" height="1"/></pattern>"#,
        r#"<rect width="10" height="10" fill="url(#p)"/>"#,
    ));
    // A filter on a normal canvas draws.
    let blur = doc(
        r#"<filter id="b"><feGaussianBlur stdDeviation="1"/></filter>"#,
        r#"<rect width="10" height="10" filter="url(#b)"/>"#,
    );
    assert!(!transparent(&rasterize(blur.as_bytes(), 100).unwrap()));
}

#[test]
fn svg_safety_drawings_visiting_too_many_nodes_are_refused() {
    // Each pattern fills two squares with the next: drawing one square
    // draws 2^24 of the last.
    let patterns: String = (0..24)
        .map(|i| {
            let next = format!(r#"<rect width="1" height="1" fill="url(#p{})"/>"#, i + 1);
            format!(
                r#"<pattern id="p{i}" patternUnits="userSpaceOnUse" width="1" height="1">{next}{next}</pattern>"#
            )
        })
        .collect();
    let doc = format!(
        r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs>{patterns}<pattern id="p24" width="1" height="1"><rect width="1" height="1"/></pattern></defs><rect width="10" height="10" fill="url(#p0)"/></svg>"#
    );
    assert_eq!(rasterize(doc.as_bytes(), 10), Err(Error::TooManyNodes));
}

#[test]
fn svg_safety_text_length_is_bounded() {
    // usvg lays out every glyph while parsing, before the layer estimate:
    // a document with too much text is refused before that.
    let text = "a".repeat(super::MAX_TEXT_CHARS + 1);
    let doc = format!(
        r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><text x="0" y="9">{text}</text></svg>"#
    );
    assert_eq!(rasterize(doc.as_bytes(), 10), Err(Error::TooMuchText));
    assert_eq!(size(doc.as_bytes()), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_text_use_is_bounded() {
    // Each <use> copies the tree's 1000 characters, so counting only the
    // source <text> would let 100 uses lay out 100 000.
    let text = "a".repeat(1000);
    let uses = r##"<use href="#t"/>"##.repeat(100);
    let doc = format!(
        r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><text id="t">{text}</text></defs>{uses}</svg>"#
    );
    assert_eq!(rasterize(doc.as_bytes(), 10), Err(Error::TooMuchText));
    assert_eq!(size(doc.as_bytes()), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_text_tref_is_bounded() {
    // <tref> may take the text of any element; each of the 70 references
    // lays out the 1000 characters of a <g> outside any <text>.
    let text = "b".repeat(1000);
    let refs = r##"<text x="0" y="9"><tref href="#d"/></text>"##.repeat(70);
    let doc = format!(
        r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><g id="d">{text}</g></defs>{refs}</svg>"#
    );
    assert_eq!(rasterize(doc.as_bytes(), 10), Err(Error::TooMuchText));
    assert_eq!(size(doc.as_bytes()), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_text_references_under_the_bound_still_parse() {
    // The same expansion, with a short target: a legitimate document stays
    // within the budget and parses.
    let uses = r##"<use href="#t"/>"##.repeat(3);
    let doc = format!(
        r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><text id="t">ok</text></defs>{uses}</svg>"#
    );
    assert!(size(doc.as_bytes()).is_ok());
}

#[test]
fn svg_safety_text_reference_fan_out_is_bounded() {
    // Ten uses of each of g1..g8, with no text: counting every path is 10^8
    // visits. The memo counts each target once, and the expanded node count
    // refuses the document before usvg expands it.
    let groups: String = (1..=8)
        .map(|i| {
            let uses = format!(r##"<use href="#g{}"/>"##, i - 1).repeat(10);
            format!(r#"<g id="g{i}">{uses}</g>"#)
        })
        .collect();
    let doc = format!(
        r##"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><rect id="g0" width="1" height="1"/>{groups}</defs><use href="#g8"/></svg>"##
    );
    let tree = xml(&doc).unwrap();
    assert_eq!(check_text(&tree), Err(Error::TooManyNodes));
    assert_eq!(size(doc.as_bytes()), Err(Error::TooManyNodes));
}

#[test]
fn svg_safety_text_reference_spelling_matches_usvg() {
    // usvg takes `xlink:href` before `href`, and its IRI parser ignores spaces
    // around the `#id`. The walk must resolve the same references, or 100 uses
    // of a 1000-character text lay out 100 000 characters uncounted.
    let text = "a".repeat(1000);
    let doc = |uses: &str| {
        format!(
            r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="10" height="10"><defs><text id="t">{text}</text><g id="e"/></defs>{uses}</svg>"##
        )
    };
    for uses in [
        r##"<use href=" #t"/>"##.repeat(100),
        r##"<use href="#t "/>"##.repeat(100),
        r##"<use href="#e" xlink:href="#t"/>"##.repeat(100),
    ] {
        assert_eq!(size(doc(&uses).as_bytes()), Err(Error::TooMuchText));
    }
}

#[test]
fn svg_safety_text_tref_does_not_stop_at_a_cycle() {
    // A `tref` reads the referenced element's text nodes without expanding
    // it, so the target being on the walk's stack is not a reason to count
    // nothing: each of the 100 uses lays out the 1000 characters under `A`.
    let text = "a".repeat(1000);
    let uses = r##"<use href="#A"/>"##.repeat(100);
    let doc = format!(
        r##"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><g id="A">{text}<text x="0" y="9"><tref href="#A"/></text></g></defs>{uses}</svg>"##
    );
    assert_eq!(size(doc.as_bytes()), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_text_in_clip_paths_is_bounded() {
    // An objectBoundingBox clip path is converted for every element that
    // references it, so 100 references lay out the text 100 times.
    let text = "a".repeat(1000);
    let rects = r#"<rect width="10" height="10" clip-path="url(#c)"/>"#.repeat(100);
    let doc = |units: &str| {
        format!(
            r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><clipPath id="c" clipPathUnits="{units}"><text x="0" y="9">{text}</text></clipPath></defs>{rects}</svg>"#
        )
    };
    assert_eq!(
        size(doc("objectBoundingBox").as_bytes()),
        Err(Error::TooMuchText)
    );
    // A userSpaceOnUse clip path is converted once, so the same text is under
    // the bound however many elements reference it.
    assert!(size(doc("userSpaceOnUse").as_bytes()).is_ok());
    // One clip path over the bound is refused even with a single reference.
    let big = "a".repeat(super::MAX_TEXT_CHARS + 1);
    let one = format!(
        r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><clipPath id="c"><text x="0" y="9">{big}</text></clipPath></defs><rect width="10" height="10" clip-path="url(#c)"/></svg>"#
    );
    assert_eq!(size(one.as_bytes()), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_text_in_markers_is_bounded() {
    // A middle marker is drawn at every vertex of the path; a 100-vertex
    // path lays out the marker's 1000 characters 100 times.
    let text = "a".repeat(1000);
    let path: String = (0..100).map(|i| format!("L{i} 0")).collect();
    let doc = format!(
        r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><marker id="m" markerWidth="1" markerHeight="1"><text x="0" y="9">{text}</text></marker></defs><path d="M0 0{path}" fill="none" stroke="black" marker-mid="url(#m)"/></svg>"#
    );
    assert_eq!(size(doc.as_bytes()), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_inherited_markers_are_bounded() {
    // Marker properties inherit: a `<g marker-mid>` draws the marker at every
    // vertex of every descendant path, not once for the group.
    let text = "a".repeat(1000);
    let paths: String = (0..100)
        .map(|i| format!(r#"<path d="M0 0L{i} 0L{i} {i}"/>"#))
        .collect();
    let doc = format!(
        r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><marker id="m" markerWidth="1" markerHeight="1"><text x="0" y="9">{text}</text></marker></defs><g marker-mid="url(#m)">{paths}</g></svg>"#
    );
    assert_eq!(size(doc.as_bytes()), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_linked_resources_are_bounded() {
    // A clip path can name another one; usvg converts the linked clip path,
    // including its text, so the walk follows that link too.
    let big = "a".repeat(super::MAX_TEXT_CHARS + 1);
    let doc = format!(
        r##"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><clipPath id="b"><text x="0" y="9">{big}</text></clipPath><clipPath id="a" clip-path="url(#b)"/></defs><rect width="10" height="10" clip-path="url(#a)"/></svg>"##
    );
    assert_eq!(size(doc.as_bytes()), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_text_in_masks_is_bounded() {
    // An objectBoundingBox mask (the default) is converted for every element
    // that references it.
    let text = "a".repeat(1000);
    let rects = r#"<rect width="10" height="10" mask="url(#m)"/>"#.repeat(100);
    let doc = format!(
        r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><mask id="m"><text x="0" y="9">{text}</text></mask></defs>{rects}</svg>"#
    );
    assert_eq!(size(doc.as_bytes()), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_filter_lists_are_bounded() {
    // A filter value is a list; both filters convert and lay out their
    // `feImage` text.
    let text = "a".repeat(40_000);
    let doc = format!(
        r##"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><filter id="a"><feImage href="#t"/></filter><filter id="b"><feImage href="#t"/></filter><text id="t" x="0" y="9">{text}</text></defs><rect width="10" height="10" filter="url(#a) url(#b)"/></svg>"##
    );
    assert_eq!(size(doc.as_bytes()), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_text_in_filters_is_bounded_per_reference() {
    // A filter's units default to objectBoundingBox, so usvg converts it for
    // every element that references it, laying out its `feImage` text each
    // time.
    let text = "a".repeat(1000);
    let rects = r#"<rect width="10" height="10" filter="url(#f)"/>"#.repeat(100);
    let doc = format!(
        r##"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><filter id="f"><feImage href="#t"/></filter><text id="t" x="0" y="9">{text}</text></defs>{rects}</svg>"##
    );
    assert_eq!(size(doc.as_bytes()), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_stylesheet_resources_follow_use_copies() {
    // A style rule applies to every copy a `<use>` makes, so a mask named
    // only by a class is laid out once per copy, not once per source element.
    let text = "a".repeat(1000);
    let uses = r##"<use href="#g"/>"##.repeat(100);
    let doc = format!(
        r##"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><style>.m{{mask:url(#m)}}</style><defs><mask id="m"><text x="0" y="9">{text}</text></mask><g id="g"><rect class="m" width="10" height="10"/></g></defs>{uses}</svg>"##
    );
    assert_eq!(size(doc.as_bytes()), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_text_in_patterns_is_bounded() {
    // A pattern is converted once, so a small text stays under the bound
    // however many elements fill with it; a pattern over the bound is refused
    // even with one reference.
    let small = "a".repeat(1000);
    let fills = r#"<rect width="10" height="10" fill="url(#p)"/>"#.repeat(100);
    let small_doc = format!(
        r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><pattern id="p" patternUnits="userSpaceOnUse" width="10" height="10"><text x="0" y="9">{small}</text></pattern></defs>{fills}</svg>"#
    );
    assert!(size(small_doc.as_bytes()).is_ok());
    let big = "a".repeat(super::MAX_TEXT_CHARS + 1);
    let big_doc = format!(
        r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><pattern id="p" patternUnits="userSpaceOnUse" width="10" height="10"><text x="0" y="9">{big}</text></pattern></defs><rect width="10" height="10" fill="url(#p)"/></svg>"#
    );
    assert_eq!(size(big_doc.as_bytes()), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_text_in_filters_is_bounded() {
    // `feImage` can reference an element and draw it, including its text.
    let big = "a".repeat(super::MAX_TEXT_CHARS + 1);
    let doc = format!(
        r##"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><filter id="f"><feImage href="#t"/></filter><text id="t" x="0" y="9">{big}</text></defs><rect width="10" height="10" filter="url(#f)"/></svg>"##
    );
    assert_eq!(size(doc.as_bytes()), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_text_only_in_a_clip_path_asks_for_fonts() {
    // usvg lays out this text, so the walk must report it and the parse must
    // load the font database; otherwise the clip path comes out empty.
    let doc = r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><clipPath id="c"><text x="0" y="9">SALE</text></clipPath></defs><rect width="10" height="10" clip-path="url(#c)"/></svg>"#;
    let tree = xml(doc).unwrap();
    assert_eq!(check_text(&tree), Ok(true));
}

#[test]
fn svg_safety_resource_chains_do_not_overflow_the_stack() {
    // Resources can link to each other, and usvg converts the linked one.
    // The chain is flat XML, so only a depth carried through the resource
    // walk stops it.
    let chain: String = (1..5_000)
        .map(|i| format!(r##"<clipPath id="c{i}" clip-path="url(#c{})"/>"##, i - 1))
        .collect();
    let doc = format!(
        r##"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><clipPath id="c0"><text x="0" y="9">SALE</text></clipPath>{chain}</defs><rect width="10" height="10" clip-path="url(#c4999)"/></svg>"##
    );
    assert_eq!(size(doc.as_bytes()), Err(Error::TooManyNodes));
}

#[test]
fn svg_safety_use_chains_do_not_overflow_the_stack() {
    // usvg refuses a chain deeper than 1024 elements; the walk must stop at
    // the same depth instead of recursing through all 50 000 links.
    let chain: String = (1..50_000)
        .map(|i| format!(r##"<g id="g{i}"><use href="#g{}"/></g>"##, i - 1))
        .collect();
    let doc = format!(
        r##"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><rect id="g0" width="1" height="1"/>{chain}</defs><use href="#g49999"/></svg>"##
    );
    assert!(doc.len() < super::MAX_BYTES);
    assert_eq!(size(doc.as_bytes()), Err(Error::TooManyNodes));
}

#[test]
fn svg_safety_whitespace_is_not_a_visited_node() {
    // usvg builds no node for a whitespace text node. Counting them makes a
    // document of 500 001 paths fail a bound usvg itself accepts.
    let paths = "<path/>\n".repeat(500_001);
    let doc =
        format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10">{paths}</svg>"#);
    let tree = xml(&doc).unwrap();
    assert_eq!(check_text(&tree), Ok(false));
}

const OPEN: &str = r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="10" height="10">"#;

fn obb_clip(text: &str) -> String {
    format!(
        r#"<clipPath id="c" clipPathUnits="objectBoundingBox"><text x="0" y="0.9">{text}</text></clipPath>"#
    )
}

fn check(doc: &str) -> Result<bool, Error> {
    check_text(&xml(doc).unwrap())
}

#[test]
fn svg_safety_duplicate_resource_ids_use_the_last() {
    // usvg's link table keeps the last element with an id for resource
    // links; the walk's `<use>` table keeps the first and must not be used
    // for a clip-path reference.
    let text = "a".repeat(1000);
    let rects = r#"<rect width="5" height="5" clip-path="url(#c)"/>"#.repeat(100);
    let doc = format!(
        r#"{OPEN}<defs><clipPath id="c"/>{}</defs>{rects}<text x="0" y="9">a</text></svg>"#,
        obb_clip(&text)
    );
    assert_eq!(check(&doc), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_duplicate_feimage_targets_use_the_last() {
    let text = "a".repeat(70_000);
    let doc = format!(
        r##"{OPEN}<defs><g id="t"/><filter id="f" filterUnits="userSpaceOnUse"><feImage href="#t"/></filter><text id="t" x="0" y="9">{text}</text></defs><rect width="10" height="10" filter="url(#f)"/><text x="0" y="9">a</text></svg>"##
    );
    assert_eq!(check(&doc), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_inline_style_parses_like_usvg() {
    // simplecss skips a comment before a name and drops a leading `*`; the
    // walk must use the same tokenizer.
    let text = "a".repeat(1000);
    for style in ["/**/clip-path:url(#c)", "*clip-path:url(#c)"] {
        let rects = format!(r#"<rect width="5" height="5" style="{style}"/>"#).repeat(100);
        let doc = format!(
            r#"{OPEN}<defs>{}</defs>{rects}<text x="0" y="9">a</text></svg>"#,
            obb_clip(&text)
        );
        assert_eq!(check(&doc), Err(Error::TooMuchText), "{style}");
    }
}

#[test]
fn svg_safety_inline_marker_shorthand_is_bounded() {
    // `marker: url(#m)` sets the three marker properties.
    let text = "a".repeat(1000);
    let path: String = (0..100).map(|i| format!("L{i} 0")).collect();
    let doc = format!(
        r#"{OPEN}<defs><marker id="m" markerWidth="1" markerHeight="1"><text x="0" y="9">{text}</text></marker></defs><path d="M0 0{path}" fill="none" stroke="black" style="marker:url(#m)"/><text x="0" y="9">a</text></svg>"#
    );
    assert_eq!(check(&doc), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_inherited_clip_paths_are_bounded() {
    // `clip-path="inherit"` takes the direct parent's value.
    let text = "a".repeat(1000);
    let rects = r#"<rect width="5" height="5" clip-path="inherit"/>"#.repeat(100);
    let doc = format!(
        r#"{OPEN}<defs>{}</defs><g clip-path="url(#c)">{rects}</g><text x="0" y="9">a</text></svg>"#,
        obb_clip(&text)
    );
    assert_eq!(check(&doc), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_markers_through_use_copies_are_bounded() {
    // The marker is on the `<g>` around a `<use>`; usvg draws it on every
    // path the use copies, not only on the source path.
    let text = "a".repeat(1000);
    let a = r##"<use href="#p"/>"##.repeat(10);
    let b = r##"<use href="#a"/>"##.repeat(10);
    let doc = format!(
        r##"{OPEN}<defs><marker id="m" markerWidth="1" markerHeight="1"><text x="0" y="9">{text}</text></marker><path id="p" d="M0 0L5 5" stroke="black"/><g id="a">{a}</g><g id="b">{b}</g></defs><g marker-start="url(#m)"><use href="#b"/></g><text x="0" y="9">a</text></svg>"##
    );
    assert_eq!(check(&doc), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_marker_on_the_use_itself_is_bounded() {
    let text = "a".repeat(1000);
    let a = r##"<use href="#p"/>"##.repeat(10);
    let b = r##"<use href="#a"/>"##.repeat(10);
    let doc = format!(
        r##"{OPEN}<defs><marker id="m" markerWidth="1" markerHeight="1"><text x="0" y="9">{text}</text></marker><path id="p" d="M0 0L5 5" stroke="black"/><g id="a">{a}</g><g id="b">{b}</g></defs><use href="#b" marker-start="url(#m)"/><text x="0" y="9">a</text></svg>"##
    );
    assert_eq!(check(&doc), Err(Error::TooMuchText));
}

#[test]
fn svg_safety_text_free_stylesheet_marker_still_parses() {
    // An arrow marker without text is common; charging its path data against
    // the text budget refused a document usvg accepts.
    let d = format!("M0 0{}", "L1 1".repeat(50));
    let paths = format!(r#"<path d="{d}" stroke="black"/>"#).repeat(200);
    let doc = format!(
        r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><style>path{{marker-end:url(#a)}}</style><defs><marker id="a" markerWidth="4" markerHeight="4"><path d="M0 0L4 2L0 4z"/></marker></defs>{paths}</svg>"#
    );
    assert_eq!(check(&doc), Ok(false));
    assert!(size(doc.as_bytes()).is_ok());
}

#[test]
fn svg_text_draws_with_the_font_database() {
    // The machine's fonts are not part of this test: the document's family
    // comes from the database it is given.
    const PACIFICO: &[u8] =
        include_bytes!("../../../../tests/compat/cases/layout/fonts/Pacifico-Regular.ttf");
    let mut fontdb = usvg::fontdb::Database::new();
    fontdb.load_font_data(PACIFICO.to_vec());
    let mut options = options(true);
    options.fontdb = std::sync::Arc::new(fontdb);
    options.font_family = "Pacifico".into();
    let tree = parse_with(TEXT, &options).unwrap();
    let raster = draw(&tree, 40.0, MAX_SIDE).unwrap();
    assert_eq!(raster.size, pt(40.0, 20.0));
    assert!(
        !transparent(&raster),
        "text is drawn with the database's font"
    );
}

#[test]
fn svg_safety_text_uses_system_fonts() {
    use usvg::fontdb::{Family, Query, Stretch, Style, Weight};

    let raster = rasterize(TEXT, 40).unwrap();
    assert_eq!(raster.size, pt(40.0, 20.0));
    // A canvas may rasterize an app-generated SVG with text; the text uses
    // the system fonts the platform's text engine uses. A machine with no
    // font, or none of the families the fallback names, has nothing to draw
    // with.
    let serif = Query {
        families: &[Family::Serif],
        weight: Weight::NORMAL,
        stretch: Stretch::Normal,
        style: Style::Normal,
    };
    if super::SYSTEM_FONTS.query(&serif).is_some() {
        assert!(!transparent(&raster), "text is drawn with a system font");
    }
}

/// What a drawing of an SVG ([`drawing`]) fills and strokes, painted for a
/// box of `size` with text color `current`: each paint with the operations
/// before it (the state it draws with).
mod as_drawing {
    use super::*;
    use crate::{
        canvas::{
            CanvasOp, Drawing, FillRule, GradientShape, Num, Paint, PathOp, ViewPaint,
            point_in_path,
        },
        geometry::{Point, point, px},
        style::{Color, PaintStyle},
    };

    const GREEN: Color = Color(0x00ff_00ff);

    fn paint(drawing: &Drawing, size: Size<Points>) -> Drawing {
        drawing.painted(&PaintStyle::default(), GREEN, Color::TRANSPARENT, &[], size)
    }

    /// The paint of each shape, in order: `(fill or stroke style, the
    /// operations up to the shape, its path)`.
    fn shapes(drawing: &Drawing) -> Vec<(Paint, &[CanvasOp], &[PathOp])> {
        let (mut fill, mut stroke) = (None, None);
        let mut out = Vec::new();
        for (i, op) in drawing.ops.iter().enumerate() {
            match op {
                CanvasOp::FillStyle(p) => fill = Some(p.clone()),
                CanvasOp::StrokeStyle(p) => stroke = Some(p.clone()),
                CanvasOp::Fill(Some(path), _) => {
                    out.push((fill.clone().unwrap(), &drawing.ops[..i], &path[..]))
                }
                CanvasOp::Stroke(Some(path)) => {
                    out.push((stroke.clone().unwrap(), &drawing.ops[..i], &path[..]))
                }
                _ => {}
            }
        }
        out
    }

    fn inside(ops: &[CanvasOp], path: &[PathOp], x: f32, y: f32) -> bool {
        point_in_path(ops, Some(path), FillRule::NonZero, at(x, y), |_| 0.0)
    }

    fn at(x: f32, y: f32) -> Point<Points> {
        point(px(x), px(y))
    }

    /// A drawing parses text without scanning the system fonts: the vector
    /// replay has no glyphs, so the fonts would only cost a scan.
    #[test]
    fn svg_drawing_with_text_needs_no_fonts() {
        let doc = r##"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20"><rect width="20" height="20" fill="#00ff00"/><text x="2" y="12">hello</text></svg>"##;
        let d = drawing(doc).unwrap();
        let painted = paint(&d, pt(20.0, 20.0));
        assert_eq!(shapes(&painted).len(), 1);
    }

    /// An icon stroked with `currentColor` takes the view's text color,
    /// whatever it is when drawn; its own colors stay.
    #[test]
    fn svg_drawing_current_color_is_the_text_color() {
        let icon = r##"<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M4 4h16v16H4z" fill="none" stroke="currentColor" stroke-width="2"/><rect width="4" height="4" fill="#0000ff"/></svg>"##;
        let d = drawing(icon).unwrap();
        assert!(
            d.view_paints
                .iter()
                .any(|(_, v)| *v == ViewPaint::StrokeCurrentColor)
        );
        let painted = paint(&d, pt(24.0, 24.0));
        let paints: Vec<_> = shapes(&painted).into_iter().map(|s| s.0).collect();
        assert_eq!(
            paints,
            [Paint::Color(GREEN), Paint::Color(Color(0x0000_ffff))]
        );
        assert!(painted.ops.contains(&CanvasOp::LineWidth(Num::Const(2.0))));
        // A `color` of the document's own is what its `currentColor` is.
        let own = drawing(
            r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 4" color="#ff0000"><rect width="4" height="4" fill="currentColor"/></svg>"##,
        )
        .unwrap();
        assert_eq!(
            shapes(&painted_of(&own))[0].0,
            Paint::Color(Color(0xff00_00ff))
        );
    }

    fn painted_of(d: &Drawing) -> Drawing {
        paint(d, d.fit().unwrap().size)
    }

    /// Gradients are drawn as gradients, in the shape's coordinates
    /// (`objectBoundingBox` included), with their stops' opacity.
    #[test]
    fn svg_drawing_keeps_gradients() {
        let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
            <defs>
              <linearGradient id="l"><stop offset="0" stop-color="#ff0000"/><stop offset="1" stop-color="#0000ff" stop-opacity="0.5"/></linearGradient>
              <radialGradient id="r" cx="50" cy="50" r="40" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#000"/></radialGradient>
            </defs>
            <rect x="10" y="0" width="80" height="20" fill="url(#l)"/>
            <circle cx="50" cy="50" r="40" fill="url(#r)"/>
          </svg>"##;
        let painted = painted_of(&drawing(svg).unwrap());
        let shapes = shapes(&painted);
        let Paint::Gradient(linear) = &shapes[0].0 else {
            panic!("{:?}", shapes[0].0)
        };
        let GradientShape::Linear { start, end } = linear.shape else {
            panic!("{linear:?}")
        };
        // From the box's left edge to its right one.
        assert!((start.x.0 - 10.0).abs() < 1e-3 && (end.x.0 - 90.0).abs() < 1e-3);
        assert!((start.y.0 - end.y.0).abs() < 1e-3);
        assert_eq!(
            linear
                .stops
                .iter()
                .map(|(o, c)| (o.0, *c))
                .collect::<Vec<_>>(),
            [(0.0, Color(0xff00_00ff)), (1.0, Color(0x0000_ff80))]
        );
        let Paint::Gradient(radial) = &shapes[1].0 else {
            panic!("{:?}", shapes[1].0)
        };
        assert_eq!(
            radial.shape,
            GradientShape::Radial {
                start: at(50.0, 50.0),
                start_radius: Points::ZERO,
                end: at(50.0, 50.0),
                end_radius: px(40.0),
            }
        );
    }

    /// The view box is fitted into the canvas's box as
    /// `preserveAspectRatio` says: in the middle by default, stretched by
    /// `none`, covering it by `slice`; the canvas's natural size is the
    /// SVG's `width` and `height`.
    #[test]
    fn svg_drawing_fits_its_view_box_into_the_box() {
        let tall = |aspect: &str| {
            drawing(&format!(
                r##"<svg xmlns="http://www.w3.org/2000/svg" width="5" height="10" viewBox="0 0 10 20" {aspect}><rect width="10" height="20"/></svg>"##
            ))
            .unwrap()
        };
        let meet = tall("");
        assert_eq!(meet.fit().unwrap().size, pt(5.0, 10.0));
        let painted = paint(&meet, pt(40.0, 40.0));
        let (_, ops, path) = shapes(&painted)[0];
        // 20 × 40 in the middle of 40 × 40.
        assert!(inside(ops, path, 11.0, 1.0) && inside(ops, path, 29.0, 39.0));
        assert!(!inside(ops, path, 9.0, 20.0) && !inside(ops, path, 31.0, 20.0));
        let painted = painted_of(&tall(r#"preserveAspectRatio="none""#));
        let (_, ops, path) = shapes(&painted)[0];
        assert!(inside(ops, path, 4.9, 9.9) && !inside(ops, path, 5.1, 5.0));
        let stretched = drawing(
            r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 20" preserveAspectRatio="none"><rect width="10" height="20"/></svg>"##,
        )
        .unwrap();
        let painted = paint(&stretched, pt(40.0, 40.0));
        let (_, ops, path) = shapes(&painted)[0];
        assert!(inside(ops, path, 1.0, 1.0) && inside(ops, path, 39.0, 39.0));
        // Sliced: 40 × 80 from 20 above the top; its top left quarter is
        // a red square, the rest blue.
        let sliced = drawing(
            r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 20" preserveAspectRatio="xMinYMid slice"><rect width="10" height="20" fill="#00f"/><rect width="5" height="10" fill="#f00"/></svg>"##,
        )
        .unwrap();
        let painted = paint(&sliced, pt(40.0, 40.0));
        let (_, ops, red) = shapes(&painted)[1];
        assert!(inside(ops, red, 19.0, 19.0) && !inside(ops, red, 21.0, 19.0));
        assert!(!inside(ops, red, 19.0, 21.0));
        // A `width` and `height` beside the view box scale what usvg
        // draws; the drawing stays in the view box's coordinates.
        let big = drawing(
            r##"<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24"><rect width="12" height="12"/></svg>"##,
        )
        .unwrap();
        assert_eq!(big.fit().unwrap().size, pt(48.0, 48.0));
        let painted = paint(&big, pt(24.0, 24.0));
        let (_, ops, path) = shapes(&painted)[0];
        assert!(inside(ops, path, 11.0, 11.0) && !inside(ops, path, 13.0, 5.0));
    }

    /// A document that is no SVG fails as the rasters do.
    #[test]
    fn svg_drawing_of_no_svg_fails() {
        assert!(matches!(drawing("<html/>"), Err(Error::Invalid(_))));
        assert!(drawing("not xml").is_err());
    }
}