d2-rs-math 0.1.13

Rust port of D2's d2latex package and mathjax-go: LaTeX layout and SVG.
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
// SPDX-License-Identifier: MPL-2.0 AND BSD-3-Clause
// decoder_field: Copyright 2009 The Go Authors. All rights reserved.
// Source: D2 d2renderers/d2svgimport/import.go, lib/svg/doctype.go.
use super::svg_xml_admission::{Attribute, Attributes, State};
use quick_xml::{Reader, events::Event};
use std::collections::BTreeMap;
fn context(cancel: Option<&d2_rs_core::CancellationToken>) -> Result<(), String> {
    match cancel.and_then(d2_rs_core::CancellationToken::error) {
        Some(d2_rs_core::LayoutError::DeadlineExceeded) => Err("context deadline exceeded".into()),
        Some(_) => Err("context canceled".into()),
        None => Ok(()),
    }
}
#[derive(Debug, serde::Serialize, serde::Deserialize, PartialEq)]
pub struct Element {
    pub name: String,
    pub attributes: Attributes,
    pub children: Vec<usize>,
    pub parent: Option<usize>,
    pub text: Vec<u8>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize, PartialEq)]
pub struct Document {
    pub namespace: String,
    pub elements: Vec<Element>,
    pub ids: BTreeMap<String, usize>,
    pub counts: [usize; 4],
    /// Set when an animation names opacity, display, or visibility. Omitted
    /// from v0.9 fixture JSON; serde default keeps those comparisons stable.
    #[serde(default)]
    pub has_visibility_animation: bool,
}
impl Document {
    /// Count authored ID declarations, including ambiguous repetitions.
    pub fn declared_ids(&self) -> usize {
        self.elements
            .iter()
            .filter(|e| {
                e.attributes
                    .values
                    .get("id")
                    .is_some_and(|id| !id.is_empty())
            })
            .count()
    }
}

fn space(c: u8) -> bool {
    matches!(c, b' ' | b'\t' | b'\r' | b'\n')
}
// Go encoding/xml:procInst searches name= before the importer's stricter field
// parser. Preserve this lookup, including its deliberately permissive syntax.
fn decoder_field<'a>(name: &str, mut input: &'a str) -> &'a str {
    let key = format!("{name}=");
    while let Some(at) = input.find(&key) {
        let rest = &input[at + key.len()..];
        let Some(&quote) = rest.as_bytes().first() else {
            return "";
        };
        if matches!(quote, b'\'' | b'"') {
            return rest[1..]
                .find(quote as char)
                .map_or("", |end| &rest[1..end + 1]);
        }
        input = &rest[rest.chars().next().unwrap().len_utf8()..];
    }
    ""
}
struct Fields<'a> {
    bytes: &'a [u8],
    at: usize,
}
impl<'a> Fields<'a> {
    fn skip(&mut self) -> bool {
        let before = self.at;
        while self.at < self.bytes.len() && space(self.bytes[self.at]) {
            self.at += 1;
        }
        self.at != before
    }
    fn take(&mut self, value: &[u8]) -> bool {
        if self.bytes[self.at..].starts_with(value) {
            self.at += value.len();
            true
        } else {
            false
        }
    }
    fn quoted(&mut self) -> Option<&'a [u8]> {
        let quote = *self.bytes.get(self.at)?;
        if !matches!(quote, b'\'' | b'"') {
            return None;
        }
        self.at += 1;
        let start = self.at;
        while self.at < self.bytes.len() && self.bytes[self.at] != quote {
            self.at += 1;
        }
        if self.at == self.bytes.len() {
            return None;
        }
        let result = &self.bytes[start..self.at];
        self.at += 1;
        Some(result)
    }
}
pub fn declaration(
    input: &str,
    end: usize,
    cancel: Option<&d2_rs_core::CancellationToken>,
) -> Result<(), String> {
    let version = decoder_field("version", input);
    let encoding = decoder_field("encoding", input);
    if (!version.is_empty() && version != "1.0")
        || (!encoding.is_empty()
            && !encoding.eq_ignore_ascii_case("UTF-8")
            && !encoding.eq_ignore_ascii_case("ISO-8859-1"))
    {
        return Err(format!("invalid XML near byte {end}"));
    }
    let invalid = || "invalid XML declaration".to_string();
    let mut p = Fields {
        bytes: input.as_bytes(),
        at: 0,
    };
    skip_declaration_space(&mut p, cancel)?;
    let mut fields = Vec::new();
    while p.at < p.bytes.len() {
        context(cancel)?;
        let start = p.at;
        while p.at < p.bytes.len() && p.bytes[p.at].is_ascii_alphabetic() {
            p.at += 1;
            if p.at & 4095 == 0 {
                context(cancel)?;
            }
        }
        if start == p.at {
            return Err(invalid());
        }
        let name = &p.bytes[start..p.at];
        skip_declaration_space(&mut p, cancel)?;
        if !p.take(b"=") {
            return Err(invalid());
        }
        skip_declaration_space(&mut p, cancel)?;
        let quote = *p.bytes.get(p.at).ok_or_else(invalid)?;
        if !matches!(quote, b'\'' | b'"') {
            return Err(invalid());
        }
        p.at += 1;
        let start = p.at;
        while p.at < p.bytes.len() && p.bytes[p.at] != quote {
            p.at += 1;
            if p.at & 4095 == 0 {
                context(cancel)?;
            }
        }
        if p.at == p.bytes.len() {
            return Err(invalid());
        }
        let value = &p.bytes[start..p.at];
        p.at += 1;
        fields.push((name, value));
        if p.at < p.bytes.len() && !space(p.bytes[p.at]) {
            return Err(invalid());
        }
        skip_declaration_space(&mut p, cancel)?;
    }
    if fields.is_empty()
        || fields.len() > 3
        || fields[0] != (b"version".as_slice(), b"1.0".as_slice())
    {
        return Err(invalid());
    }
    let mut next = 1;
    if fields.get(next).is_some_and(|f| f.0 == b"encoding") {
        if !fields[next].1.eq_ignore_ascii_case(b"UTF-8")
            && !fields[next].1.eq_ignore_ascii_case(b"ISO-8859-1")
        {
            return Err("only UTF-8 and ISO-8859-1 XML declarations are supported".into());
        }
        next += 1;
    }
    if fields.get(next).is_some_and(|f| f.0 == b"standalone") {
        if !matches!(fields[next].1, b"yes" | b"no") {
            return Err(invalid());
        }
        next += 1;
    }
    if next != fields.len() {
        return Err(invalid());
    }
    Ok(())
}
fn skip_declaration_space(
    p: &mut Fields<'_>,
    cancel: Option<&d2_rs_core::CancellationToken>,
) -> Result<(), String> {
    while p.at < p.bytes.len() && space(p.bytes[p.at]) {
        p.at += 1;
        if p.at & 4095 == 0 {
            context(cancel)?;
        }
    }
    Ok(())
}
/// encoding/xml Decoder.name/nsname: the run of name bytes (ASCII name
/// characters and every byte >= 0x80) at `start` must be a valid XML name;
/// nsname also rejects more than one colon. Returns the syntax error offset,
/// the end of the run.
fn go_name_error(input: &str, start: usize, namespaced: bool) -> Option<usize> {
    let bytes = input.as_bytes();
    let mut end = start;
    while bytes.get(end).is_some_and(|&byte| {
        byte >= 0x80 || byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b':' | b'.' | b'-')
    }) {
        end += 1;
    }
    let name = input.get(start..end)?;
    let invalid = !crate::image_svg::go_xml_names::valid(name)
        || (namespaced && name.matches(':').count() > 1);
    invalid.then_some(end)
}
/// encoding/xml reads `<!` not followed by `-` or `[` as a directive up to the
/// unquoted `>` that closes its nesting depth (skipping nested comments).
fn go_directive_closes(rest: &[u8]) -> bool {
    let mut quote = 0u8;
    let mut depth = 0usize;
    let mut i = 3;
    while i < rest.len() {
        let b = rest[i];
        if quote == 0 && b == b'>' && depth == 0 {
            return true;
        }
        if b == quote {
            quote = 0;
        } else if quote != 0 {
        } else if b == b'\'' || b == b'"' {
            quote = b;
        } else if b == b'>' {
            depth = depth.saturating_sub(1);
        } else if b == b'<' {
            if rest[i + 1..].starts_with(b"!--") {
                let Some(close) = rest[i + 4..].windows(3).position(|w| w == b"-->") else {
                    return false;
                };
                i += 4 + close + 3;
                continue;
            }
            depth += 1;
        }
        i += 1;
    }
    false
}
fn doctype(raw: &str, start: usize) -> bool {
    // Original helper caps both the raw declaration and prolog scan. No
    // internal subset, entity expansion, system-only locator or DTD resolution.
    if raw.len() > 256 || start + 9 > 16 << 10 {
        return false;
    }
    let mut p = Fields {
        bytes: raw.as_bytes(),
        at: 0,
    };
    if !p.take(b"<!DOCTYPE")
        || !p.skip()
        || !p.take(b"svg")
        || !p.skip()
        || !p.take(b"PUBLIC")
        || !p.skip()
    {
        return false;
    }
    let Some(public) = p.quoted() else {
        return false;
    };
    if !p.skip() {
        return false;
    }
    let Some(system) = p.quoted() else {
        return false;
    };
    p.skip();
    if !p.take(b">") || p.at != p.bytes.len() {
        return false;
    }
    (public == b"-//W3C//DTD SVG 1.0//EN"
        && system == b"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd")
        || (public == b"-//W3C//DTD SVG 1.1//EN"
            && system == b"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd")
}
fn resolve(name: &str, bindings: &BTreeMap<String, String>, attribute: bool) -> (String, String) {
    // encoding/xml translate leaves an unprefixed `xmlns` name, element or
    // attribute, in the empty namespace.
    if name == "xmlns" {
        return (String::new(), name.into());
    }
    if let Some((prefix, local)) = name.split_once(':') {
        let namespace = if attribute && prefix == "xmlns" {
            "xmlns".into()
        } else if prefix == "xml" {
            super::svg_xml_admission::XML.into()
        } else {
            bindings
                .get(prefix)
                .cloned()
                .unwrap_or_else(|| prefix.into())
        };
        (namespace, local.into())
    } else {
        (
            if attribute {
                String::new()
            } else {
                bindings.get("").cloned().unwrap_or_default()
            },
            name.into(),
        )
    }
}
// Go text() rejects unknown entities immediately after consuming their
// semicolon, before the closing quote/start-tag terminator is read.
fn attribute_decode_error(raw: &[u8], offset: usize) -> usize {
    for (index, &byte) in raw.iter().enumerate() {
        if byte == b'<' {
            return offset + index + 1;
        }
        if byte == b'&' {
            let tail = &raw[index..];
            if let Some(end) = tail.iter().position(|&b| b == b';') {
                if std::str::from_utf8(&tail[..=end])
                    .ok()
                    .is_some_and(|text| quick_xml::escape::unescape(text).is_err())
                {
                    return offset + index + end + 1;
                }
            }
        }
    }
    offset + raw.len() + 1
}
fn decoded(raw: &[u8], entities: bool) -> Result<Vec<u8>, ()> {
    let text = std::str::from_utf8(raw).map_err(|_| ())?;
    let normalized = text.replace("\r\n", "\n").replace('\r', "\n");
    let text = if entities {
        quick_xml::escape::unescape(&normalized)
            .map_err(|_| ())?
            .into_owned()
    } else {
        normalized
    };
    if text.chars().any(|c| {
        !matches!(c, '\t' | '\n' | '\r') && (c < '\u{20}' || c == '\u{fffe}' || c == '\u{ffff}')
    }) {
        return Err(());
    }
    Ok(text.into_bytes())
}
/// Native parsed tree and declared ID inventory. Limits have the same order as
/// structural_work. Source is the already-redacted importer diagnostic label.
pub fn parse(
    source: &str,
    input: &str,
    limits: [usize; 9],
    cancel: Option<&d2_rs_core::CancellationToken>,
) -> Result<Document, String> {
    parse_bytes(source, input.as_bytes(), limits, cancel)
}
pub fn parse_bytes(
    source: &str,
    input: &[u8],
    limits: [usize; 9],
    cancel: Option<&d2_rs_core::CancellationToken>,
) -> Result<Document, String> {
    context(cancel)?;
    if limits.contains(&0) {
        return Err("d2svgimport: all import limits must be positive".into());
    }
    if input.len() > limits[0] {
        return Err(format!(
            "d2svgimport: {source} is {} bytes, exceeding limit {}",
            input.len(),
            limits[0]
        ));
    }
    let input = input.strip_prefix(&[0xef, 0xbb, 0xbf]).unwrap_or(input);
    let declaration_end = if input.starts_with(b"<?xml") {
        input
            .windows(2)
            .position(|pair| pair == b"?>")
            .map(|end| end + 2)
    } else {
        None
    };
    let latin1 = declaration_end
        .and_then(|end| std::str::from_utf8(&input[5..end - 2]).ok())
        .is_some_and(|header| decoder_field("encoding", header).eq_ignore_ascii_case("ISO-8859-1"));
    let converted;
    let input = if latin1 {
        let end = declaration_end.unwrap();
        let prefix = std::str::from_utf8(&input[..end])
            .map_err(|_| format!("d2svgimport: {source}: invalid XML near byte {end}"))?;
        let mut output = prefix.to_owned();
        for chunk in input[end..].chunks(4096) {
            context(cancel)?;
            output.extend(chunk.iter().copied().map(char::from));
        }
        converted = output;
        converted.as_str()
    } else {
        std::str::from_utf8(input).map_err(|_| {
            format!(
                "d2svgimport: {source}: invalid XML near byte {}",
                input.len()
            )
        })?
    };
    parse_decoded(source, input, limits, cancel)
}
fn parse_decoded(
    source: &str,
    input: &str,
    limits: [usize; 9],
    cancel: Option<&d2_rs_core::CancellationToken>,
) -> Result<Document, String> {
    // ImportNode removes exactly one BOM. quick-xml would remove another
    // automatically; encoding/xml instead returns that remaining BOM as text.
    if input.starts_with('\u{feff}') {
        let end = input.find('<').unwrap_or(input.len());
        return Err(format!(
            "d2svgimport: {source}: text content is unsupported near byte {end}"
        ));
    }
    let mut reader = Reader::from_str(input);
    reader.config_mut().check_comments = true;
    let mut scopes: Vec<BTreeMap<String, String>> = Vec::new();
    let mut document = Document {
        namespace: String::new(),
        elements: Vec::new(),
        ids: BTreeMap::new(),
        counts: [0; 4],
        has_visibility_animation: false,
    };
    let mut declared_ids = 0;
    let mut state = State::default();
    let mut stack: Vec<usize> = Vec::new();
    let mut closed = false;
    let mut declaration_allowed = true;
    let mut seen_declaration = false;
    let mut seen_doctype = false;
    let error = |reason: String| format!("d2svgimport: {source}: {reason}");
    loop {
        context(cancel)?;
        let start = reader.buffer_position() as usize;
        let event = reader.read_event().map_err(|_| {
            let rest = &input.as_bytes()[start..];
            if rest.starts_with(b"<!")
                && rest.len() > 2
                && !matches!(rest[2], b'-' | b'[')
                && go_directive_closes(rest)
            {
                return error("unsupported XML directive or DTD".into());
            }
            let mut at = reader.buffer_position() as usize;
            if input.as_bytes()[start..].starts_with(b"<!--") {
                if let Some(position) = input[start + 4..].find("--") {
                    at = start + 4 + position + 3;
                }
            }
            error(format!("invalid XML near byte {at}"))
        })?;
        let end = reader.buffer_position() as usize;
        match event {
            Event::Start(node) | Event::Empty(node) => {
                if let Some(at) = go_name_error(input, start + 1, true) {
                    return Err(error(format!("invalid XML near byte {at}")));
                }
                let mut raw_attrs = Vec::new();
                for item in node.attributes().with_checks(false) {
                    let item = item.map_err(|reason| {
                        use quick_xml::events::attributes::AttrError;
                        let at = match reason {
                            AttrError::UnquotedValue(position)
                            | AttrError::ExpectedEq(position) => start + 2 + position,
                            _ => end,
                        };
                        error(format!("invalid XML near byte {at}"))
                    })?;
                    let key_at =
                        (item.key.as_ref().as_ptr() as usize).wrapping_sub(input.as_ptr() as usize);
                    if key_at < input.len() {
                        if let Some(at) = go_name_error(input, key_at, true) {
                            return Err(error(format!("invalid XML near byte {at}")));
                        }
                    }
                    let name = std::str::from_utf8(item.key.as_ref())
                        .map_err(|_| error(format!("invalid XML near byte {end}")))?
                        .to_owned();
                    let value = decoded(item.value.as_ref(), true).map_err(|_| {
                        let offset = (item.value.as_ptr() as usize)
                            .checked_sub(input.as_ptr() as usize)
                            .filter(|&offset| offset <= input.len())
                            .unwrap_or(start);
                        error(format!(
                            "invalid XML near byte {}",
                            attribute_decode_error(item.value.as_ref(), offset)
                        ))
                    })?;
                    raw_attrs.push((name, String::from_utf8(value).unwrap()));
                }
                let empty = input.as_bytes().get(end.saturating_sub(2)..end) == Some(b"/>");
                declaration_allowed = false;
                if closed {
                    return Err(error(format!("multiple root elements near byte {end}")));
                }
                if stack.len() + 1 > limits[1] {
                    return Err(error(format!("XML depth exceeds limit {}", limits[1])));
                }
                document.counts[0] += 1;
                if document.counts[0] > limits[2] {
                    return Err(error(format!("element count exceeds limit {}", limits[2])));
                }
                let mut bindings = scopes.last().cloned().unwrap_or_default();
                for (name, value) in &raw_attrs {
                    if name == "xmlns" {
                        bindings.insert(String::new(), value.clone());
                    } else if let Some(prefix) = name.strip_prefix("xmlns:") {
                        bindings.insert(prefix.into(), value.clone());
                    }
                }
                let qname = node.name();
                let qname = std::str::from_utf8(qname.as_ref())
                    .map_err(|_| error(format!("invalid XML near byte {end}")))?;
                let (ns, local) = resolve(qname, &bindings, false);
                let name = state.element(source, &ns, &local)?;
                if document.elements.is_empty() && name != "svg" {
                    return Err(error(format!("root element must be <svg>, got <{name}>")));
                }
                let attrs = raw_attrs
                    .into_iter()
                    .map(|(name, value)| {
                        let (namespace, name) = resolve(&name, &bindings, true);
                        Attribute {
                            namespace,
                            name,
                            value,
                        }
                    })
                    .collect::<Vec<_>>();
                let mut attributes =
                    state.attributes(source, &name, &attrs, limits[3], limits[4], cancel)?;
                let index = document.elements.len();
                if !attributes.id.is_empty() {
                    if declared_ids >= limits[8] {
                        return Err(error(format!(
                            "ID resource count exceeds limit {}",
                            limits[8]
                        )));
                    }
                    declared_ids += 1;
                    if let Some(previous) = document.ids.insert(attributes.id.clone(), index) {
                        if let Some(previous) = document.elements.get_mut(previous) {
                            previous.attributes.id.clear();
                        }
                        document.ids.insert(attributes.id.clone(), usize::MAX);
                        attributes.id.clear();
                    }
                }
                let parent = stack.last().copied();
                if let Some(parent) = parent {
                    let parent_name = document.elements[parent].name.clone();
                    if is_animation(&parent_name) {
                        if name == "title" || name == "desc" {
                            for attribute in &attributes.order {
                                if attribute != "id" {
                                    return Err(error(format!(
                                        "element <{name}> has unsupported attribute {:?}",
                                        display_name(attribute)
                                    )));
                                }
                            }
                        } else if name != "mpath" || parent_name != "animateMotion" {
                            return Err(error(format!(
                                "animation element <{parent_name}> has unsupported child <{name}>"
                            )));
                        }
                    }
                    if matches!(parent_name.as_str(), "title" | "desc" | "dc:title") {
                        return Err(error(format!(
                            "non-rendering element <{parent_name}> cannot contain child elements"
                        )));
                    }
                    if is_animation(&name) {
                        validate_animation(
                            source,
                            &name,
                            &attributes,
                            parent,
                            &mut document,
                            cancel,
                        )?;
                    } else {
                        document.elements[parent].children.push(index);
                    }
                }
                document.elements.push(Element {
                    name,
                    attributes,
                    children: Vec::new(),
                    parent,
                    text: Vec::new(),
                });
                if empty {
                    if stack.is_empty() {
                        closed = true;
                    }
                } else {
                    stack.push(index);
                    scopes.push(bindings);
                }
            }
            Event::End(node) => {
                if let Some(at) = go_name_error(input, start + 2, true) {
                    return Err(error(format!("invalid XML near byte {at}")));
                }
                declaration_allowed = false;
                if stack.is_empty() {
                    return Err(error(format!("unexpected closing element near byte {end}")));
                }
                let qname = node.name();
                let qname = std::str::from_utf8(qname.as_ref())
                    .map_err(|_| error(format!("invalid XML near byte {end}")))?;
                let (ns, local) = resolve(qname, scopes.last().unwrap(), false);
                let name = state.element(source, &ns, &local)?;
                let current = *stack.last().unwrap();
                if document.elements[current].name != name {
                    return Err(error(format!(
                        "closing </{name}> does not match <{}>",
                        document.elements[current].name
                    )));
                }
                stack.pop();
                scopes.pop();
                if stack.is_empty() {
                    closed = true;
                }
            }
            Event::Text(text) => text_event(
                &mut document,
                &stack,
                &decoded(text.as_ref(), true)
                    .map_err(|_| error(format!("invalid XML near byte {end}")))?,
                limits[0],
                source,
                end,
                &mut declaration_allowed,
                cancel,
            )?,
            Event::CData(text) => text_event(
                &mut document,
                &stack,
                &decoded(text.as_ref(), false)
                    .map_err(|_| error(format!("invalid XML near byte {end}")))?,
                limits[0],
                source,
                end,
                &mut declaration_allowed,
                cancel,
            )?,
            Event::Comment(_) => {
                if stack
                    .last()
                    .is_some_and(|&index| document.elements[index].name == "style")
                {
                    return Err(error("XML comments in <style> are unsupported".into()));
                }
                declaration_allowed = false;
            }
            Event::Decl(_) => {
                if seen_declaration
                    || !declaration_allowed
                    || !document.elements.is_empty()
                    || !stack.is_empty()
                {
                    return Err(error("XML processing instructions are forbidden".into()));
                }
                declaration(&input[start + 5..end - 2], end, cancel).map_err(&error)?;
                seen_declaration = true;
                declaration_allowed = false;
            }
            Event::PI(_) => {
                // Decoder.name reads the target first; it has no colon rule.
                if let Some(at) = go_name_error(input, start + 2, false) {
                    return Err(error(format!("invalid XML near byte {at}")));
                }
                return Err(error("XML processing instructions are forbidden".into()));
            }
            Event::DocType(_) => {
                if !document.elements.is_empty()
                    || !stack.is_empty()
                    || seen_doctype
                    || !doctype(&input[start..end], start)
                {
                    return Err(error("unsupported XML directive or DTD".into()));
                }
                seen_doctype = true;
                declaration_allowed = false;
            }
            Event::Eof => {
                if !stack.is_empty() {
                    return Err(error(format!("invalid XML near byte {end}")));
                }
                break;
            }
        }
    }
    if document.elements.is_empty() {
        return Err(error("document has no root <svg> element".into()));
    }
    if let Some(&index) = stack.last() {
        return Err(error(format!(
            "unterminated <{}> element",
            document.elements[index].name
        )));
    }
    if !closed {
        return Err(error("unterminated root element".into()));
    }
    document.namespace = state.namespace.unwrap_or_default();
    document.counts[1] = state.attributes;
    document.counts[2] = state.attribute_bytes;
    Ok(document)
}
fn is_animation(name: &str) -> bool {
    matches!(
        name,
        "animate" | "animateColor" | "animateTransform" | "animateMotion" | "set" | "mpath"
    )
}
fn display_name(name: &str) -> &str {
    if name.len() > 64 {
        "<oversized-name>"
    } else {
        name
    }
}
fn animation_attribute(name: &str) -> bool {
    matches!(
        name,
        "id" | "href"
            | "attributeName"
            | "attributeType"
            | "type"
            | "begin"
            | "dur"
            | "end"
            | "min"
            | "max"
            | "restart"
            | "repeatCount"
            | "repeatDur"
            | "fill"
            | "calcMode"
            | "values"
            | "keyTimes"
            | "keySplines"
            | "from"
            | "to"
            | "by"
            | "additive"
            | "accumulate"
            | "path"
            | "keyPoints"
            | "rotate"
    )
}
/// import.go StartElement animation branch plus boilerplate.go validateAnimation.
fn validate_animation(
    source: &str,
    name: &str,
    attributes: &Attributes,
    parent: usize,
    document: &mut Document,
    cancel: Option<&d2_rs_core::CancellationToken>,
) -> Result<(), String> {
    let error = |reason: String| format!("d2svgimport: {source}: {reason}");
    if name == "mpath" && document.elements[parent].name != "animateMotion" {
        return Err(error("<mpath> must be a child of <animateMotion>".into()));
    }
    for attribute in &attributes.order {
        if !animation_attribute(attribute)
            || (name == "mpath" && attribute != "href" && attribute != "id")
        {
            return Err(error(format!(
                "element <{name}> has unsupported attribute {:?}",
                display_name(attribute)
            )));
        }
    }
    if attributes.values.contains_key("href") || name == "mpath" {
        let href = attributes
            .values
            .get("href")
            .map(String::as_str)
            .unwrap_or("");
        let Some(id) = href.strip_prefix('#') else {
            return Err(error(format!(
                "element <{name}> href must be one local #id reference"
            )));
        };
        if !super::svg_xml_admission::valid_id(id, cancel)? {
            return Err(error(format!(
                "element <{name}> href must be one local #id reference"
            )));
        }
    }
    let attribute_name = attributes
        .values
        .get("attributeName")
        .map(String::as_str)
        .unwrap_or("");
    if matches!(attribute_name, "opacity" | "display" | "visibility") {
        document.has_visibility_animation = true;
    }
    let base = document.elements[parent]
        .attributes
        .values
        .get(attribute_name)
        .cloned()
        .unwrap_or_default();
    if let Some(to) = reveal(name, attribute_name, &base, &attributes.values) {
        document.elements[parent]
            .attributes
            .values
            .insert(attribute_name.to_owned(), to);
    }
    Ok(())
}
/// svgposter.Reveal. A direct unconditional reveal replaces the parent's
/// presentation attribute; every other SMIL keeps the authored base.
fn reveal(
    element: &str,
    attribute: &str,
    base: &str,
    attrs: &BTreeMap<String, String>,
) -> Option<String> {
    let attr = |key: &str| attrs.get(key).map(String::as_str).unwrap_or("");
    if !attr("href").is_empty()
        || (element != "set" && (element != "animate" || attr("fill").trim() != "freeze"))
    {
        return None;
    }
    match attr("begin").trim() {
        "" | "0" | "0s" | "0ms" => {}
        _ => return None,
    }
    if attr("repeatCount").trim() == "indefinite" || attr("repeatDur").trim() == "indefinite" {
        return None;
    }
    let values = attr("values").trim();
    let to = if element == "animate" && !values.is_empty() {
        last_smil_value(values)
    } else {
        attr("to").trim().to_owned()
    };
    let base = base.trim();
    match attribute {
        "opacity" => {
            let start = base.parse::<f64>().ok()?;
            let end = to.parse::<f64>().ok()?;
            if start == 0.0 && end > 0.0 && end <= 1.0 {
                Some(format_g(end))
            } else {
                None
            }
        }
        "visibility" if (base == "hidden" || base == "collapse") && to == "visible" => Some(to),
        "display" if base == "none" && (to == "inline" || to == "block") => Some(to),
        _ => None,
    }
}
fn last_smil_value(values: &str) -> String {
    let trimmed = values.trim_end_matches(|c: char| c == ';' || c.is_whitespace());
    if trimmed.is_empty() {
        return String::new();
    }
    let start = trimmed.rfind(';').map(|index| index + 1).unwrap_or(0);
    trimmed[start..].trim().to_owned()
}
/// strconv.FormatFloat(v, 'g', -1, 64) for the (0, 1] reveal endpoint.
fn format_g(value: f64) -> String {
    if value == 0.0 {
        return "0".to_owned();
    }
    let sci = format!("{value:e}");
    let (mantissa, exp) = sci.split_once('e').expect("scientific float");
    let exp: i32 = exp.parse().expect("float exponent");
    let digits: String = mantissa
        .chars()
        .filter(|c| *c != '.' && *c != '-')
        .collect();
    let mut out = String::new();
    if !(-4..6).contains(&exp) {
        out.push_str(&digits[..1]);
        if digits.len() > 1 {
            out.push('.');
            out.push_str(&digits[1..]);
        }
        out.push('e');
        out.push(if exp < 0 { '-' } else { '+' });
        out.push_str(&format!("{:02}", exp.abs()));
    } else if exp >= 0 {
        let int_len = exp as usize + 1;
        if digits.len() <= int_len {
            out.push_str(&digits);
            out.extend(std::iter::repeat_n('0', int_len - digits.len()));
        } else {
            out.push_str(&digits[..int_len]);
            out.push('.');
            out.push_str(&digits[int_len..]);
        }
    } else {
        out.push_str("0.");
        out.extend(std::iter::repeat_n('0', (-exp - 1) as usize));
        out.push_str(&digits);
    }
    out
}
fn text_event(
    document: &mut Document,
    stack: &[usize],
    value: &[u8],
    maximum: usize,
    source: &str,
    end: usize,
    declaration_allowed: &mut bool,
    cancel: Option<&d2_rs_core::CancellationToken>,
) -> Result<(), String> {
    let current = stack.last().copied();
    let name = current
        .map(|index| document.elements[index].name.as_str())
        .unwrap_or("");
    if matches!(name, "style" | "text" | "tspan" | "dc:format") {
        let kind = match name {
            "style" => "stylesheet",
            "text" | "tspan" => "painted",
            _ => "metadata",
        };
        let stylesheet = name == "style";
        let index = current.unwrap();
        for chunk in value.chunks(4096) {
            context(cancel)?;
            let used = if stylesheet {
                document.counts[3]
            } else {
                document.elements[index].text.len()
            };
            if used > maximum || chunk.len() > maximum - used {
                return Err(format!(
                    "d2svgimport: {source}: {kind} text exceeds byte limit {maximum}"
                ));
            }
            document.elements[index].text.extend_from_slice(chunk);
            if stylesheet {
                document.counts[3] += chunk.len();
            }
        }
        context(cancel)?;
    } else if matches!(name, "title" | "desc" | "dc:title") {
        for _ in value.chunks(4096) {
            context(cancel)?;
        }
        context(cancel)?;
    } else {
        for (index, &byte) in value.iter().enumerate() {
            if !space(byte) {
                return Err(format!(
                    "d2svgimport: {source}: text content is unsupported near byte {end}"
                ));
            }
            if index & 4095 == 0 {
                context(cancel)?;
            }
        }
    }
    if !value.is_empty() {
        *declaration_allowed = false;
    }
    Ok(())
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn document_context_precedes_limits_and_byte_work() {
        let token = d2_rs_core::CancellationToken::new();
        token.cancel();
        assert_eq!(
            parse_bytes("math", b"<svg/>", [0; 9], Some(&token)).unwrap_err(),
            "context canceled"
        );
        let token = d2_rs_core::CancellationToken::new();
        token.expire();
        assert_eq!(
            parse_bytes("math", b"<svg/>", [1; 9], Some(&token)).unwrap_err(),
            "context deadline exceeded"
        );
        assert_eq!(
            parse_bytes("math", b"<svg/>", [0; 9], None).unwrap_err(),
            "d2svgimport: all import limits must be positive"
        );
        assert_eq!(
            parse_bytes("math", b"<svg/>", [1; 9], None).unwrap_err(),
            "d2svgimport: math is 6 bytes, exceeding limit 1"
        );
    }
    #[cfg(feature = "oracle-fixtures")]
    #[test]
    fn original_xml_document_trees_and_errors() {
        let rows: serde_json::Value = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
            "tests/fixtures/svg-xml-document-v090.json"
        ))
        .unwrap();
        let mut mismatches = Vec::new();
        for row in rows.as_array().unwrap() {
            let limits = serde_json::from_value(row["limits"].clone()).unwrap();
            let bytes: Vec<u8> = serde_json::from_value(row["input_bytes"].clone()).unwrap();
            let result = parse_bytes("math", &bytes, limits, None);
            let actual_error = result.as_ref().err().map(String::as_str).unwrap_or("");
            if actual_error != row["error"].as_str().unwrap() {
                mismatches.push(format!(
                    "{} {:?}: expected {:?}, got {:?}",
                    row["mode"], row["input"], row["error"], actual_error
                ));
                continue;
            }
            if let Ok(document) = result {
                // The capture records an ambiguous (duplicated) ID as null;
                // the parser keeps it under the usize::MAX sentinel.
                let mut output = row["output"].clone();
                if let Some(ids) = output.get_mut("ids").and_then(|v| v.as_object_mut()) {
                    for value in ids.values_mut() {
                        if value.is_null() {
                            *value = serde_json::json!(usize::MAX);
                        }
                    }
                }
                let expected: Document = serde_json::from_value(output).unwrap();
                assert_eq!(document, expected, "{row}");
            }
        }
        assert!(mismatches.is_empty(), "{}", mismatches.join("\n"));
    }
}