asset-io 0.3.2

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
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
// 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.

//! Validated container structure.

use std::{
    borrow::Cow,
    io::{Read, Seek, SeekFrom, Write},
    sync::Arc,
};

use crate::{
    error::{Error, Result},
    handler::{ContainerHandler, ReadSeek, ReadWriteSeek},
    io::Io,
    item::{Extent, Item, ItemInfo, ItemKind},
    range::ByteRange,
    segment::{Name, Role, Segment, SegmentKind, DEFAULT_CHUNK_SIZE, MAX_SEGMENT_SIZE},
    sink::{Chunk, Sink},
    task::block_on,
    transfer::TransferEncoding,
    walk::Node,
};

/// Upper bound on segments per asset. Bounds memory use on hostile inputs
/// made of many tiny elements.
pub const MAX_SEGMENTS: usize = 1 << 22;

/// Index of a segment within its [`Structure`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SegmentId(u32);

impl SegmentId {
    /// The id of the segment at position `i` in [`Structure::segments`]. The index
    /// is not checked against any structure; [`Structure::segment`] does that.
    pub fn from_index(i: usize) -> Result<Self> {
        u32::try_from(i)
            .map(SegmentId)
            .map_err(|_| Error::LimitExceeded {
                what: "segment count",
                limit: u32::MAX as u64,
            })
    }

    /// Position in [`Structure::segments`].
    pub fn index(self) -> usize {
        self.0 as usize
    }
}

/// One independently valid piece of a multi-part asset, such as one image of a
/// Multi-Picture Format file.
///
/// Sub-assets are contiguous, in file order, and together cover every byte of the
/// asset, so they can be listed as the parts of a C2PA multi-asset hash. A
/// [`Structure`] always has at least one: the primary asset, which is the whole
/// file when nothing else is embedded.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SubAsset {
    range: ByteRange,
    segments: std::ops::Range<usize>,
    media_type: Option<Cow<'static, str>>,
    primary: bool,
}

impl SubAsset {
    /// Where the sub-asset lies in the asset: absolute offset and length.
    pub fn range(&self) -> ByteRange {
        self.range
    }

    /// Indices (see [`SegmentId::index`]) of the segments the sub-asset is made of.
    pub fn segments(&self) -> std::ops::Range<usize> {
        self.segments.clone()
    }

    /// Media type of the sub-asset, or `None` when the container cannot tell (trailing
    /// data after the last image).
    pub fn media_type(&self) -> Option<&str> {
        self.media_type.as_deref()
    }

    /// Whether this is the primary asset, the first sub-asset.
    pub fn is_primary(&self) -> bool {
        self.primary
    }

    /// `offset` relative to the start of the sub-asset, or `None` if it is outside
    /// it. Hash exclusion ranges of a sub-asset are relative to the sub-asset.
    pub fn relative(&self, offset: u64) -> Option<u64> {
        (self.range.offset()..self.range.end())
            .contains(&offset)
            .then(|| offset - self.range.offset())
    }
}

/// One box of a C2PA box hash; see [`Structure::c2pa_boxes`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct C2paBox {
    /// The name the hash lists the box under.
    pub name: Cow<'static, str>,
    /// Where the box is.
    pub range: ByteRange,
    /// The ranges inside the box that hold asset metadata (XMP, EXIF), which a box
    /// hash may exclude (C2PA 2.4, 15.12.3).
    pub metadata: Vec<ByteRange>,
}

/// A region of the file with a role, in file order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Region {
    /// Owning segment.
    pub segment: SegmentId,
    /// Header, payload or trailer.
    pub role: Role,
    /// Byte range.
    pub range: ByteRange,
}

/// The parsed structure of an asset.
///
/// Invariants, enforced by [`StructureBuilder`]:
/// - `segments` are in file order and tile `[0, total_size)` exactly;
/// - no segment is empty and each fits `header + trailer <= range`;
/// - every item extent lies inside the segment it names.
///
/// Something a container keeps with a structure for its own use; see
/// [`StructureBuilder::attach`].
pub(crate) trait Attached: std::any::Any + std::fmt::Debug + Send + Sync {
    fn as_any(&self) -> &dyn std::any::Any;
}

impl<T: std::any::Any + std::fmt::Debug + Send + Sync> Attached for T {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// A `Structure` holds geometry, and whatever opaque state its container attached
/// to it (see [`attachment`](crate::container_api::attachment)). It is `Send + Sync` and can be
/// shared across threads for parallel reads.
#[derive(Debug)]
pub struct Structure {
    handler: Arc<dyn ContainerHandler>,
    media_type: Cow<'static, str>,
    total_size: u64,
    segments: Vec<Segment>,
    items: Vec<Item>,
    subassets: Vec<SubAsset>,
    /// How many leading segments are the container's own structure. Segments from
    /// here on are data beyond the end of it.
    boxes: usize,
    attachment: Option<Arc<dyn Attached>>,
    /// Where the elements of [subdividing](Segment::subdivides) segments start
    /// after the first, in file order; see [`StructureBuilder::split`].
    splits: Vec<Split>,
}

/// A boundary inside a subdividing segment: an element starts here.
#[derive(Debug, Clone, Copy)]
struct Split {
    at: u64,
    header_len: u32,
    name: Name,
}

impl Structure {
    /// What the container [attached](StructureBuilder::attach) to this structure, if
    /// it is a `T`. Handlers use it for state that is not geometry: how a payload is
    /// encoded, or what a later write needs to know.
    pub(crate) fn attachment<T: std::any::Any>(&self) -> Option<&T> {
        self.attachment.as_deref()?.as_any().downcast_ref()
    }

    /// The bytes beyond the end of the container's own structure, up to the end of
    /// the file: data after the last chunk or box, and, in a multi-image file,
    /// everything after the primary image. `None` when there are none, and for
    /// containers that do not report it.
    ///
    /// A box hash lists any boxes among them (the later images of a Multi-Picture
    /// Format JPEG) as they are, and unnamed bytes at the end as one final box
    /// named [`AFTER_BOX`](crate::AFTER_BOX) (C2PA 2.4, 18.7.2); see
    /// [`c2pa_boxes`](Self::c2pa_boxes). A hash of one part of a multi-asset file
    /// covers that part only and never includes them.
    pub fn trailing(&self) -> Option<ByteRange> {
        let first = self.segments.get(self.boxes)?;
        ByteRange::new(
            first.range().offset(),
            self.total_size - first.range().offset(),
        )
        .ok()
    }

    /// How many leading segments are the container's own structure.
    pub(crate) fn box_count(&self) -> usize {
        self.boxes
    }

    /// The sub-assets of the asset, in file order: contiguous, non-overlapping, and
    /// covering every byte. A file that embeds nothing else has one, the whole
    /// file. A Multi-Picture Format JPEG has one per image, plus one for any data
    /// after the last image.
    ///
    /// This is geometry only. Whether to hash the sub-assets separately (a C2PA
    /// multi-asset hash) or as one asset is the caller's decision.
    pub fn subassets(&self) -> &[SubAsset] {
        &self.subassets
    }

    /// The handler that parsed this asset.
    pub(crate) fn handler(&self) -> &Arc<dyn ContainerHandler> {
        &self.handler
    }

    /// The container's [id](ContainerHandler::id), for example `"jpeg"`.
    pub fn container_id(&self) -> &str {
        self.handler.id()
    }

    /// Media type, for example `image/jpeg`.
    pub fn media_type(&self) -> &str {
        &self.media_type
    }

    /// How a box-based hash names an element of this asset, or `None` if the
    /// element is not a box. Container knowledge lives in the handler.
    pub fn box_name(&self, name: Name) -> Option<Cow<'static, str>> {
        self.handler.box_name(name)
    }

    /// Asset size in bytes.
    pub fn total_size(&self) -> u64 {
        self.total_size
    }

    /// All segments in file order.
    pub fn segments(&self) -> &[Segment] {
        &self.segments
    }

    /// Look up a segment.
    pub fn segment(&self, id: SegmentId) -> Result<&Segment> {
        self.segments
            .get(id.index())
            .ok_or(Error::NotFound { what: "segment" })
    }

    /// Every element of the file in order, as a hasher sees it: each segment, with
    /// segments that [subdivide](Segment::subdivides) replaced by their finer
    /// elements. The elements tile the file exactly as the segments do.
    ///
    /// `f` receives the owning segment's id and the element. For most segments the
    /// element is the segment itself. The finer elements were found when the asset
    /// was parsed, so nothing is read. The same call works for every container;
    /// callers never test the format.
    pub fn elements<F>(&self, mut f: F) -> Result<()>
    where
        F: FnMut(SegmentId, &Segment) -> Result<()>,
    {
        for (i, seg) in self.segments.iter().enumerate() {
            let id = SegmentId(i as u32);
            if !seg.subdivides() {
                f(id, seg)?;
                continue;
            }
            let range = seg.range();
            let from = self.splits.partition_point(|s| s.at < range.offset());
            let to = self.splits.partition_point(|s| s.at < range.end());
            let mut start = range.offset();
            let mut header_len = seg.header().len() as u32;
            let mut name = seg.name();
            for split in self.splits[from..to].iter().chain(std::iter::once(&Split {
                at: range.end(),
                header_len: 0,
                name: Name::None,
            })) {
                let len = split.at - start;
                f(
                    id,
                    &Segment::new(ByteRange::new(start, len)?, header_len, 0, seg.kind(), name)?,
                )?;
                start = split.at;
                header_len = split.header_len;
                name = split.name;
            }
        }
        Ok(())
    }

    /// Every header/payload/trailer run of the file, in order, covering all bytes once.
    pub fn regions(&self) -> impl Iterator<Item = Region> + '_ {
        self.segments.iter().enumerate().flat_map(|(i, seg)| {
            let segment = SegmentId(i as u32);
            seg.regions().map(move |(role, range)| Region {
                segment,
                role,
                range,
            })
        })
    }

    /// Every item, in declaration order.
    pub fn items(&self) -> impl Iterator<Item = &Item> + '_ {
        self.items.iter()
    }

    /// All items of a kind.
    pub fn items_of(&self, kind: ItemKind) -> impl Iterator<Item = &Item> + '_ {
        self.items.iter().filter(move |e| e.kind() == kind)
    }

    /// All items of a kind carrying `label` (see [`Item::label`]).
    pub fn items_labelled<'a>(
        &'a self,
        kind: ItemKind,
        label: &'a str,
    ) -> impl Iterator<Item = &'a Item> + 'a {
        self.items
            .iter()
            .filter(move |e| e.kind() == kind && e.label() == Some(label))
    }

    /// The items with an extent in segment `id`: what the segment holds.
    pub fn items_in(&self, id: SegmentId) -> impl Iterator<Item = &Item> + '_ {
        self.items.iter().filter(move |e| e.is_in(id))
    }

    /// Visit the container's element hierarchy in file order, parents first.
    ///
    /// Flat containers yield their segments. Nested ones (ISO BMFF) also yield the
    /// elements inside segments, found lazily by reading only their headers. Callers
    /// never test the format; the handler decides what the hierarchy is.
    pub fn walk<R, F>(&self, src: &mut R, mut f: F) -> Result<()>
    where
        R: Read + Seek,
        F: FnMut(&Node<'_>) -> Result<()>,
    {
        let src: &mut dyn ReadSeek = src;
        self.handler.walk(self, src, &mut f)
    }

    /// The item of a kind: `Ok(None)` if absent, `Err(Ambiguous)` if several.
    pub fn item(&self, kind: ItemKind) -> Result<Option<&Item>> {
        let mut it = self.items_of(kind);
        let first = it.next();
        let extra = it.count();
        match (first, extra) {
            (None, _) => Ok(None),
            (Some(e), 0) => Ok(Some(e)),
            (Some(_), n) => Err(Error::Ambiguous {
                what: kind.as_str(),
                count: n + 1,
            }),
        }
    }

    /// Like [`item`](Self::item) but absence is an error.
    pub fn require_item(&self, kind: ItemKind) -> Result<&Item> {
        self.item(kind)?.ok_or(Error::NotFound {
            what: kind.as_str(),
        })
    }

    /// The C2PA hard binding an embedded manifest in this asset should use, or
    /// `None` when asset-io cannot support embedding one in its container; see
    /// [`ContainerHandler::c2pa_hash`]. A caller may choose a data hash instead
    /// of a recommended box hash.
    pub fn c2pa_hash(&self) -> Option<crate::C2paHash> {
        self.handler.c2pa_hash(self)
    }

    /// The ranges a C2PA data hash (`c2pa.hash.data`) excludes when `item` is the
    /// embedded manifest store.
    ///
    /// The container's C2PA embedding rules decide whether framing, checksums,
    /// padding or only stored payload bytes are excluded; see
    /// [`ContainerHandler::c2pa_data_hash_exclusions`]. Results are ordered,
    /// nonempty, disjoint, nonadjacent and within the asset. Works on parsed and
    /// planned structures without reading the source.
    ///
    /// The item must be a JUMBF item of this structure; the caller selects which
    /// store it is. This neither interprets the manifest nor computes a hash.
    /// Containers whose C2PA embedding uses another binding (ISO BMFF, PDF) return
    /// [`Error::UnsupportedFeature`].
    pub fn c2pa_data_hash_exclusions(&self, item: &Item) -> Result<Vec<ByteRange>> {
        if item.kind() != ItemKind::Jumbf || !self.items.iter().any(|e| std::ptr::eq(e, item)) {
            return Err(Error::InvalidFormat(
                "C2PA data-hash exclusions require a JUMBF item from this structure".into(),
            ));
        }
        let mut ranges = self.handler.c2pa_data_hash_exclusions(self, item)?;
        for range in &ranges {
            self.check_readable(*range)?;
        }
        ranges.retain(|range| !range.is_empty());
        ranges.sort_by_key(ByteRange::offset);
        let mut merged: Vec<ByteRange> = Vec::new();
        for range in ranges {
            if let Some(last) = merged.last_mut() {
                if range.offset() <= last.end() {
                    *last =
                        ByteRange::new(last.offset(), last.end().max(range.end()) - last.offset())?;
                    continue;
                }
            }
            merged.push(range);
        }
        Ok(merged)
    }

    // ------------------------------------------------------------------
    // Bounded data access
    // ------------------------------------------------------------------

    fn check_readable(&self, range: ByteRange) -> Result<()> {
        if range.end() > self.total_size {
            return Err(Error::invalid_segment(
                range.offset(),
                "range extends past end of asset",
            ));
        }
        Ok(())
    }

    /// Read a range into memory. Fails above `MAX_SEGMENT_SIZE`; use
    /// [`stream_range`](Self::stream_range) for large ranges.
    pub fn read_range<R: Read + Seek>(&self, src: &mut R, range: ByteRange) -> Result<Vec<u8>> {
        let mut out = Vec::new();
        self.read_into(src, range, &mut out)?;
        Ok(out)
    }

    /// Append a range to `out`. The range is validated against the asset size
    /// before any allocation, and reads grow `out` only as data arrives.
    fn read_into<R: Read + Seek + ?Sized>(
        &self,
        src: &mut R,
        range: ByteRange,
        out: &mut Vec<u8>,
    ) -> Result<()> {
        self.check_readable(range)?;
        let total = (out.len() as u64).saturating_add(range.len());
        if total > MAX_SEGMENT_SIZE {
            return Err(Error::LimitExceeded {
                what: "read size",
                limit: MAX_SEGMENT_SIZE,
            });
        }
        let start = out.len();
        out.try_reserve(range.len() as usize)
            .map_err(|_| Error::LimitExceeded {
                what: "allocation",
                limit: MAX_SEGMENT_SIZE,
            })?;
        src.seek(SeekFrom::Start(range.offset()))?;
        Read::take(&mut *src, range.len()).read_to_end(out)?;
        if (out.len() - start) as u64 != range.len() {
            return Err(Error::invalid_segment(
                range.offset(),
                "unexpected end of data",
            ));
        }
        Ok(())
    }

    /// The superbox type UUID of a JUMBF item (ISO/IEC 19566-5): the 16-byte
    /// type in its description box. Callers compare it with the types they care
    /// about; this crate attaches no meaning to any of them.
    ///
    /// Returns `Ok(None)` if the item is not a JUMBF superbox with a
    /// description box in the first 32 bytes (including boxes using extended
    /// lengths, which this does not interpret). Reads at most 32 bytes of an item
    /// stored as is; an item with a [transfer encoding](Item::transfer) is decoded.
    pub fn jumbf_type<R: Read + Seek>(&self, src: &mut R, item: &Item) -> Result<Option<[u8; 16]>> {
        block_on(self.total_size, src, |mut io| async move {
            self.jumbf_type_async(&mut io, item).await
        })
    }

    /// [`jumbf_type`](Self::jumbf_type), reading through `io`.
    pub async fn jumbf_type_async(&self, io: &mut Io, item: &Item) -> Result<Option<[u8; 16]>> {
        if item.kind() != ItemKind::Jumbf {
            return Ok(None);
        }
        if let Some(t) = item.jumbf_type() {
            return Ok(Some(t));
        }
        if *item.transfer() != TransferEncoding::Identity {
            // Decode only the head. Stored bytes that do not decode, or whose decoder
            // is not built in, give no type, as bytes that are not a superbox do.
            const STORED_HEAD: u64 = 4096;
            let mut stored = Vec::new();
            for extent in item.extents() {
                let left = STORED_HEAD - stored.len() as u64;
                let r = extent.range();
                self.read_in(
                    io,
                    ByteRange::new(r.offset(), r.len().min(left))?,
                    &mut stored,
                )
                .await?;
                if stored.len() as u64 >= STORED_HEAD {
                    break;
                }
            }
            return match item.transfer().decode_prefix(&stored, 32) {
                Ok(head) => Ok(crate::jumbf::superbox_type(&head)),
                Err(Error::InvalidFormat(_) | Error::UnsupportedFeature(_)) => Ok(None),
                Err(e) => Err(e),
            };
        }
        let first = item.extents().next().ok_or(Error::NotFound {
            what: "item extent",
        })?;
        let r = first.range();
        if r.len() < 32 {
            return Ok(None);
        }
        self.check_readable(r)?;
        let mut head = [0u8; 32];
        io.read_at(r.offset(), &mut head).await?;
        Ok(crate::jumbf::superbox_type(&head))
    }

    /// Append `range` to `out` through `io`, within the same bounds as
    /// [`read_into`](Self::read_into).
    async fn read_in(&self, io: &mut Io, range: ByteRange, out: &mut Vec<u8>) -> Result<()> {
        self.check_readable(range)?;
        if (out.len() as u64).saturating_add(range.len()) > MAX_SEGMENT_SIZE {
            return Err(Error::LimitExceeded {
                what: "read size",
                limit: MAX_SEGMENT_SIZE,
            });
        }
        let bytes = io.read_vec(range.offset(), range.len() as usize).await?;
        if out.is_empty() {
            *out = bytes;
        } else {
            out.extend_from_slice(&bytes);
        }
        Ok(())
    }

    /// [`read_item`](Self::read_item), reading through `io`.
    pub async fn read_item_async(&self, io: &mut Io, item: &Item) -> Result<Vec<u8>> {
        let mut stored = Vec::new();
        for extent in item.extents() {
            self.read_in(io, extent.range, &mut stored).await?;
        }
        Ok(stored)
    }

    /// [`read_content`](Self::read_content), reading through `io`.
    pub async fn read_content_async(&self, io: &mut Io, item: &Item) -> Result<Vec<u8>> {
        item.transfer()
            .decode(self.read_item_async(io, item).await?)
    }

    /// The JUMBF store as a reader sees it, or `None` if the asset has none.
    ///
    /// Usually that is the one JUMBF item. A file with an `original` store and an
    /// `update` (ISO BMFF) reads as the two combined, with the update's children
    /// after the original's. Several unrelated stores are
    /// [`Error::Ambiguous`]. Merkle boxes are not stores and are never returned.
    /// To read the C2PA manifest store whatever other JUMBF the asset holds, use
    /// [`c2pa_store`](Self::c2pa_store).
    pub fn store<R: Read + Seek>(&self, src: &mut R) -> Result<Option<Vec<u8>>> {
        use crate::segment::labels::{ORIGINAL, UPDATE};
        let original = self.items_labelled(ItemKind::Jumbf, ORIGINAL).next();
        let update = self.items_labelled(ItemKind::Jumbf, UPDATE).next();
        if let (Some(o), Some(u)) = (original, update) {
            let o = self.read_content(src, o)?;
            let u = self.read_content(src, u)?;
            return crate::jumbf::extend(&o, &u).map(Some);
        }
        match self.item(ItemKind::Jumbf)? {
            Some(e) => self.read_content(src, e).map(Some),
            None => Ok(None),
        }
    }

    /// The asset's XMP packet, or `None` if it has none. Containers that store XMP
    /// in several pieces return it reassembled.
    pub fn xmp(&self, src: &mut dyn ReadSeek) -> Result<Option<Vec<u8>>> {
        self.handler.read_xmp(self, src)
    }

    /// The JUMBF item holding the asset's C2PA manifest store: the one whose
    /// superbox type is [`C2PA_STORE_TYPE`](crate::jumbf::C2PA_STORE_TYPE).
    /// `None` if there is none; other JUMBF, such as JPEG XT boxes of other types,
    /// is ignored. Several stores are [`Error::Ambiguous`].
    ///
    /// When a store is kept as an `original` plus an `update` (ISO BMFF), this is
    /// the `original`; [`c2pa_store`](Self::c2pa_store) reads the two combined. The
    /// item is what a caller excludes from a hash or patches in place.
    pub fn c2pa_item<R: Read + Seek>(&self, src: &mut R) -> Result<Option<&Item>> {
        block_on(self.total_size, src, |mut io| async move {
            self.c2pa_item_async(&mut io).await
        })
    }

    /// [`c2pa_item`](Self::c2pa_item), reading through `io`, for a [`Task`](crate::task::Task) where
    /// the caller does the reads. There are none when the parser recorded the
    /// type of each JUMBF item, as the built-in handlers do.
    pub async fn c2pa_item_async(&self, io: &mut Io) -> Result<Option<&Item>> {
        use crate::segment::labels::UPDATE;
        let mut found = None;
        let mut count = 0;
        for item in self.items_of(ItemKind::Jumbf) {
            if item.label() == Some(UPDATE) {
                continue;
            }
            if self.jumbf_type_async(io, item).await? == Some(crate::jumbf::C2PA_STORE_TYPE) {
                count += 1;
                found.get_or_insert(item);
            }
        }
        if count > 1 {
            return Err(Error::Ambiguous {
                what: "C2PA manifest store",
                count,
            });
        }
        Ok(found)
    }

    /// The asset's C2PA manifest store as a reader sees it, or `None` if it has
    /// none: the content of [`c2pa_item`](Self::c2pa_item), with any transfer
    /// encoding undone, and an `update` appended to its `original` (ISO BMFF).
    /// Only finds the store; the manifests in it are not interpreted.
    pub fn c2pa_store<R: Read + Seek>(&self, src: &mut R) -> Result<Option<Vec<u8>>> {
        block_on(self.total_size, src, |mut io| async move {
            self.c2pa_store_async(&mut io).await
        })
    }

    /// [`c2pa_store`](Self::c2pa_store), reading through `io`, for a [`Task`](crate::task::Task)
    /// where the caller does the reads.
    pub async fn c2pa_store_async(&self, io: &mut Io) -> Result<Option<Vec<u8>>> {
        use crate::segment::labels::{ORIGINAL, UPDATE};
        let Some(item) = self.c2pa_item_async(io).await? else {
            return Ok(None);
        };
        let store = self.read_content_async(io, item).await?;
        if item.label() == Some(ORIGINAL) {
            if let Some(update) = self.items_labelled(ItemKind::Jumbf, UPDATE).next() {
                let update = self.read_content_async(io, update).await?;
                return crate::jumbf::extend(&store, &update).map(Some);
            }
        }
        Ok(Some(store))
    }

    /// The boxes a C2PA box hash (`c2pa.hash.boxes`) lists for this asset, in file
    /// order, covering every byte once.
    ///
    /// Each element ([`elements`](Self::elements)) is one box, named by the
    /// handler's [`c2pa_box_name`](ContainerHandler::c2pa_box_name): a JPEG scan
    /// with restart markers is its `SOS` box and one box per `RSTn`. Elements past
    /// the container's own structure that are boxes (later images of a
    /// Multi-Picture Format JPEG) are listed as they are. The segments of the C2PA
    /// manifest store ([`c2pa_item`](Self::c2pa_item)) are one box named
    /// [`C2PA_BOX`](crate::C2PA_BOX), which the hash does not cover, and unnamed
    /// bytes at the end one box named [`AFTER_BOX`](crate::AFTER_BOX).
    ///
    /// `src` is the asset; a planned structure's boxes are known before the
    /// output exists. An element of the
    /// structure without a box name, or boxes after unnamed data, are
    /// [`Error::UnsupportedFeature`]: the asset is not box-hashable.
    ///
    /// Only finding the store can read `src`; see
    /// [`c2pa_boxes_with`](Self::c2pa_boxes_with).
    pub fn c2pa_boxes<R: Read + Seek>(&self, src: &mut R) -> Result<Vec<C2paBox>> {
        self.c2pa_boxes_with(self.c2pa_item(src)?)
    }

    /// [`c2pa_boxes`](Self::c2pa_boxes) given the store's item, as
    /// [`c2pa_item`](Self::c2pa_item) or [`c2pa_item_async`](Self::c2pa_item_async)
    /// finds it, or `None` for an asset without one. Reads nothing.
    pub fn c2pa_boxes_with(&self, store: Option<&Item>) -> Result<Vec<C2paBox>> {
        let store: Vec<SegmentId> = match store {
            Some(item) if self.items.iter().any(|e| std::ptr::eq(e, item)) => {
                item.extents().map(|e| e.segment()).collect()
            }
            Some(_) => {
                return Err(Error::InvalidFormat(
                    "C2PA boxes require the store's item from this structure".into(),
                ))
            }
            None => Vec::new(),
        };
        let metadata: Vec<ByteRange> = self
            .items
            .iter()
            .filter(|i| matches!(i.kind(), ItemKind::Xmp | ItemKind::Exif))
            .flat_map(|i| i.extents().map(|e| e.range()))
            .collect();
        let unsupported = Error::UnsupportedFeature;
        let mut boxes: Vec<C2paBox> = Vec::new();
        let mut after: Option<ByteRange> = None;
        self.elements(|id, element| {
            let range = element.range();
            if store.contains(&id) {
                match boxes.last_mut() {
                    Some(last)
                        if last.name == crate::C2PA_BOX && last.range.end() == range.offset() =>
                    {
                        last.range =
                            ByteRange::new(last.range.offset(), last.range.len() + range.len())?;
                    }
                    _ => boxes.push(C2paBox {
                        name: Cow::Borrowed(crate::C2PA_BOX),
                        range,
                        metadata: Vec::new(),
                    }),
                }
                return Ok(());
            }
            match (
                self.handler.c2pa_box_name(self, id, element),
                id.index() < self.boxes,
            ) {
                (Some(_), _) if after.is_some() => {
                    Err(unsupported("C2PA box hash: boxes after unnamed data"))
                }
                (Some(name), _) => {
                    boxes.push(C2paBox {
                        name,
                        range,
                        metadata: metadata
                            .iter()
                            .filter(|m| range.contains(m))
                            .copied()
                            .collect(),
                    });
                    Ok(())
                }
                (None, false) => {
                    after = Some(match after {
                        Some(a) => ByteRange::new(a.offset(), range.end() - a.offset())?,
                        None => range,
                    });
                    Ok(())
                }
                (None, true) => Err(unsupported("C2PA box hash: an element has no box name")),
            }
        })?;
        if let Some(range) = after {
            boxes.push(C2paBox {
                name: Cow::Borrowed(crate::AFTER_BOX),
                range,
                metadata: Vec::new(),
            });
        }
        Ok(boxes)
    }

    /// Read an item's extents, concatenated: the bytes stored in the file.
    pub fn read_item<R: Read + Seek + ?Sized>(&self, src: &mut R, item: &Item) -> Result<Vec<u8>> {
        let mut out = Vec::new();
        for extent in item.extents() {
            self.read_into(src, extent.range, &mut out)?;
        }
        Ok(out)
    }

    /// Read an item's content: [`read_item`](Self::read_item), then the item's
    /// [transfer encoding](Item::transfer) undone. For most items the two are the
    /// same.
    pub fn read_content<R: Read + Seek + ?Sized>(
        &self,
        src: &mut R,
        item: &Item,
    ) -> Result<Vec<u8>> {
        let stored = self.read_item(src, item)?;
        item.transfer().decode(stored)
    }

    /// Stream a range through a caller-owned buffer; no allocation.
    pub fn stream_range<R, F>(
        &self,
        src: &mut R,
        range: ByteRange,
        buf: &mut [u8],
        mut f: F,
    ) -> Result<()>
    where
        R: Read + Seek,
        F: FnMut(&[u8]) -> Result<()>,
    {
        self.check_readable(range)?;
        if buf.is_empty() {
            return Err(Error::InvalidFormat("empty stream buffer".into()));
        }
        src.seek(SeekFrom::Start(range.offset()))?;
        let mut remaining = range.len();
        while remaining > 0 {
            let n = remaining.min(buf.len() as u64) as usize;
            src.read_exact(&mut buf[..n])?;
            f(&buf[..n])?;
            remaining -= n as u64;
        }
        Ok(())
    }

    // ------------------------------------------------------------------
    // Zero-copy access over a byte slice (for example a memory map)
    // ------------------------------------------------------------------

    /// Borrow `range` from `data`, which must hold the whole asset starting at
    /// offset 0. No copy is made. `data` is only length-checked: it is the
    /// caller's job to pass the bytes this structure was parsed from.
    pub fn slice<'a>(&self, data: &'a [u8], range: ByteRange) -> Result<&'a [u8]> {
        self.check_readable(range)?;
        if (data.len() as u64) < self.total_size {
            return Err(Error::invalid_segment(
                data.len() as u64,
                format!(
                    "buffer holds {} bytes, asset is {}",
                    data.len(),
                    self.total_size
                ),
            ));
        }
        let bad = || Error::invalid_segment(range.offset(), "range does not fit in memory");
        let start = usize::try_from(range.offset()).map_err(|_| bad())?;
        let end = usize::try_from(range.end()).map_err(|_| bad())?;
        data.get(start..end).ok_or_else(bad)
    }

    /// An item's bytes from `data`. Borrowed, with no copy, when the item has a
    /// single extent; copied (up to `MAX_SEGMENT_SIZE`) when it has several.
    pub fn slice_item<'a>(&self, data: &'a [u8], item: &Item) -> Result<Cow<'a, [u8]>> {
        let mut extents = item.extents();
        let Some(first) = extents.next() else {
            return Ok(Cow::Borrowed(&[]));
        };
        let head = self.slice(data, first.range)?;
        let Some(second) = extents.next() else {
            return Ok(Cow::Borrowed(head));
        };
        let mut out = Vec::new();
        for r in [first.range, second.range]
            .into_iter()
            .chain(extents.map(|p| p.range))
        {
            let b = self.slice(data, r)?;
            if (out.len() as u64).saturating_add(b.len() as u64) > MAX_SEGMENT_SIZE {
                return Err(Error::LimitExceeded {
                    what: "read size",
                    limit: MAX_SEGMENT_SIZE,
                });
            }
            out.try_reserve(b.len()).map_err(|_| Error::LimitExceeded {
                what: "allocation",
                limit: MAX_SEGMENT_SIZE,
            })?;
            out.extend_from_slice(b);
        }
        Ok(Cow::Owned(out))
    }

    // ------------------------------------------------------------------
    // Read-side sink
    // ------------------------------------------------------------------

    /// Deliver every byte of the asset to `sink`, in file order, tagged with its
    /// segment and role: the read-side counterpart of [`write`](Self::write). Runs
    /// the sink would skip ([`Sink::wants`]) are not read. Chunks are at most
    /// `DEFAULT_CHUNK_SIZE` bytes and borrow one reused buffer.
    pub fn read<R: Read + Seek>(&self, src: &mut R, sink: &mut dyn Sink) -> Result<()> {
        sink.begin(self)?;
        let mut buf = vec![0u8; DEFAULT_CHUNK_SIZE];
        for r in self.regions() {
            if !sink.wants(self.segment(r.segment)?, r.role) {
                continue;
            }
            self.check_readable(r.range)?;
            src.seek(SeekFrom::Start(r.range.offset()))?;
            let mut offset = r.range.offset();
            let mut remaining = r.range.len();
            while remaining > 0 {
                let n = remaining.min(buf.len() as u64) as usize;
                src.read_exact(&mut buf[..n])?;
                sink.chunk(Chunk {
                    segment: r.segment,
                    role: r.role,
                    offset,
                    data: &buf[..n],
                })?;
                offset += n as u64;
                remaining -= n as u64;
            }
        }
        Ok(())
    }

    /// Like [`read`](Self::read) over bytes already in memory
    /// (a memory map, say). Nothing is copied: each region reaches the sink as one
    /// chunk borrowed from `data`. A sink that wants parallelism can split the
    /// chunks itself.
    pub fn read_slice(&self, data: &[u8], sink: &mut dyn Sink) -> Result<()> {
        sink.begin(self)?;
        for r in self.regions() {
            if !sink.wants(self.segment(r.segment)?, r.role) {
                continue;
            }
            sink.chunk(Chunk {
                segment: r.segment,
                role: r.role,
                offset: r.range.offset(),
                data: self.slice(data, r.range)?,
            })?;
        }
        Ok(())
    }

    // ------------------------------------------------------------------
    // In-place patching
    // ------------------------------------------------------------------

    /// Overwrite an item's bytes in an already-written stream.
    ///
    /// `data` must fit the item's total capacity; the remainder is
    /// zero-filled so the structure is unchanged. Container checksums that cover
    /// the patched payload (PNG CRC) are recomputed. `out` must contain the
    /// asset starting at offset 0.
    pub fn patch<W: Read + Write + Seek>(
        &self,
        out: &mut W,
        item: &Item,
        data: &[u8],
    ) -> Result<()> {
        self.handler.check_patch(self, item, data.len())?;
        let capacity = item.len();
        if data.len() as u64 > capacity {
            return Err(Error::LimitExceeded {
                what: "patch exceeds payload capacity",
                limit: capacity,
            });
        }
        let mut rest = data;
        for extent in item.extents() {
            let take = (rest.len() as u64).min(extent.range.len()) as usize;
            out.seek(SeekFrom::Start(extent.range.offset()))?;
            out.write_all(&rest[..take])?;
            write_zeros(out, extent.range.len() - take as u64)?;
            rest = &rest[take..];
        }
        // Extents are in order; fix each segment's trailer once.
        let mut last: Option<SegmentId> = None;
        for extent in item.extents() {
            if last != Some(extent.segment) {
                last = Some(extent.segment);
                self.fix_trailer(out, extent.segment)?;
            }
        }
        out.flush()?;
        Ok(())
    }

    /// Write this asset to `out` with `updates` applied, delivering every output
    /// byte to `sink`, and return the structure of what was written. `src` must be
    /// the stream this structure was parsed from. `out` is only written to, from its
    /// current position. The container's handler does the work; callers never name
    /// the format.
    pub fn write(
        &self,
        src: &mut dyn ReadSeek,
        out: &mut dyn Write,
        updates: &crate::Updates,
        sink: &mut dyn crate::sink::Sink,
    ) -> Result<Structure> {
        self.handler.write(self, src, out, updates, sink)
    }

    /// The structure `write` would produce for `updates`, without writing: where each
    /// item would land, and the total size. `src` must be the stream this
    /// structure was parsed from.
    ///
    /// The result is the one `write` returns, so a caller can learn where a
    /// manifest will go (and size a hash exclusion for it) before producing any
    /// output. A container that cannot plan reports [`Error::UnsupportedFormat`].
    pub fn plan(&self, src: &mut dyn ReadSeek, updates: &crate::Updates) -> Result<Structure> {
        self.handler.plan(self, src, updates)
    }

    /// Fill a placeholder: overwrite an item's bytes, in place, with `data` of
    /// exactly the same length.
    ///
    /// This is how a signed manifest replaces the placeholder it was sized from.
    /// Bytes outside the payload (box sizes, offsets, everything a hash or an
    /// offset table was computed over) are not touched, so none of them can move.
    /// Unlike [`patch`](Self::patch), which zero-fills a shorter `data`, a length
    /// mismatch is an error: it means the placeholder was not sized correctly.
    ///
    /// Writing the store again with `set_jumbf` is not a substitute: that is free
    /// to change the size.
    ///
    /// `data` is the content, not what is stored: an item with a
    /// [transfer encoding](Item::transfer) (SVG's base64) has `data` encoded first,
    /// and it is the encoded length that must match.
    pub fn patch_exact<W: Read + Write + Seek>(
        &self,
        out: &mut W,
        item: &Item,
        data: &[u8],
    ) -> Result<()> {
        let stored = item.transfer().encode(data)?;
        // The container's refusal comes before a complaint about the length.
        self.handler.check_patch(self, item, stored.len())?;
        if stored.len() as u64 != item.len() {
            return Err(Error::InvalidFormat(format!(
                "replacement is {} bytes, the placeholder is {}",
                stored.len(),
                item.len()
            )));
        }
        self.patch(out, item, &stored)
    }

    fn fix_trailer<W: Read + Write + Seek>(&self, out: &mut W, id: SegmentId) -> Result<()> {
        let out: &mut dyn ReadWriteSeek = out;
        self.handler.fix_trailer(out, self, id)
    }
}

fn write_zeros<W: Write>(w: &mut W, mut n: u64) -> Result<()> {
    static ZEROS: [u8; 4096] = [0; 4096];
    while n > 0 {
        let k = n.min(ZEROS.len() as u64) as usize;
        w.write_all(&ZEROS[..k])?;
        n -= k as u64;
    }
    Ok(())
}

/// Builds a [`Structure`], rejecting anything that would violate its invariants.
#[derive(Debug)]
pub struct StructureBuilder {
    handler: Arc<dyn ContainerHandler>,
    media_type: Cow<'static, str>,
    total_size: u64,
    cursor: u64,
    segments: Vec<Segment>,
    items: Vec<Item>,
    /// Segment index and media type where each sub-asset after the primary starts.
    sub_starts: Vec<(usize, Option<Cow<'static, str>>)>,
    /// Segment index where data beyond the container's structure starts, if declared.
    boxes: Option<usize>,
    attachment: Option<Arc<dyn Attached>>,
    splits: Vec<Split>,
}

impl StructureBuilder {
    /// Start a structure for an asset of known size, owned by `handler`.
    pub fn new(
        handler: Arc<dyn ContainerHandler>,
        media_type: impl Into<Cow<'static, str>>,
        total_size: u64,
    ) -> Self {
        Self {
            handler,
            media_type: media_type.into(),
            total_size,
            cursor: 0,
            segments: Vec::new(),
            items: Vec::new(),
            sub_starts: Vec::new(),
            boxes: None,
            attachment: None,
            splits: Vec::new(),
        }
    }

    /// Keep `value` with the structure, for the container's own use later (read it
    /// back with [`crate::container_api::attachment`]). It is opaque to everything else. One
    /// value is kept; a second replaces the first.
    pub fn attach<T: std::any::Any + std::fmt::Debug + Send + Sync>(
        &mut self,
        value: T,
    ) -> &mut Self {
        self.attachment = Some(Arc::new(value));
        self
    }

    pub(crate) fn attach_shared(&mut self, value: Option<Arc<dyn Attached>>) {
        self.attachment = value;
    }

    /// Declare that the container's own structure ends here: segments pushed from
    /// now on are data beyond it (see [`Structure::trailing`]). Without a call, every
    /// segment is part of the structure.
    pub fn end_boxes(&mut self) -> Result<()> {
        if self.boxes.is_some() {
            return Err(Error::InvalidFormat("structure end declared twice".into()));
        }
        self.boxes = Some(self.segments.len());
        Ok(())
    }

    /// Declare that the next segment pushed starts a new [`SubAsset`]. The first
    /// sub-asset, the primary, starts at the first segment without a call.
    /// `media_type` is `None` for data the container cannot identify.
    pub fn begin_subasset(&mut self, media_type: Option<Cow<'static, str>>) -> Result<()> {
        let at = self.segments.len();
        let last = self.sub_starts.last().map_or(0, |s| s.0);
        if at == 0 || at == last {
            return Err(Error::InvalidFormat("empty sub-asset".into()));
        }
        self.sub_starts.push((at, media_type));
        Ok(())
    }

    /// Undo the last [`begin_subasset`](Self::begin_subasset) and everything pushed
    /// since, for a parser that found the sub-asset was not one after all. Returns
    /// the offset where it started, which is also the cursor again.
    ///
    /// Fails if there is no sub-asset to undo, or if an item already refers to one
    /// of the segments being removed.
    pub fn rollback_subasset(&mut self) -> Result<u64> {
        let Some(&(at, _)) = self.sub_starts.last() else {
            return Err(Error::InvalidFormat("no sub-asset to roll back".into()));
        };
        if self
            .items
            .iter()
            .any(|e| e.extents().any(|p| p.segment().index() >= at))
        {
            return Err(Error::InvalidFormat(
                "an item refers to the sub-asset being rolled back".into(),
            ));
        }
        let start = self
            .segments
            .get(at)
            .map_or(self.cursor, |s| s.range().offset());
        self.segments.truncate(at);
        self.sub_starts.pop();
        self.cursor = start;
        Ok(start)
    }

    /// Offset where the next segment must start.
    pub fn cursor(&self) -> u64 {
        self.cursor
    }

    /// Append a segment. It must start at the cursor and end within the asset.
    pub fn push(&mut self, seg: Segment) -> Result<SegmentId> {
        if self.segments.len() + self.splits.len() >= MAX_SEGMENTS {
            return Err(Error::LimitExceeded {
                what: "segments",
                limit: MAX_SEGMENTS as u64,
            });
        }
        let ext = seg.range();
        if ext.offset() != self.cursor {
            return Err(Error::invalid_segment(
                ext.offset(),
                format!("segment must start at {} (gap or overlap)", self.cursor),
            ));
        }
        if ext.end() > self.total_size {
            return Err(Error::invalid_segment(
                ext.offset(),
                "segment extends past end of asset",
            ));
        }
        let id = SegmentId::from_index(self.segments.len())?;
        self.cursor = ext.end();
        self.segments.push(seg);
        Ok(id)
    }

    /// Append a segment at the cursor from its three lengths.
    pub fn push_span(
        &mut self,
        kind: SegmentKind,
        name: Name,
        header_len: u32,
        payload_len: u64,
        trailer_len: u16,
    ) -> Result<SegmentId> {
        let total = (header_len as u64)
            .checked_add(payload_len)
            .and_then(|v| v.checked_add(trailer_len as u64))
            .ok_or_else(|| Error::invalid_segment(self.cursor, "segment length overflows"))?;
        let seg = Segment::new(
            ByteRange::new(self.cursor, total)?,
            header_len,
            trailer_len,
            kind,
            name,
        )?;
        self.push(seg)
    }

    /// Like [`push_span`](Self::push_span), for a container where each item of
    /// metadata is one segment, as chunks are: the segment's payload is also
    /// declared as the item `info` describes.
    pub fn push_item(
        &mut self,
        kind: SegmentKind,
        name: Name,
        header_len: u32,
        payload_len: u64,
        trailer_len: u16,
        info: ItemInfo,
    ) -> Result<SegmentId> {
        let id = self.push_span(kind, name, header_len, payload_len, trailer_len)?;
        self.item_of_segments(info, &[id])?;
        Ok(id)
    }

    /// Append one unnamed segment of [`Other`](SegmentKind::Other) kind for
    /// whatever is left of the asset, if anything: trailing data the container does
    /// not account for.
    pub fn push_tail(&mut self) -> Result<()> {
        if self.cursor < self.total_size {
            self.push_span(
                SegmentKind::Other,
                Name::None,
                0,
                self.total_size - self.cursor,
                0,
            )?;
        }
        Ok(())
    }

    /// Segment already pushed.
    pub fn segment(&self, id: SegmentId) -> Result<&Segment> {
        self.segments
            .get(id.index())
            .ok_or(Error::NotFound { what: "segment" })
    }

    /// Record that pushed segment `id` holds a finer element starting at `at`,
    /// framed by `header_len` bytes and named `name`: the segment
    /// [subdivides](Segment::subdivides), and its first element runs from its own
    /// start to its first split. Splits are recorded in file order, inside the
    /// segment's payload, and count towards [`MAX_SEGMENTS`].
    pub fn split(&mut self, id: SegmentId, at: u64, header_len: u32, name: Name) -> Result<()> {
        if self.segments.len() + self.splits.len() >= MAX_SEGMENTS {
            return Err(Error::LimitExceeded {
                what: "segment count",
                limit: MAX_SEGMENTS as u64,
            });
        }
        let seg = self
            .segments
            .get_mut(id.index())
            .ok_or(Error::NotFound { what: "segment" })?;
        let fits = at
            .checked_add(u64::from(header_len))
            .is_some_and(|end| end <= seg.range().end());
        if at < seg.payload().offset()
            || !fits
            || self.splits.last().is_some_and(|last| last.at >= at)
        {
            return Err(Error::invalid_segment(
                at,
                "split out of order or outside its segment",
            ));
        }
        *seg = seg.with_subdivision();
        self.splits.push(Split {
            at,
            header_len,
            name,
        });
        Ok(())
    }

    /// Copy the splits of `src`'s segment `from` to pushed segment `id`, which
    /// holds the same bytes.
    pub(crate) fn split_like(
        &mut self,
        id: SegmentId,
        src: &Structure,
        from: SegmentId,
    ) -> Result<()> {
        let from = src.segment(from)?.range();
        let to = self.segment(id)?.range().offset();
        let first = src.splits.partition_point(|s| s.at < from.offset());
        for split in src.splits[first..].iter().take_while(|s| s.at < from.end()) {
            self.split(
                id,
                to + (split.at - from.offset()),
                split.header_len,
                split.name,
            )?;
        }
        Ok(())
    }

    /// Declare an item whose extents are the payloads of whole segments.
    pub fn item_of_segments(&mut self, info: ItemInfo, ids: &[SegmentId]) -> Result<()> {
        let mut extents = Vec::with_capacity(ids.len());
        for &id in ids {
            extents.push((id, self.segment(id)?.payload()));
        }
        self.item(info, &extents)
    }

    /// Declare an item from explicit `(segment, range)` extents, in logical order.
    /// Each range must lie within its segment.
    pub fn item(&mut self, info: ItemInfo, extents: &[(SegmentId, ByteRange)]) -> Result<()> {
        let mut it = extents.iter();
        let Some(&(sid, range)) = it.next() else {
            return Err(Error::InvalidFormat(
                "item needs at least one extent".into(),
            ));
        };
        let first = self.make_extent(sid, range)?;
        let mut rest = Vec::new();
        for &(sid, range) in it {
            rest.push(self.make_extent(sid, range)?);
        }
        self.items.push(Item { info, first, rest });
        Ok(())
    }

    fn make_extent(&self, segment: SegmentId, range: ByteRange) -> Result<Extent> {
        let seg = self.segment(segment)?;
        if !seg.range().contains(&range) {
            return Err(Error::invalid_segment(
                range.offset(),
                "item extent lies outside its segment",
            ));
        }
        Ok(Extent { range, segment })
    }

    /// Finish. The segments must cover the whole asset.
    pub fn finish(self) -> Result<Structure> {
        if self.cursor != self.total_size {
            return Err(Error::invalid_segment(
                self.cursor,
                format!(
                    "segments cover {} of {} bytes",
                    self.cursor, self.total_size
                ),
            ));
        }
        if self
            .sub_starts
            .last()
            .is_some_and(|s| s.0 >= self.segments.len())
        {
            return Err(Error::InvalidFormat("empty sub-asset".into()));
        }
        let mut subassets = Vec::with_capacity(self.sub_starts.len() + 1);
        let mut start = 0usize;
        let mut media = Some(self.media_type.clone());
        for (i, next) in self
            .sub_starts
            .iter()
            .map(|(s, m)| (*s, m.clone()))
            .chain(std::iter::once((self.segments.len(), None)))
            .enumerate()
        {
            let (end, next_media) = next;
            let from = self
                .segments
                .get(start)
                .map_or(self.total_size, |s| s.range().offset());
            let to = self
                .segments
                .get(end)
                .map_or(self.total_size, |s| s.range().offset());
            subassets.push(SubAsset {
                range: ByteRange::new(from, to - from)?,
                segments: start..end,
                media_type: media,
                primary: i == 0,
            });
            start = end;
            media = next_media;
        }
        let boxes = self.boxes.unwrap_or(self.segments.len());
        if boxes > self.segments.len() {
            return Err(Error::InvalidFormat(
                "structure ends after the last segment".into(),
            ));
        }
        Ok(Structure {
            handler: self.handler,
            media_type: self.media_type,
            total_size: self.total_size,
            segments: self.segments,
            items: self.items,
            subassets,
            boxes,
            attachment: self.attachment,
            splits: self.splits,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::container_api::{BoxFuture, FormatSpec};

    /// A handler that only exists to own structures in these tests.
    #[derive(Debug)]
    struct TestHandler;

    impl ContainerHandler for TestHandler {
        fn id(&self) -> &'static str {
            "test"
        }

        fn formats(&self) -> &[FormatSpec] {
            const F: &[FormatSpec] = &[FormatSpec::new("application/x-test", "test")];
            F
        }

        fn parse_async(self: Arc<Self>, _: crate::io::Io) -> BoxFuture<'static, Result<Structure>> {
            Box::pin(async { Err(Error::UnsupportedFormat) })
        }

        fn write(
            &self,
            _: &Structure,
            _: &mut dyn ReadSeek,
            _: &mut dyn Write,
            _: &crate::Updates,
            _: &mut dyn crate::Sink,
        ) -> Result<Structure> {
            Err(Error::UnsupportedFormat)
        }
    }

    fn builder(total: u64) -> StructureBuilder {
        StructureBuilder::new(Arc::new(TestHandler), "application/x-test", total)
    }

    #[test]
    fn subassets_tile_and_default_to_one() {
        let mut b = builder(30);
        b.push_span(SegmentKind::Preamble, Name::None, 30, 0, 0)
            .unwrap();
        let s = b.finish().unwrap();
        assert_eq!(s.subassets().len(), 1);
        assert!(s.subassets()[0].is_primary());
        assert_eq!(s.subassets()[0].range(), ByteRange::new(0, 30).unwrap());

        let mut b = builder(30);
        assert!(b.begin_subasset(None).is_err(), "nothing pushed yet");
        b.push_span(SegmentKind::Preamble, Name::None, 10, 0, 0)
            .unwrap();
        b.begin_subasset(Some("a/b".into())).unwrap();
        assert!(b.begin_subasset(None).is_err(), "empty sub-asset");
        b.push_span(SegmentKind::Other, Name::None, 20, 0, 0)
            .unwrap();
        let s = b.finish().unwrap();
        let subs = s.subassets();
        assert_eq!(subs[0].range(), ByteRange::new(0, 10).unwrap());
        assert_eq!(subs[1].range(), ByteRange::new(10, 20).unwrap());
        assert_eq!(subs[1].segments(), 1..2);
        assert_eq!(subs[1].media_type(), Some("a/b"));

        let mut b = builder(30);
        b.push_span(SegmentKind::Preamble, Name::None, 10, 0, 0)
            .unwrap();
        b.begin_subasset(None).unwrap();
        assert!(b.finish().is_err(), "trailing empty sub-asset");
    }

    #[test]
    fn an_attachment_is_kept_by_type_and_replaced_by_another() {
        #[derive(Debug, PartialEq)]
        struct State(u32);
        let mut b = builder(4);
        b.push_span(SegmentKind::Preamble, Name::None, 4, 0, 0)
            .unwrap();
        b.attach(State(1)).attach(State(2));
        let s = b.finish().unwrap();
        assert_eq!(s.attachment::<State>(), Some(&State(2)));
        assert!(s.attachment::<String>().is_none());

        let mut b = builder(4);
        b.push_span(SegmentKind::Preamble, Name::None, 4, 0, 0)
            .unwrap();
        assert!(b.finish().unwrap().attachment::<State>().is_none());
    }

    #[test]
    fn rolling_back_a_subasset_restores_the_cursor() {
        let mut b = builder(30);
        assert!(b.rollback_subasset().is_err(), "nothing to roll back");
        b.push_span(SegmentKind::Preamble, Name::None, 10, 0, 0)
            .unwrap();
        b.begin_subasset(Some("a/b".into())).unwrap();
        b.push_span(SegmentKind::Other, Name::None, 5, 0, 0)
            .unwrap();
        b.push_span(SegmentKind::Other, Name::None, 5, 0, 0)
            .unwrap();
        assert_eq!(b.rollback_subasset().unwrap(), 10);
        assert_eq!(b.cursor(), 10);
        assert!(b.rollback_subasset().is_err(), "already undone");
        // The rest is pushed as part of the primary asset.
        b.push_span(SegmentKind::Other, Name::None, 20, 0, 0)
            .unwrap();
        let s = b.finish().unwrap();
        assert_eq!(s.subassets().len(), 1);
        assert_eq!(s.segments().len(), 2);

        // A sub-asset with nothing pushed yet rolls back too.
        let mut b = builder(30);
        b.push_span(SegmentKind::Preamble, Name::None, 10, 0, 0)
            .unwrap();
        b.begin_subasset(None).unwrap();
        assert_eq!(b.rollback_subasset().unwrap(), 10);

        // An item that refers to the removed segments blocks it.
        let mut b = builder(30);
        let first = b
            .push_span(SegmentKind::Preamble, Name::None, 10, 0, 0)
            .unwrap();
        b.begin_subasset(None).unwrap();
        let second = b
            .push_span(SegmentKind::Metadata, Name::None, 4, 16, 0)
            .unwrap();
        b.item_of_segments(ItemInfo::xmp(), &[second]).unwrap();
        assert!(b.rollback_subasset().is_err());
        let _ = first;
    }

    #[test]
    fn tiles_exactly() {
        let mut b = builder(30);
        b.push_span(SegmentKind::Preamble, Name::None, 10, 0, 0)
            .unwrap();
        let id = b
            .push_span(SegmentKind::Metadata, Name::FourCC(*b"iTXt"), 8, 8, 4)
            .unwrap();
        b.item_of_segments(ItemInfo::xmp(), &[id]).unwrap();
        let s = b.finish().unwrap();
        let covered: u64 = s.regions().map(|r| r.range.len()).sum();
        assert_eq!(covered, 30);
        let e = s.require_item(ItemKind::Xmp).unwrap();
        assert_eq!(e.len(), 8);
        assert!(s.item(ItemKind::Jumbf).unwrap().is_none());
        assert!(matches!(
            s.require_item(ItemKind::Jumbf),
            Err(Error::NotFound { .. })
        ));
    }

    #[test]
    fn rejects_gap_overrun_and_short_cover() {
        let mut b = builder(20);
        let gap = Segment::new(
            ByteRange::new(5, 5).unwrap(),
            0,
            0,
            SegmentKind::Other,
            Name::None,
        )
        .unwrap();
        assert!(b.push(gap).is_err());
        assert!(b
            .push_span(SegmentKind::Other, Name::None, 0, 21, 0)
            .is_err());
        b.push_span(SegmentKind::Other, Name::None, 0, 10, 0)
            .unwrap();
        assert!(b.finish().is_err());
    }

    #[test]
    fn ambiguous_item() {
        let mut b = builder(8);
        let a = b
            .push_span(SegmentKind::Metadata, Name::None, 0, 4, 0)
            .unwrap();
        let c = b
            .push_span(SegmentKind::Metadata, Name::None, 0, 4, 0)
            .unwrap();
        b.item_of_segments(ItemInfo::jumbf(), &[a]).unwrap();
        b.item_of_segments(ItemInfo::jumbf(), &[c]).unwrap();
        let s = b.finish().unwrap();
        assert!(matches!(
            s.item(ItemKind::Jumbf),
            Err(Error::Ambiguous { count: 2, .. })
        ));
    }

    #[test]
    fn extent_must_lie_in_segment() {
        let mut b = builder(10);
        let a = b
            .push_span(SegmentKind::Metadata, Name::None, 0, 5, 0)
            .unwrap();
        let _ = b
            .push_span(SegmentKind::Other, Name::None, 0, 5, 0)
            .unwrap();
        let outside = ByteRange::new(4, 3).unwrap();
        assert!(b.item(ItemInfo::xmp(), &[(a, outside)]).is_err());
    }

    #[test]
    fn read_range_is_bounded() {
        let mut b = builder(8);
        b.push_span(SegmentKind::Other, Name::None, 0, 8, 0)
            .unwrap();
        let s = b.finish().unwrap();
        let mut src = std::io::Cursor::new(vec![1u8, 2, 3, 4, 5, 6, 7, 8]);
        let got = s
            .read_range(&mut src, ByteRange::new(2, 3).unwrap())
            .unwrap();
        assert_eq!(got, vec![3, 4, 5]);
        assert!(s
            .read_range(&mut src, ByteRange::new(6, 3).unwrap())
            .is_err());
    }
}