asset-io 0.4.0

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

// Unless required by applicable law or agreed to in writing,
// this software is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
// specific language governing permissions and limitations under
// each license.

//! SVG on the structure model: a text container, with no binary framing.
//!
//! A C2PA manifest is the base64 text of a `<c2pa:manifest>` element in the root
//! element's `<metadata>`; XMP is an `<?xpacket ...?>` packet. The file is cut into
//! segments at those, and only those:
//!
//! - the first segment, the [`Preamble`](SegmentKind::Preamble), runs from the start
//!   of the file through the root element's start tag;
//! - a `<c2pa:manifest>` element is a [`Metadata`](SegmentKind::Metadata) segment: the
//!   open tag is its header, the base64 text its payload and the close tag its
//!   trailer, so the payload is the range a C2PA hash excludes. A non-empty payload
//!   is an [`ItemKind::Jumbf`] item;
//! - the whole xpacket is a [`Metadata`](SegmentKind::Metadata) segment and an
//!   [`ItemKind::Xmp`] item;
//! - everything between is [`Other`](SegmentKind::Other) text. A gap is cut where the
//!   start tag of the first `<metadata>` ends, and the piece before the cut is named
//!   `Name::Id(1)`, so a writer finds where new metadata goes without scanning again.
//!
//! These boundaries are a function of the bytes, which a writer has to honour: what it
//! plans must be what parsing the output finds. A write is a splice. Text that is
//! kept is copied, so nothing is re-serialized, and only the new elements and, when a
//! manifest is written, the `xmlns:c2pa` declaration on the root element are new bytes.
//!
//! The manifest is stored as base64, so its item has the
//! [`Base64`](TransferEncoding::Base64) transfer encoding, which
//! [`Structure::read_content`](crate::Structure::read_content) undoes. [`Structure::store`](crate::Structure::store) does that for you.
//!
//! The document is parsed in one pass through a buffered reader (up to 256 MiB).
//! The reader retains its input window and current XML event, rather than a copy of
//! the complete document. A single XML event, such as a large text node, is still
//! buffered by quick-xml. A manifest that is not in `svg > metadata` is not one;
//! several are ambiguous, as in any container.

use std::{borrow::Cow, sync::Arc};

use quick_xml::{
    events::{BytesStart, Event},
    name::ResolveResult,
    NsReader, Reader,
};

use crate::{
    container_api::{
        BoxFuture, ContainerHandler, Existing, FormatSpec, Io, ItemInfo, MetadataSlot,
        MetadataUpdate, PlanBuilder, StructureBuilder, WritePlan, MAX_SEGMENT_SIZE,
    },
    jumbf::superbox_type,
    transfer::{base64_decode, base64_encode},
    ByteRange, Error, ItemKind, Name, Result, Role, Segment, SegmentId, SegmentKind, Structure,
    TransferEncoding, Updates,
};

const SVG_NS: &[u8] = b"http://www.w3.org/2000/svg";
const C2PA_NS: &[u8] = b"http://c2pa.org/manifest";
const XMP_ID: &[u8] = b"W5M0MpCehiHzreSzNTczkc9d";
const XPACKET: &[u8] = b"xpacket";
const MANIFEST_OPEN: &[u8] = b"<c2pa:manifest>";
const MANIFEST_CLOSE: &[u8] = b"</c2pa:manifest>";
const NS_DECL: &[u8] = b" xmlns:c2pa=\"http://c2pa.org/manifest\"";

/// The name of the text that ends with the start tag of `<metadata>`.
const METADATA_OPEN: Name = Name::Id(1);

/// How many characters of base64 hold the 32 bytes that give a JUMBF its type.
const TYPE_CHARS: usize = 44;

/// The SVG container handler.
#[derive(Debug, Clone, Copy, Default)]
pub struct SvgHandler;

/// The SVG handler.
pub fn handler() -> Arc<dyn ContainerHandler> {
    Arc::new(SvgHandler)
}

/// The SVG container's [`ContainerHandler::id`].
pub const ID: &str = "svg";

impl ContainerHandler for SvgHandler {
    // C2PA excludes only the base64 text; the enclosing tags stay hashed.
    fn c2pa_data_hash_exclusions(
        &self,
        _structure: &Structure,
        item: &crate::Item,
    ) -> Result<Vec<ByteRange>> {
        Ok(item.extents().map(|extent| extent.range()).collect())
    }

    fn id(&self) -> &'static str {
        ID
    }

    fn formats(&self) -> &[FormatSpec] {
        const F: &[FormatSpec] = &[
            FormatSpec::new("image/svg+xml", "svg").media_type_aliases(&["application/svg+xml"])
        ];
        F
    }

    // No `detect`: `<svg` near the start is not a signature, so SVG is found by
    // extension or media type only.

    fn parse_async(self: Arc<Self>, io: Io) -> BoxFuture<'static, Result<Structure>> {
        Box::pin(parse_with(self, io))
    }

    fn write_plan_async<'f, 'a: 'f>(
        &'f self,
        src_structure: &'f Structure,
        mut io: Io,
        updates: &'a Updates,
    ) -> BoxFuture<'f, Result<WritePlan<'a>>> {
        Box::pin(async move { plan(src_structure, &mut io, updates).await })
    }

    fn compose(&self, kind: ItemKind, data: &[u8]) -> Result<Vec<u8>> {
        match kind {
            ItemKind::Jumbf => {
                let text = base64_encode(data);
                let mut out = Vec::with_capacity(text.len() + 40);
                out.extend_from_slice(MANIFEST_OPEN);
                out.extend_from_slice(&text);
                out.extend_from_slice(MANIFEST_CLOSE);
                Ok(out)
            }
            ItemKind::Xmp => {
                check_packet(data)?;
                Ok(data.to_vec())
            }
            _ => Err(Error::UnsupportedFormat),
        }
    }
}

/// Parse an SVG into a validated structure.
#[cfg(test)]
fn parse<R: std::io::Read + std::io::Seek>(src: &mut R) -> Result<Structure> {
    handler().parse(src)
}

fn xml_error(e: impl std::fmt::Display) -> Error {
    Error::InvalidFormat(format!("SVG: XML is not well formed: {e}"))
}

// ---------------------------------------------------------------------------
// Scanning
// ---------------------------------------------------------------------------

/// Which of the elements that matter an element is, by where it is.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Kind {
    Svg,
    Metadata,
    Manifest,
    Other,
}

/// A `<c2pa:manifest>` element: where it starts and the lengths of its three parts.
#[derive(Clone, Copy)]
struct Element {
    start: u64,
    header: u64,
    payload: u64,
    trailer: u64,
    jumbf_type: Option<[u8; 16]>,
}

impl Element {
    fn end(&self) -> u64 {
        self.start + self.header + self.payload + self.trailer
    }
}

/// What the scan of a document found.
struct Scan {
    /// Where the root element's start tag ends.
    root_end: u64,
    /// Where the start tag of the first `<metadata>` of the root ends.
    metadata_end: Option<u64>,
    manifests: Vec<Element>,
    /// The xpackets, each from its begin to the end of its end.
    xmps: Vec<(u64, u64)>,
}

/// The namespace an element is in, as far as it matters.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Ns {
    Svg,
    C2pa,
    Other,
}

fn ns_of(bound: &ResolveResult<'_>) -> Ns {
    match bound {
        ResolveResult::Bound(n) if n.as_ref() == SVG_NS => Ns::Svg,
        ResolveResult::Bound(n) if n.as_ref() == C2PA_NS => Ns::C2pa,
        _ => Ns::Other,
    }
}

/// Whether `e` is the element called `local` in `want`. As for c2pa-rs, a name
/// written as `raw` counts too, whatever it is bound to.
fn named(e: &BytesStart<'_>, ns: Ns, want: Ns, local: &[u8], raw: &[u8]) -> bool {
    (ns == want && e.local_name().as_ref() == local) || e.name().as_ref() == raw
}

fn kind_at(depth: usize, path: &[Kind; 3], e: &BytesStart<'_>, ns: Ns) -> Kind {
    match depth {
        0 if named(e, ns, Ns::Svg, b"svg", b"svg") => Kind::Svg,
        1 if path[0] == Kind::Svg && named(e, ns, Ns::Svg, b"metadata", b"metadata") => {
            Kind::Metadata
        }
        2 if path[1] == Kind::Metadata && named(e, ns, Ns::C2pa, b"manifest", b"c2pa:manifest") => {
            Kind::Manifest
        }
        _ => Kind::Other,
    }
}

fn contains(hay: &[u8], needle: &[u8]) -> bool {
    hay.windows(needle.len()).any(|w| w == needle)
}

async fn scan(io: Io) -> Result<Scan> {
    let mut reader = NsReader::from_reader(tokio::io::BufReader::new(io.into_tokio_reader()));
    let mut buf = Vec::new();
    let mut depth = 0usize;
    let mut path = [Kind::Other; 3];
    let mut root_end = None;
    let mut metadata_end = None;
    let mut manifests: Vec<Element> = Vec::new();
    let mut open: Option<(u64, u64, Option<Vec<u8>>)> = None;
    let mut xmps = Vec::new();
    // Where an xpacket began and how deep, and how shallow the document has been
    // since. Until it ends we do not know whether it is an item. Whether or not it is
    // one, nothing can be written inside it: a new packet there would end it
    // somewhere else, so a `<metadata>` inside one is not a place to write.
    let mut begin: Option<(u64, usize)> = None;
    let mut low = usize::MAX;

    loop {
        let before = reader.buffer_position();
        let (bound, event) = reader
            .read_resolved_event_into_async(&mut buf)
            .await
            .map_err(xml_error)?;
        let ns = ns_of(&bound);
        let after = reader.buffer_position();
        if let Some((_, _, head)) = open.as_mut() {
            if head.as_ref().is_some_and(|head| head.len() < TYPE_CHARS) {
                match &event {
                    Event::Text(text) => {
                        if let Some(head) = head {
                            let remaining = TYPE_CHARS - head.len();
                            head.extend(
                                text.as_ref()
                                    .iter()
                                    .copied()
                                    .filter(|c| !c.is_ascii_whitespace())
                                    .take(remaining),
                            );
                        }
                    }
                    Event::End(_) if depth == 3 => {}
                    _ => *head = None,
                }
            }
        }
        match event {
            Event::Start(e) => {
                let first_root = depth == 0 && root_end.is_none();
                let kind = if depth == 0 && !first_root {
                    Kind::Other
                } else {
                    kind_at(depth, &path, &e, ns)
                };
                if first_root {
                    if kind != Kind::Svg {
                        return Err(Error::InvalidFormat(
                            "SVG: the root element is not svg".into(),
                        ));
                    }
                    root_end = Some(after);
                }
                if depth == 1 && kind == Kind::Metadata && begin.is_none() && metadata_end.is_none()
                {
                    metadata_end = Some(after);
                }
                if kind == Kind::Manifest {
                    open = Some((before, after, Some(Vec::with_capacity(TYPE_CHARS))));
                }
                if let Some(slot) = path.get_mut(depth) {
                    *slot = kind;
                }
                depth += 1;
            }
            Event::Empty(e) => {
                let first_root = depth == 0 && root_end.is_none();
                if first_root {
                    if kind_at(0, &path, &e, ns) != Kind::Svg {
                        return Err(Error::InvalidFormat(
                            "SVG: the root element is not svg".into(),
                        ));
                    }
                    root_end = Some(after);
                } else if kind_at(depth, &path, &e, ns) == Kind::Manifest {
                    manifests.push(Element {
                        start: before,
                        header: after - before,
                        payload: 0,
                        trailer: 0,
                        jumbf_type: None,
                    });
                }
            }
            Event::End(_) => {
                depth = depth
                    .checked_sub(1)
                    .ok_or_else(|| xml_error("an end tag with nothing open"))?;
                low = low.min(depth);
                if depth == 2 {
                    if let Some((start, header_end, head)) = open.take() {
                        manifests.push(Element {
                            start,
                            header: header_end - start,
                            payload: before - header_end,
                            trailer: after - before,
                            jumbf_type: head
                                .and_then(|head| base64_decode(&head).ok())
                                .and_then(|data| superbox_type(&data)),
                        });
                    }
                }
            }
            Event::PI(pi) => {
                let content: &[u8] = pi.as_ref();
                if contains(content, XPACKET) {
                    if contains(content, XMP_ID) {
                        // Not inside a manifest, which would be the outer item, and
                        // not before the root element, which would hold the document.
                        if begin.is_none() && open.is_none() && root_end.is_some() {
                            begin = Some((before, depth));
                            low = depth;
                        }
                    } else if let Some((b, at)) = begin.take() {
                        // Only a packet that opens and closes at one depth and never
                        // closes anything outside itself can be replaced without
                        // changing how the rest of the document nests.
                        if depth == at && low >= at {
                            xmps.push((b, after));
                            // What is inside an item is part of it, not an item.
                            manifests.retain(|m| m.start < b);
                        }
                    }
                }
            }
            Event::Eof => break,
            _ => {}
        }
        buf.clear();
    }
    if open.is_some() {
        return Err(Error::InvalidFormat(
            "SVG: a c2pa:manifest element is not closed".into(),
        ));
    }
    Ok(Scan {
        root_end: root_end.ok_or_else(|| Error::InvalidFormat("SVG: no root element".into()))?,
        metadata_end,
        manifests,
        xmps,
    })
}

/// What the plan needs to know about the root element, from its start tag.
struct Root {
    /// Where to insert an attribute: just before the `>`.
    attr_at: u64,
    has_c2pa_ns: bool,
    /// The prefix the root element is written with, `ns0` in `<ns0:svg>`.
    prefix: Option<String>,
    self_closing: bool,
}

fn root_info(header: &[u8]) -> Result<Root> {
    let mut reader = Reader::from_reader(header);
    loop {
        let event = reader.read_event().map_err(xml_error)?;
        let (e, self_closing) = match event {
            Event::Start(e) => (e, false),
            Event::Empty(e) => (e, true),
            Event::Eof => return Err(xml_error("no root element")),
            _ => continue,
        };
        let has_c2pa_ns = e
            .attributes()
            .filter_map(|a| a.ok())
            .any(|a| a.key.as_ref() == b"xmlns:c2pa");
        let prefix = e
            .name()
            .prefix()
            .map(|p| String::from_utf8_lossy(p.into_inner()).into_owned());
        return Ok(Root {
            attr_at: (header.len() as u64).saturating_sub(1),
            has_c2pa_ns,
            prefix,
            self_closing,
        });
    }
}

// ---------------------------------------------------------------------------
// Parsing
// ---------------------------------------------------------------------------

/// An element or packet the structure has a segment for.
#[derive(Clone, Copy)]
struct Span {
    xmp: bool,
    el: Element,
}

async fn parse_with(handler: Arc<dyn ContainerHandler>, io: Io) -> Result<Structure> {
    let total = io.len();
    if total > MAX_SEGMENT_SIZE {
        return Err(Error::LimitExceeded {
            what: "SVG size",
            limit: MAX_SEGMENT_SIZE,
        });
    }
    let sc = scan(io).await?;

    // Items do not overlap: what is inside one is part of it.
    let mut spans: Vec<Span> = sc
        .manifests
        .iter()
        .map(|&el| Span { xmp: false, el })
        .collect();
    spans.extend(sc.xmps.iter().map(|&(s, e)| Span {
        xmp: true,
        el: Element {
            start: s,
            header: 0,
            payload: e - s,
            trailer: 0,
            jumbf_type: None,
        },
    }));
    spans.sort_by_key(|s| s.el.start);
    // The cut after `<metadata>` must not fall inside a span.
    let cut = sc
        .metadata_end
        .filter(|&m| !spans.iter().any(|s| s.el.start < m && m < s.el.end()));

    let mut b = StructureBuilder::new(handler, "image/svg+xml", total);
    b.push_span(
        SegmentKind::Preamble,
        Name::None,
        u32::try_from(sc.root_end).map_err(|_| Error::LimitExceeded {
            what: "SVG header size",
            limit: u32::MAX as u64,
        })?,
        0,
        0,
    )?;
    let mut at = sc.root_end;
    for s in &spans {
        gap(&mut b, at, s.el.start, cut)?;
        let (h, p, t) = (
            u32::try_from(s.el.header).map_err(|_| too_long())?,
            s.el.payload,
            u16::try_from(s.el.trailer).map_err(|_| too_long())?,
        );
        if s.xmp {
            b.push_item(SegmentKind::Metadata, Name::None, h, p, t, ItemInfo::xmp())?;
        } else {
            let id = b.push_span(SegmentKind::Metadata, Name::None, h, p, t)?;
            // An empty element holds no manifest.
            if p > 0 {
                b.item_of_segments(
                    ItemInfo::jumbf()
                        .jumbf_type(s.el.jumbf_type)
                        .transfer(TransferEncoding::Base64),
                    &[id],
                )?;
            }
        }
        at = s.el.end();
    }
    gap(&mut b, at, total, cut)?;
    b.finish()
}

fn too_long() -> Error {
    Error::LimitExceeded {
        what: "SVG element tag size",
        limit: u32::MAX as u64,
    }
}

/// The text from `from` to `to` as one segment, or two where `cut` falls in it.
fn gap(b: &mut StructureBuilder, from: u64, to: u64, cut: Option<u64>) -> Result<()> {
    if let Some(c) = cut.filter(|&c| from < c && c <= to) {
        b.push_span(SegmentKind::Other, METADATA_OPEN, 0, c - from, 0)?;
        if c < to {
            b.push_span(SegmentKind::Other, Name::None, 0, to - c, 0)?;
        }
    } else if from < to {
        b.push_span(SegmentKind::Other, Name::None, 0, to - from, 0)?;
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Writing
// ---------------------------------------------------------------------------

/// Part of a run of text: kept source bytes or new ones.
enum Piece<'a> {
    Copy(ByteRange),
    Put(Cow<'a, [u8]>),
}

impl Piece<'_> {
    fn len(&self) -> u64 {
        match self {
            Piece::Copy(r) => r.len(),
            Piece::Put(d) => d.len() as u64,
        }
    }
}

/// Emit the run as one segment of `kind` and `name`, with its bytes in `role`.
fn flush<'a>(
    b: &mut PlanBuilder<'_, 'a>,
    run: &mut Vec<Piece<'a>>,
    kind: SegmentKind,
    name: Name,
    role: Role,
) -> Result<()> {
    let len: u64 = run.iter().map(Piece::len).sum();
    if len == 0 {
        run.clear();
        return Ok(());
    }
    let (header, payload) = if role == Role::Header {
        (
            u32::try_from(len).map_err(|_| Error::LimitExceeded {
                what: "SVG header size",
                limit: u32::MAX as u64,
            })?,
            0,
        )
    } else {
        (0, len)
    };
    let id = b.shape(kind, name, header, payload, 0)?;
    for piece in run.drain(..) {
        match piece {
            Piece::Copy(r) if !r.is_empty() => {
                b.copy(id, role, r);
            }
            Piece::Put(d) if !d.is_empty() => {
                b.put(id, role, d);
            }
            _ => {}
        }
    }
    Ok(())
}

fn put_manifest<'a>(b: &mut PlanBuilder<'_, 'a>, jumbf: &[u8]) -> Result<()> {
    let id = b.put_segment(
        SegmentKind::Metadata,
        Name::None,
        MANIFEST_OPEN,
        base64_encode(jumbf),
        MANIFEST_CLOSE,
    )?;
    b.item(
        ItemInfo::jumbf()
            .jumbf_type(superbox_type(jumbf))
            .transfer(TransferEncoding::Base64),
        &[id],
    )
}

fn put_xmp<'a>(b: &mut PlanBuilder<'_, 'a>, packet: &'a [u8]) -> Result<()> {
    let id = b.put_segment(SegmentKind::Metadata, Name::None, &[][..], packet, &[][..])?;
    b.item(ItemInfo::xmp(), &[id])
}

/// What a source segment holds: an XMP packet, a manifest element, or text. A
/// metadata segment that is not XMP is a manifest element, including an empty one,
/// which holds no item.
fn held(src: &Structure, id: SegmentId, seg: &Segment) -> Option<ItemKind> {
    if src.items_in(id).any(|e| e.kind() == ItemKind::Xmp) {
        Some(ItemKind::Xmp)
    } else if seg.kind() == SegmentKind::Metadata {
        Some(ItemKind::Jumbf)
    } else {
        None
    }
}

/// Decide what the output contains, and describe how to write it.
async fn plan<'a>(src: &Structure, io: &mut Io, updates: &'a Updates) -> Result<WritePlan<'a>> {
    let segs = src.segments();
    let first = segs
        .first()
        .filter(|s| s.kind() == SegmentKind::Preamble)
        .ok_or_else(|| Error::InvalidFormat("SVG: structure has no root element".into()))?;
    let mut has_xmp = false;
    let mut has_manifest = false;
    for (i, seg) in segs.iter().enumerate() {
        match held(src, SegmentId::from_index(i)?, seg) {
            Some(ItemKind::Xmp) => has_xmp = true,
            Some(_) => has_manifest = true,
            None => {}
        }
    }
    let has_open = segs.iter().any(|s| s.name() == METADATA_OPEN);

    if let MetadataUpdate::Set(d) = updates.xmp() {
        check_packet(d)?;
    }
    let sets_manifest = matches!(updates.jumbf(), MetadataUpdate::Set(_));
    if let MetadataUpdate::Set(d) = updates.jumbf() {
        if d.is_empty() {
            return Err(Error::InvalidFormat("SVG: JUMBF is empty".into()));
        }
    }
    let new_xmp = !has_xmp && matches!(updates.xmp(), MetadataUpdate::Set(_));
    let new_manifest = !has_manifest && sets_manifest;
    let insert = new_xmp || new_manifest;
    let wrap = insert && !has_open;

    // The root element's start tag, for where to declare the namespace and how to
    // write `<metadata>`.
    let root = if sets_manifest || wrap {
        let header = io.read_vec(0, first.range().len() as usize).await?;
        Some(root_info(&header)?)
    } else {
        None
    };
    if wrap && root.as_ref().is_some_and(|r| r.self_closing) {
        return Err(Error::InvalidFormat(
            "SVG: the root element is empty, so there is nowhere to put metadata".into(),
        ));
    }

    let mut xmp = MetadataSlot::new(updates.xmp());
    let mut jumbf = MetadataSlot::new(updates.jumbf());
    let mut b = PlanBuilder::new(src);
    let mut run: Vec<Piece<'a>> = Vec::new();

    // The root's start tag, with the declaration of the C2PA namespace added if a
    // manifest is written and it is not there.
    let end = first.range().len();
    match root.as_ref().filter(|r| sets_manifest && !r.has_c2pa_ns) {
        Some(r) => {
            run.push(Piece::Copy(ByteRange::new(0, r.attr_at)?));
            run.push(Piece::Put(Cow::Borrowed(NS_DECL)));
            run.push(Piece::Copy(ByteRange::new(r.attr_at, end - r.attr_at)?));
        }
        None => run.push(Piece::Copy(ByteRange::new(0, end)?)),
    }
    flush(
        &mut b,
        &mut run,
        SegmentKind::Preamble,
        Name::None,
        Role::Header,
    )?;

    let new_items = |b: &mut PlanBuilder<'_, 'a>,
                     xmp: &mut MetadataSlot<'a>,
                     jumbf: &mut MetadataSlot<'a>|
     -> Result<()> {
        if !has_xmp {
            if let Some(d) = xmp.pending() {
                put_xmp(b, d)?;
            }
        }
        if !has_manifest {
            if let Some(d) = jumbf.pending() {
                put_manifest(b, d)?;
            }
        }
        Ok(())
    };

    // No `<metadata>` to put them in: make one, right after the root's start tag.
    if wrap {
        let qname = match root.as_ref().and_then(|r| r.prefix.as_deref()) {
            Some(p) => format!("{p}:metadata"),
            None => "metadata".to_owned(),
        };
        run.push(Piece::Put(Cow::Owned(format!("<{qname}>").into_bytes())));
        flush(
            &mut b,
            &mut run,
            SegmentKind::Other,
            METADATA_OPEN,
            Role::Payload,
        )?;
        new_items(&mut b, &mut xmp, &mut jumbf)?;
        run.push(Piece::Put(Cow::Owned(format!("</{qname}>").into_bytes())));
    }

    for (i, seg) in segs.iter().enumerate().skip(1) {
        let id = SegmentId::from_index(i)?;
        match held(src, id, seg) {
            Some(ItemKind::Xmp) => match xmp.existing() {
                Existing::Keep => {
                    flush(
                        &mut b,
                        &mut run,
                        SegmentKind::Other,
                        Name::None,
                        Role::Payload,
                    )?;
                    b.copy_segment(id)?;
                }
                Existing::Replace(d) => {
                    flush(
                        &mut b,
                        &mut run,
                        SegmentKind::Other,
                        Name::None,
                        Role::Payload,
                    )?;
                    put_xmp(&mut b, d)?;
                }
                _ => {}
            },
            Some(_) => match jumbf.existing() {
                Existing::Keep => {
                    flush(
                        &mut b,
                        &mut run,
                        SegmentKind::Other,
                        Name::None,
                        Role::Payload,
                    )?;
                    b.copy_segment(id)?;
                }
                Existing::Replace(d) => {
                    flush(
                        &mut b,
                        &mut run,
                        SegmentKind::Other,
                        Name::None,
                        Role::Payload,
                    )?;
                    put_manifest(&mut b, d)?;
                }
                _ => {}
            },
            _ => {
                run.push(Piece::Copy(seg.range()));
                if seg.name() == METADATA_OPEN {
                    flush(
                        &mut b,
                        &mut run,
                        SegmentKind::Other,
                        METADATA_OPEN,
                        Role::Payload,
                    )?;
                    if insert {
                        new_items(&mut b, &mut xmp, &mut jumbf)?;
                    }
                }
            }
        }
    }
    flush(
        &mut b,
        &mut run,
        SegmentKind::Other,
        Name::None,
        Role::Payload,
    )?;
    b.carry_items(|_| true);
    b.finish()
}

/// Whether `packet` is an xpacket that reads back as one XMP item: it begins and ends
/// with the packet's processing instructions, holds no other, and its elements nest.
fn check_packet(packet: &[u8]) -> Result<()> {
    let bad = |why: &str| Error::InvalidFormat(format!("SVG: XMP is not an xpacket: {why}"));
    if !packet.starts_with(b"<?xpacket") || !packet.ends_with(b"?>") {
        return Err(bad("it must begin and end with the xpacket instructions"));
    }
    let mut reader = Reader::from_reader(packet);
    let (mut depth, mut packets, mut first) = (0i64, 0, true);
    loop {
        match reader.read_event().map_err(xml_error)? {
            Event::Start(_) => depth += 1,
            Event::End(_) => depth -= 1,
            Event::PI(pi) => {
                let content: &[u8] = pi.as_ref();
                if contains(content, XPACKET) {
                    if first && !contains(content, XMP_ID) {
                        return Err(bad("the first instruction is not the XMP packet's"));
                    }
                    first = false;
                    packets += 1;
                }
            }
            Event::Eof => break,
            _ => {}
        }
        if depth < 0 {
            return Err(bad("an end tag has nothing to close"));
        }
    }
    if depth != 0 || packets != 2 {
        return Err(bad(
            "elements must nest and there must be one begin and one end",
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use super::*;
    use crate::{container_api, testing::Conformance, NullSink};

    const NS: &str = "http://www.w3.org/2000/svg";
    const PACKET: &str = "<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\
        <x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF \
        xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"/></x:xmpmeta>\
        <?xpacket end=\"w\"?>";

    /// A JUMBF of `n` bytes that has a description box, so it has a type.
    fn jumbf(n: usize) -> Vec<u8> {
        let mut v: Vec<u8> = (0..n).map(|i| (i * 7 % 251) as u8).collect();
        v[0..4].copy_from_slice(&(n as u32).to_be_bytes());
        v[4..8].copy_from_slice(b"jumb");
        v[8..12].copy_from_slice(&((n - 8) as u32).to_be_bytes());
        v[12..16].copy_from_slice(b"jumd");
        v[16..32].copy_from_slice(&[0xc2; 16]);
        v
    }

    fn b64(data: &[u8]) -> String {
        String::from_utf8(base64_encode(data)).unwrap()
    }

    fn plain() -> String {
        format!(r#"<svg xmlns="{NS}" width="10" height="10"><rect width="10" height="10"/></svg>"#)
    }

    fn with_manifest(text: &str) -> String {
        format!(
            r#"<svg xmlns="{NS}" xmlns:c2pa="http://c2pa.org/manifest" width="10"><metadata><c2pa:manifest>{text}</c2pa:manifest></metadata><rect/></svg>"#
        )
    }

    fn parsed(svg: &str) -> Structure {
        parse(&mut Cursor::new(svg.as_bytes())).unwrap()
    }

    fn rewrite(svg: &str, u: &Updates) -> Result<String> {
        let s = parse(&mut Cursor::new(svg.as_bytes()))?;
        let mut out = Vec::new();
        s.write(&mut Cursor::new(svg.as_bytes()), &mut out, u, &mut NullSink)?;
        Ok(String::from_utf8(out).unwrap())
    }

    fn store(svg: &str) -> Option<Vec<u8>> {
        parsed(svg).store(&mut Cursor::new(svg.as_bytes())).unwrap()
    }

    #[test]
    fn a_manifest_that_is_not_base64_has_no_type() {
        let svg = with_manifest("this is not base64 at all");
        let s = parsed(&svg);
        let item = s.require_item(ItemKind::Jumbf).unwrap();
        assert_eq!(
            s.jumbf_type(&mut Cursor::new(svg.as_bytes()), item)
                .unwrap(),
            None
        );
    }

    #[test]
    fn a_manifest_type_is_found_across_large_whitespace_runs() {
        let encoded = b64(&jumbf(64));
        let text = format!(
            "{}{}{}",
            &encoded[..8],
            " ".repeat(crate::io::DEFAULT_WINDOW + 1),
            &encoded[8..]
        );
        let svg = with_manifest(&text);
        let s = parsed(&svg);

        assert_eq!(
            s.require_item(ItemKind::Jumbf).unwrap().jumbf_type(),
            Some([0xc2; 16])
        );
    }

    #[test]
    fn parsing_reads_svg_in_bounded_windows() {
        use crate::task::{Progress, Task};

        let svg = format!(r#"<svg xmlns="{NS}">{}</svg>"#, "<g/>".repeat(20_000));
        let mut task = Task::new(svg.len() as u64, |io| async move {
            parse_with(handler(), io).await
        });
        let mut requests = 0;
        let mut max_window = 0;
        let structure = loop {
            match task.resume().unwrap() {
                Progress::Read(mut req) => {
                    requests += 1;
                    max_window = max_window.max(req.window_len());
                    let start = req.offset() as usize;
                    let end = (start + req.window_len()).min(svg.len());
                    req.buffer().extend_from_slice(&svg.as_bytes()[start..end]);
                }
                Progress::Done(result) => break result,
            }
        };

        assert_eq!(structure.container_id(), ID);
        assert!(requests > 1);
        assert!(max_window <= crate::io::DEFAULT_WINDOW);
    }

    #[test]
    fn conforms() {
        let c = Conformance::new(handler()).jumbf(Some(jumbf(200)));
        c.check("plain", plain().as_bytes());
        c.check(
            "prefixed root",
            format!(r#"<ns0:svg xmlns:ns0="{NS}"><ns0:rect/></ns0:svg>"#).as_bytes(),
        );
        c.check(
            "with metadata",
            format!(r#"<svg xmlns="{NS}"><metadata><title>t</title></metadata><rect/></svg>"#)
                .as_bytes(),
        );
        c.check("manifest", with_manifest(&b64(&jumbf(100))).as_bytes());
        c.check(
            "manifest and xmp",
            format!(
                r#"<?xml version="1.0"?><!-- c --><!DOCTYPE svg><svg xmlns="{NS}" xmlns:c2pa="http://c2pa.org/manifest"><metadata>
  {PACKET}
  <c2pa:manifest>{}</c2pa:manifest>
</metadata><g/></svg>
"#,
                b64(&jumbf(64))
            )
            .as_bytes(),
        );
        c.check(
            "xmp outside metadata",
            format!(r#"<svg xmlns="{NS}">{PACKET}<metadata/></svg>"#).as_bytes(),
        );
        c.check(
            "empty manifest element",
            format!(
                r#"<svg xmlns="{NS}" xmlns:c2pa="http://c2pa.org/manifest"><metadata><c2pa:manifest/></metadata></svg>"#
            )
            .as_bytes(),
        );
    }

    #[test]
    fn a_manifest_is_a_header_a_payload_and_a_trailer() {
        let j = jumbf(100);
        let text = b64(&j);
        let svg = with_manifest(&text);
        let s = parsed(&svg);
        let seg = s
            .segments()
            .iter()
            .find(|g| g.kind() == SegmentKind::Metadata)
            .unwrap();
        let at = |r: ByteRange| &svg.as_bytes()[r.offset() as usize..r.end() as usize];
        assert_eq!(at(seg.header()), MANIFEST_OPEN);
        assert_eq!(at(seg.payload()), text.as_bytes());
        assert_eq!(at(seg.trailer()), MANIFEST_CLOSE);

        // The item is stored as text; its data is what that decodes to.
        let e = s.require_item(ItemKind::Jumbf).unwrap();
        assert_eq!(e.jumbf_type(), Some([0xc2; 16]));
        assert_eq!(
            s.read_item(&mut Cursor::new(svg.as_bytes()), e).unwrap(),
            text.as_bytes()
        );
        assert_eq!(store(&svg).unwrap(), j);
        assert_eq!(*e.transfer(), TransferEncoding::Base64);
        assert_eq!(
            s.read_content(&mut Cursor::new(svg.as_bytes()), e).unwrap(),
            j
        );
        // Without a recorded type, the type is read through the transfer encoding.
        let mut builder = StructureBuilder::new(handler(), "image/svg+xml", text.len() as u64);
        builder
            .push_item(
                SegmentKind::Metadata,
                Name::None,
                0,
                text.len() as u64,
                0,
                container_api::item_info(e).clone().jumbf_type(None),
            )
            .unwrap();
        let untyped = builder.finish().unwrap();
        assert_eq!(
            untyped
                .jumbf_type(
                    &mut Cursor::new(text.as_bytes()),
                    untyped.require_item(ItemKind::Jumbf).unwrap(),
                )
                .unwrap(),
            Some([0xc2; 16])
        );
    }

    #[test]
    fn the_text_before_metadata_ends_is_named() {
        let s = parsed(&format!(
            r#"<svg xmlns="{NS}"><defs/><metadata><a/></metadata></svg>"#
        ));
        let names: Vec<_> = s.segments().iter().map(|g| g.name()).collect();
        assert_eq!(names, [Name::None, METADATA_OPEN, Name::None]);
        assert_eq!(
            s.segments()[1].range().len(),
            "<defs/><metadata>".len() as u64
        );
    }

    #[test]
    fn a_new_manifest_is_spliced_in_and_the_root_declares_the_namespace() {
        let j = jumbf(40);
        let out = rewrite(&plain(), &Updates::new().set_jumbf(j.clone())).unwrap();
        let want = format!(
            r#"<svg xmlns="{NS}" width="10" height="10" xmlns:c2pa="http://c2pa.org/manifest"><metadata><c2pa:manifest>{}</c2pa:manifest></metadata><rect width="10" height="10"/></svg>"#,
            b64(&j)
        );
        assert_eq!(out, want);
        assert_eq!(store(&out).unwrap(), j);
    }

    #[test]
    fn metadata_takes_the_roots_prefix_and_a_declared_namespace_is_not_repeated() {
        let svg = format!(
            r#"<ns0:svg xmlns:ns0="{NS}" xmlns:c2pa="http://c2pa.org/manifest"><ns0:rect/></ns0:svg>"#
        );
        let out = rewrite(&svg, &Updates::new().set_jumbf(jumbf(40))).unwrap();
        assert!(out.contains("<ns0:metadata><c2pa:manifest>"), "{out}");
        assert!(out.contains("</c2pa:manifest></ns0:metadata>"), "{out}");
        assert_eq!(out.matches("xmlns:c2pa").count(), 1);
    }

    #[test]
    fn an_existing_manifest_is_replaced_where_it_is_and_removal_leaves_the_rest() {
        let svg = with_manifest(&b64(&jumbf(100)));
        let new = jumbf(60);
        let out = rewrite(&svg, &Updates::new().set_jumbf(new.clone())).unwrap();
        assert_eq!(out, with_manifest(&b64(&new)));

        let out = rewrite(&svg, &Updates::new().remove_jumbf()).unwrap();
        assert_eq!(
            out,
            format!(
                r#"<svg xmlns="{NS}" xmlns:c2pa="http://c2pa.org/manifest" width="10"><metadata></metadata><rect/></svg>"#
            )
        );
        assert_eq!(rewrite(&svg, &Updates::new()).unwrap(), svg);
    }

    #[test]
    fn xmp_is_replaced_in_place_or_added_to_metadata() {
        let svg = format!(r#"<svg xmlns="{NS}"><metadata>{PACKET}</metadata></svg>"#);
        let other = PACKET.replace("rdf:RDF", "rdf:RDF a=\"1\"");
        let out = rewrite(&svg, &Updates::new().set_xmp(other.clone().into_bytes())).unwrap();
        assert_eq!(out, svg.replace(PACKET, &other));

        let out = rewrite(
            &plain(),
            &Updates::new().set_xmp(PACKET.as_bytes().to_vec()),
        )
        .unwrap();
        assert!(
            out.contains(&format!("<metadata>{PACKET}</metadata>")),
            "{out}"
        );
        let s = parsed(&out);
        assert_eq!(
            s.xmp(&mut Cursor::new(out.as_bytes())).unwrap().unwrap(),
            PACKET.as_bytes()
        );
    }

    #[test]
    fn an_xpacket_that_would_change_the_nesting_is_not_xmp() {
        // Found by fuzzing. Replacing a packet with unclosed elements in it would
        // change what the rest of the document is nested in, so it is left as text.
        let svg = format!(
            r#"<svg xmlns="{NS}" xmlns:c2pa="http://c2pa.org/manifest"><metadata><?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?><x:xmpmeta><?xpacket end="w"?><c2pa:manifest>QUJD</c2pa:manifest>"#
        );
        let s = parsed(&svg);
        assert!(s.items_of(ItemKind::Xmp).next().is_none());
        let c = Conformance::new(handler()).jumbf(Some(jumbf(64)));
        c.check("unbalanced xpacket", svg.as_bytes());

        // A packet that closes more than it opens is the same.
        let svg = format!(
            r#"<svg xmlns="{NS}"><g><metadata/><?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?></g><g><?xpacket end="w"?></g></svg>"#
        );
        assert!(parsed(&svg).items_of(ItemKind::Xmp).next().is_none());
        c.check("packet across elements", svg.as_bytes());

        // Found by fuzzing: a packet that never ends swallows what follows it, so a
        // `<metadata>` after its start is no place to put a new one.
        let svg = format!(
            r#"<svg xmlns="{NS}"><g><?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?></g><metadata></metadata></svg>"#
        );
        assert!(parsed(&svg).items_of(ItemKind::Xmp).next().is_none());
        c.check("packet that never ends", svg.as_bytes());

        // Nor is one inside a packet that ends but is not an item.
        let svg = format!(
            r#"<svg xmlns="{NS}"><?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?><metadata></metadata></svg><g><?xpacket end="w"?></g>"#
        );
        c.check_if_parses("packet that ends elsewhere", svg.as_bytes());
        let svg = format!(
            r#"<svg xmlns="{NS}"><g><?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?></g><metadata></metadata><g><?xpacket end="w"?></g></svg>"#
        );
        assert!(parsed(&svg).items_of(ItemKind::Xmp).next().is_none());
        c.check(
            "packet across elements, with metadata inside",
            svg.as_bytes(),
        );
    }

    #[test]
    fn every_xpacket_is_xmp_and_what_is_inside_an_item_is_not_one() {
        // Found by fuzzing: removing the first xpacket must not reveal a second.
        let p = r#"<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?><a/><?xpacket end="w"?>"#;
        let svg = format!(r#"<svg xmlns="{NS}">{p}<g/>{p}</svg>"#);
        let s = parsed(&svg);
        assert_eq!(s.items_of(ItemKind::Xmp).count(), 2);
        assert!(matches!(
            s.xmp(&mut Cursor::new(svg.as_bytes())),
            Err(Error::Ambiguous { count: 2, .. })
        ));
        let out = rewrite(&svg, &Updates::new().remove_xmp()).unwrap();
        assert_eq!(out, format!(r#"<svg xmlns="{NS}"><g/></svg>"#));
        assert_eq!(parsed(&out).items_of(ItemKind::Xmp).count(), 0);
        Conformance::new(handler()).check("two packets", svg.as_bytes());

        // A manifest inside a packet is part of the packet; a packet inside a
        // manifest is part of the manifest. Removing the outer one takes the inner.
        let svg = format!(
            r#"<svg xmlns="{NS}" xmlns:c2pa="http://c2pa.org/manifest"><metadata><?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?><c2pa:manifest>QUJD</c2pa:manifest><?xpacket end="w"?></metadata></svg>"#
        );
        let s = parsed(&svg);
        assert_eq!(s.items_of(ItemKind::Xmp).count(), 1);
        assert_eq!(s.items_of(ItemKind::Jumbf).count(), 0);
        let c = Conformance::new(handler()).jumbf(Some(jumbf(64)));
        c.check("manifest inside a packet", svg.as_bytes());

        let svg = format!(
            r#"<svg xmlns="{NS}" xmlns:c2pa="http://c2pa.org/manifest"><metadata><c2pa:manifest><?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?><?xpacket end="w"?></c2pa:manifest></metadata></svg>"#
        );
        let s = parsed(&svg);
        assert_eq!(s.items_of(ItemKind::Xmp).count(), 0);
        c.check("packet inside a manifest", svg.as_bytes());

        // A packet that holds the whole document, or the first metadata, hides them.
        let svg = format!(
            r#"<svg xmlns="{NS}"><?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?><metadata><x/></metadata><?xpacket end="w"?><metadata/></svg>"#
        );
        c.check("metadata inside a packet", svg.as_bytes());
    }

    #[test]
    fn several_manifests_are_ambiguous_and_removal_takes_them_all() {
        let one = "<c2pa:manifest>QUJD</c2pa:manifest>";
        let svg = format!(
            r#"<svg xmlns="{NS}" xmlns:c2pa="http://c2pa.org/manifest"><metadata>{one}{one}</metadata></svg>"#
        );
        let s = parsed(&svg);
        assert!(matches!(
            s.store(&mut Cursor::new(svg.as_bytes())),
            Err(Error::Ambiguous { count: 2, .. })
        ));
        let out = rewrite(&svg, &Updates::new().remove_jumbf()).unwrap();
        assert!(!out.contains("<c2pa:manifest"), "{out}");
        // A new one replaces the first and drops the rest.
        let out = rewrite(&svg, &Updates::new().set_jumbf(jumbf(40))).unwrap();
        assert_eq!(out.matches("<c2pa:manifest>").count(), 1);
    }

    #[test]
    fn a_manifest_that_is_not_in_the_roots_metadata_is_not_one() {
        let svg = format!(
            r#"<svg xmlns="{NS}" xmlns:c2pa="http://c2pa.org/manifest"><g><metadata><c2pa:manifest>QUJD</c2pa:manifest></metadata></g></svg>"#
        );
        assert!(store(&svg).is_none());
        assert!(parsed(&svg).require_item(ItemKind::Jumbf).is_err());
    }

    #[test]
    fn a_placeholder_is_filled_in_place() {
        let placeholder = jumbf(90);
        let svg = with_manifest(&b64(&placeholder));
        let s = parsed(&svg);
        let e = s.require_item(ItemKind::Jumbf).unwrap();
        let signed = jumbf(90).iter().map(|b| b ^ 0x55).collect::<Vec<_>>();
        let mut cur = Cursor::new(svg.clone().into_bytes());
        s.patch_exact(&mut cur, e, &signed).unwrap();
        let out = String::from_utf8(cur.into_inner()).unwrap();
        assert_eq!(out, with_manifest(&b64(&signed)));

        // The length that has to match is the stored one.
        let mut cur = Cursor::new(svg.into_bytes());
        assert!(s.patch_exact(&mut cur, e, &signed[..80]).is_err());
    }

    #[test]
    fn what_cannot_be_written_is_refused() {
        // Not SVG.
        assert!(parse(&mut Cursor::new(&b"<html><body/></html>"[..])).is_err());
        assert!(parse(&mut Cursor::new(&b"not xml"[..])).is_err());
        // A manifest that is never closed.
        let open = format!(r#"<svg xmlns="{NS}"><metadata><c2pa:manifest>QU"#);
        assert!(parse(&mut Cursor::new(open.as_bytes())).is_err());

        // XMP that is not an xpacket, and an empty store.
        assert!(rewrite(&plain(), &Updates::new().set_xmp(b"<x:xmpmeta/>".to_vec())).is_err());
        assert!(rewrite(&plain(), &Updates::new().set_jumbf(Vec::new())).is_err());

        // An empty root has nowhere to put metadata, but can be kept.
        let empty = format!(r#"<svg xmlns="{NS}"/>"#);
        assert!(rewrite(&empty, &Updates::new().set_jumbf(jumbf(40))).is_err());
        assert_eq!(rewrite(&empty, &Updates::new()).unwrap(), empty);
    }

    #[test]
    fn compose_is_what_a_write_inserts() {
        let j = jumbf(40);
        let element = handler().compose(ItemKind::Jumbf, &j).unwrap();
        let out = rewrite(&plain(), &Updates::new().set_jumbf(j)).unwrap();
        assert!(contains(out.as_bytes(), &element));
        assert!(handler().compose(ItemKind::Xmp, b"<x/>").is_err());
    }

    #[test]
    fn a_hash_skips_exactly_the_base64_text() {
        // What a C2PA data hash excludes: the payload of the manifest segment.
        let j = jumbf(100);
        let svg = with_manifest(&b64(&j));
        let s = parsed(&svg);
        let e = s.require_item(ItemKind::Jumbf).unwrap();
        let r = e.extents().next().unwrap().range();
        let before = &svg.as_bytes()[..r.offset() as usize];
        assert!(before.ends_with(MANIFEST_OPEN));
        let after = &svg.as_bytes()[r.end() as usize..];
        assert!(after.starts_with(MANIFEST_CLOSE));
        assert_eq!(r.len() as usize, base64_encode(&j).len());
    }
}