Skip to main content

asset_io/
structure.rs

1// Copyright 2026 Adobe. All rights reserved.
2// This file is licensed to you under the Apache License,
3// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
4// or the MIT license (http://opensource.org/licenses/MIT),
5// at your option.
6
7// Unless required by applicable law or agreed to in writing,
8// this software is distributed on an "AS IS" BASIS, WITHOUT
9// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
10// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
11// specific language governing permissions and limitations under
12// each license.
13
14//! Validated container structure.
15
16use std::{
17    borrow::Cow,
18    io::{Read, Seek, SeekFrom, Write},
19    sync::Arc,
20};
21
22use crate::{
23    error::{Error, Result},
24    handler::{ContainerHandler, ReadSeek, ReadWriteSeek},
25    io::Io,
26    item::{Extent, Item, ItemInfo, ItemKind},
27    range::ByteRange,
28    segment::{Name, Role, Segment, SegmentKind, DEFAULT_CHUNK_SIZE, MAX_SEGMENT_SIZE},
29    sink::{Chunk, Sink},
30    task::block_on,
31    walk::Node,
32};
33
34/// Upper bound on segments per asset. Bounds memory use on hostile inputs
35/// made of many tiny elements.
36pub const MAX_SEGMENTS: usize = 1 << 22;
37
38/// Index of a segment within its [`Structure`].
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
40pub struct SegmentId(u32);
41
42impl SegmentId {
43    /// The id of the segment at position `i` in [`Structure::segments`]. The index
44    /// is not checked against any structure; [`Structure::segment`] does that.
45    pub fn from_index(i: usize) -> Result<Self> {
46        u32::try_from(i)
47            .map(SegmentId)
48            .map_err(|_| Error::LimitExceeded {
49                what: "segment count",
50                limit: u32::MAX as u64,
51            })
52    }
53
54    /// Position in [`Structure::segments`].
55    pub fn index(self) -> usize {
56        self.0 as usize
57    }
58}
59
60/// One independently valid piece of a multi-part asset, such as one image of a
61/// Multi-Picture Format file.
62///
63/// Sub-assets are contiguous, in file order, and together cover every byte of the
64/// asset, so they can be listed as the parts of a C2PA multi-asset hash. A
65/// [`Structure`] always has at least one: the primary asset, which is the whole
66/// file when nothing else is embedded.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct SubAsset {
69    range: ByteRange,
70    segments: std::ops::Range<usize>,
71    media_type: Option<Cow<'static, str>>,
72    primary: bool,
73}
74
75impl SubAsset {
76    /// Where the sub-asset lies in the asset: absolute offset and length.
77    pub fn range(&self) -> ByteRange {
78        self.range
79    }
80
81    /// Indices (see [`SegmentId::index`]) of the segments the sub-asset is made of.
82    pub fn segments(&self) -> std::ops::Range<usize> {
83        self.segments.clone()
84    }
85
86    /// Media type of the sub-asset, or `None` when the container cannot tell (trailing
87    /// data after the last image).
88    pub fn media_type(&self) -> Option<&str> {
89        self.media_type.as_deref()
90    }
91
92    /// Whether this is the primary asset, the first sub-asset.
93    pub fn is_primary(&self) -> bool {
94        self.primary
95    }
96
97    /// `offset` relative to the start of the sub-asset, or `None` if it is outside
98    /// it. Hash exclusion ranges of a sub-asset are relative to the sub-asset.
99    pub fn relative(&self, offset: u64) -> Option<u64> {
100        (self.range.offset()..self.range.end())
101            .contains(&offset)
102            .then(|| offset - self.range.offset())
103    }
104}
105
106/// A named container unit or unnamed bytes in the asset's box view.
107///
108/// Boxes tile the asset in file order. They may combine several elements, such
109/// as a GIF application extension's sub-blocks; see [`Structure::boxes`].
110#[derive(Debug, Clone, PartialEq, Eq)]
111#[non_exhaustive]
112pub struct BoxInfo {
113    /// The container-defined name, or `None` for unnamed bytes.
114    pub name: Option<Cow<'static, str>>,
115    /// Where the box is.
116    pub range: ByteRange,
117    /// The ranges inside the box that hold asset metadata (XMP, EXIF).
118    pub metadata: Vec<ByteRange>,
119}
120
121/// A region of the file with a role, in file order.
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123#[non_exhaustive]
124pub struct Region {
125    /// Owning segment.
126    pub segment: SegmentId,
127    /// Header, payload or trailer.
128    pub role: Role,
129    /// Byte range.
130    pub range: ByteRange,
131}
132
133/// The parsed structure of an asset.
134///
135/// Invariants, enforced by [`StructureBuilder`]:
136/// - `segments` are in file order and tile `[0, total_size)` exactly;
137/// - no segment is empty and each fits `header + trailer <= range`;
138/// - every item extent lies inside the segment it names.
139///
140/// Something a container keeps with a structure for its own use; see
141/// [`StructureBuilder::attach`].
142pub(crate) trait Attached: std::any::Any + std::fmt::Debug + Send + Sync {
143    fn as_any(&self) -> &dyn std::any::Any;
144}
145
146impl<T: std::any::Any + std::fmt::Debug + Send + Sync> Attached for T {
147    fn as_any(&self) -> &dyn std::any::Any {
148        self
149    }
150}
151
152/// A `Structure` holds geometry, and whatever opaque state its container attached
153/// to it (see [`attachment`](crate::container_api::attachment)). It is `Send + Sync` and can be
154/// shared across threads for parallel reads.
155#[derive(Debug)]
156pub struct Structure {
157    handler: Arc<dyn ContainerHandler>,
158    media_type: Cow<'static, str>,
159    total_size: u64,
160    segments: Vec<Segment>,
161    items: Vec<Item>,
162    subassets: Vec<SubAsset>,
163    /// How many leading segments are the container's own structure. Segments from
164    /// here on are data beyond the end of it.
165    boxes: usize,
166    attachment: Option<Arc<dyn Attached>>,
167    /// Where the elements of [subdividing](Segment::subdivides) segments start
168    /// after the first, in file order; see [`StructureBuilder::split`].
169    splits: Vec<Split>,
170}
171
172/// A boundary inside a subdividing segment: an element starts here.
173#[derive(Debug, Clone, Copy)]
174struct Split {
175    at: u64,
176    header_len: u32,
177    name: Name,
178}
179
180impl Structure {
181    /// What the container [attached](StructureBuilder::attach) to this structure, if
182    /// it is a `T`. Handlers use it for state that is not geometry: how a payload is
183    /// encoded, or what a later write needs to know.
184    pub(crate) fn attachment<T: std::any::Any>(&self) -> Option<&T> {
185        self.attachment.as_deref()?.as_any().downcast_ref()
186    }
187
188    /// The bytes beyond the end of the container's own structure, up to the end of
189    /// the file: data after the last chunk or box, and, in a multi-image file,
190    /// everything after the primary image. `None` when there are none, and for
191    /// containers that do not report it.
192    ///
193    /// A box hash lists any boxes among them (the later images of a Multi-Picture
194    /// Format JPEG) as they are, and unnamed bytes at the end as one final box
195    /// (C2PA 2.4, 18.7.2); see [`complete_boxes`](Self::complete_boxes). A hash
196    /// of one part of a multi-asset file covers that part only and never
197    /// includes them.
198    pub fn trailing(&self) -> Option<ByteRange> {
199        let first = self.segments.get(self.boxes)?;
200        ByteRange::new(
201            first.range().offset(),
202            self.total_size - first.range().offset(),
203        )
204        .ok()
205    }
206
207    /// How many leading segments are the container's own structure.
208    pub(crate) fn box_count(&self) -> usize {
209        self.boxes
210    }
211
212    /// The sub-assets of the asset, in file order: contiguous, non-overlapping, and
213    /// covering every byte. A file that embeds nothing else has one, the whole
214    /// file. A Multi-Picture Format JPEG has one per image, plus one for any data
215    /// after the last image.
216    ///
217    /// This is geometry only. Whether to hash the sub-assets separately (a C2PA
218    /// multi-asset hash) or as one asset is the caller's decision.
219    pub fn subassets(&self) -> &[SubAsset] {
220        &self.subassets
221    }
222
223    /// The handler that parsed this asset.
224    pub(crate) fn handler(&self) -> &Arc<dyn ContainerHandler> {
225        &self.handler
226    }
227
228    /// The container's [id](ContainerHandler::id), for example `"jpeg"`.
229    pub fn container_id(&self) -> &str {
230        self.handler.id()
231    }
232
233    /// Media type, for example `image/jpeg`.
234    pub fn media_type(&self) -> &str {
235        &self.media_type
236    }
237
238    /// The container-defined box name of `element`, or `None` if the element is
239    /// not a named box. `segment` identifies the owning segment in this asset;
240    /// `element` may be a finer element reported by [`elements`](Self::elements).
241    /// Container knowledge, including parsed naming context, lives in the handler.
242    pub fn box_name(&self, segment: SegmentId, element: &Segment) -> Option<Cow<'static, str>> {
243        self.handler.box_name(self, segment, element)
244    }
245
246    /// Asset size in bytes.
247    pub fn total_size(&self) -> u64 {
248        self.total_size
249    }
250
251    /// All segments in file order.
252    pub fn segments(&self) -> &[Segment] {
253        &self.segments
254    }
255
256    /// Look up a segment.
257    pub fn segment(&self, id: SegmentId) -> Result<&Segment> {
258        self.segments
259            .get(id.index())
260            .ok_or(Error::NotFound { what: "segment" })
261    }
262
263    /// Every element of the file in order: each segment, with segments that
264    /// [subdivide](Segment::subdivides) replaced by their finer elements.
265    /// The elements tile the file exactly as the segments do.
266    ///
267    /// `f` receives the owning segment's id and the element. For most segments the
268    /// element is the segment itself. The finer elements were found when the asset
269    /// was parsed, so nothing is read. The same call works for every container;
270    /// callers never test the format.
271    pub fn elements<F>(&self, mut f: F) -> Result<()>
272    where
273        F: FnMut(SegmentId, &Segment) -> Result<()>,
274    {
275        for (i, seg) in self.segments.iter().enumerate() {
276            let id = SegmentId(i as u32);
277            if !seg.subdivides() {
278                f(id, seg)?;
279                continue;
280            }
281            let range = seg.range();
282            let from = self.splits.partition_point(|s| s.at < range.offset());
283            let to = self.splits.partition_point(|s| s.at < range.end());
284            let mut start = range.offset();
285            let mut header_len = seg.header().len() as u32;
286            let mut name = seg.name();
287            for split in self.splits[from..to].iter().chain(std::iter::once(&Split {
288                at: range.end(),
289                header_len: 0,
290                name: Name::None,
291            })) {
292                let len = split.at - start;
293                f(
294                    id,
295                    &Segment::new(ByteRange::new(start, len)?, header_len, 0, seg.kind(), name)?,
296                )?;
297                start = split.at;
298                header_len = split.header_len;
299                name = split.name;
300            }
301        }
302        Ok(())
303    }
304
305    /// The asset's boxes in file order, covering every byte once. Reads nothing.
306    ///
307    /// Elements are named by [`box_name`](Self::box_name). An element that
308    /// [continues](ContainerHandler::box_continues) the preceding box is combined
309    /// with it, such as a GIF application's data sub-blocks. Unnamed bytes are
310    /// retained with [`BoxInfo::name`] set to `None`, including trailing data.
311    ///
312    /// Unlike segments (writer-sized units) and elements (the finest tiling),
313    /// boxes describe the container's grouping of those elements.
314    pub fn boxes(&self) -> Result<Vec<BoxInfo>> {
315        self.collect_boxes(None)
316    }
317
318    /// [`boxes`](Self::boxes), grouping the segments carrying `item` under `name`.
319    ///
320    /// The item must belong to this structure. Each contiguous run of its
321    /// segments becomes one box, including framing and any other bytes in those
322    /// segments. Noncontiguous runs remain separate boxes with the same name.
323    /// All other boxes keep their container-defined names. Reads nothing.
324    pub fn boxes_with(&self, item: &Item, name: &str) -> Result<Vec<BoxInfo>> {
325        if !self.items.iter().any(|e| std::ptr::eq(e, item)) {
326            return Err(Error::InvalidFormat(
327                "box grouping requires an item from this structure".into(),
328            ));
329        }
330        self.collect_boxes(Some((item, name)))
331    }
332
333    fn collect_boxes(&self, group: Option<(&Item, &str)>) -> Result<Vec<BoxInfo>> {
334        let grouped: Vec<SegmentId> = group
335            .into_iter()
336            .flat_map(|(item, _)| item.extents().map(|e| e.segment()))
337            .collect();
338        let metadata: Vec<ByteRange> = self
339            .items
340            .iter()
341            .filter(|i| matches!(i.kind(), ItemKind::Xmp | ItemKind::Exif))
342            .flat_map(|i| i.extents().map(|e| e.range()))
343            .collect();
344        let mut boxes: Vec<BoxInfo> = Vec::new();
345        let mut previous_grouped = false;
346        self.elements(|id, element| {
347            let range = element.range();
348            if let Some((_, name)) = group.filter(|_| grouped.contains(&id)) {
349                match boxes.last_mut() {
350                    Some(last) if previous_grouped && last.range.end() == range.offset() => {
351                        last.range =
352                            ByteRange::new(last.range.offset(), last.range.len() + range.len())?;
353                    }
354                    _ => boxes.push(BoxInfo {
355                        name: Some(Cow::Owned(name.to_owned())),
356                        range,
357                        metadata: Vec::new(),
358                    }),
359                }
360                previous_grouped = true;
361                return Ok(());
362            }
363            let follows_group = previous_grouped;
364            previous_grouped = false;
365            if self.handler.box_continues(self, id, element) {
366                return match boxes.last_mut() {
367                    Some(last)
368                        if !follows_group
369                            && last.name.is_some()
370                            && last.range.end() == range.offset() =>
371                    {
372                        last.range =
373                            ByteRange::new(last.range.offset(), last.range.len() + range.len())?;
374                        Ok(())
375                    }
376                    _ => Err(Error::UnsupportedFeature(
377                        "box continuation follows no container box",
378                    )),
379                };
380            }
381            boxes.push(BoxInfo {
382                name: self.box_name(id, element),
383                range,
384                metadata: Vec::new(),
385            });
386            Ok(())
387        })?;
388        for b in &mut boxes {
389            b.metadata = metadata
390                .iter()
391                .filter(|m| b.range.contains(m))
392                .copied()
393                .collect();
394        }
395        Ok(boxes)
396    }
397
398    /// Every header/payload/trailer run of the file, in order, covering all bytes once.
399    pub fn regions(&self) -> impl Iterator<Item = Region> + '_ {
400        self.segments.iter().enumerate().flat_map(|(i, seg)| {
401            let segment = SegmentId(i as u32);
402            seg.regions().map(move |(role, range)| Region {
403                segment,
404                role,
405                range,
406            })
407        })
408    }
409
410    /// Every item, in declaration order.
411    pub fn items(&self) -> impl Iterator<Item = &Item> + '_ {
412        self.items.iter()
413    }
414
415    /// All items of a kind.
416    pub fn items_of(&self, kind: ItemKind) -> impl Iterator<Item = &Item> + '_ {
417        self.items.iter().filter(move |e| e.kind() == kind)
418    }
419
420    /// All items of a kind carrying `label` (see [`Item::label`]).
421    pub fn items_labelled<'a>(
422        &'a self,
423        kind: ItemKind,
424        label: &'a str,
425    ) -> impl Iterator<Item = &'a Item> + 'a {
426        self.items
427            .iter()
428            .filter(move |e| e.kind() == kind && e.label() == Some(label))
429    }
430
431    /// The items with an extent in segment `id`: what the segment holds.
432    pub fn items_in(&self, id: SegmentId) -> impl Iterator<Item = &Item> + '_ {
433        self.items.iter().filter(move |e| e.is_in(id))
434    }
435
436    /// Visit the container's element hierarchy in file order, parents first.
437    ///
438    /// Flat containers yield their segments. Nested ones (ISO BMFF) also yield the
439    /// elements inside segments, found lazily by reading only their headers. Callers
440    /// never test the format; the handler decides what the hierarchy is.
441    pub fn walk<R, F>(&self, src: &mut R, mut f: F) -> Result<()>
442    where
443        R: Read + Seek,
444        F: FnMut(&Node<'_>) -> Result<()>,
445    {
446        let src: &mut dyn ReadSeek = src;
447        self.handler.walk(self, src, &mut f)
448    }
449
450    /// The item of a kind: `Ok(None)` if absent, `Err(Ambiguous)` if several.
451    pub fn item(&self, kind: ItemKind) -> Result<Option<&Item>> {
452        let mut it = self.items_of(kind);
453        let first = it.next();
454        let extra = it.count();
455        match (first, extra) {
456            (None, _) => Ok(None),
457            (Some(e), 0) => Ok(Some(e)),
458            (Some(_), n) => Err(Error::Ambiguous {
459                what: kind.as_str(),
460                count: n + 1,
461            }),
462        }
463    }
464
465    /// Like [`item`](Self::item) but absence is an error.
466    pub fn require_item(&self, kind: ItemKind) -> Result<&Item> {
467        self.item(kind)?.ok_or(Error::NotFound {
468            what: kind.as_str(),
469        })
470    }
471
472    /// Whether the container's own structure can be represented entirely by
473    /// named boxes. Unnamed trailing bytes do not affect the result.
474    ///
475    /// Returns `false` for an empty structure, unnamed boxes within it, or
476    /// elements that cannot be assembled into boxes. Derived from the generic
477    /// [`boxes`](Self::boxes) view, including subdivisions and continuations;
478    /// this does not select a hashing or signing scheme.
479    pub fn supports_named_boxes(&self) -> bool {
480        let structure_end = self.segments[..self.boxes]
481            .last()
482            .map_or(0, |s| s.range().end());
483        structure_end != 0
484            && self.boxes().is_ok_and(|boxes| {
485                boxes
486                    .iter()
487                    .take_while(|b| b.range.offset() < structure_end)
488                    .all(|b| b.name.is_some())
489            })
490    }
491
492    /// The ranges a C2PA data hash (`c2pa.hash.data`) excludes when `item` is the
493    /// embedded manifest store.
494    ///
495    /// The container's C2PA embedding rules decide whether framing, checksums,
496    /// padding or only stored payload bytes are excluded; see
497    /// [`ContainerHandler::c2pa_data_hash_exclusions`]. Results are ordered,
498    /// nonempty, disjoint, nonadjacent and within the asset. Works on parsed and
499    /// planned structures without reading the source.
500    ///
501    /// The item must be a C2PA item of this structure, usually its
502    /// [`c2pa_item`](Self::c2pa_item). This neither interprets the manifest nor computes a hash.
503    /// Containers whose C2PA embedding uses another binding (ISO BMFF) return
504    /// [`Error::UnsupportedFeature`].
505    pub fn c2pa_data_hash_exclusions(&self, item: &Item) -> Result<Vec<ByteRange>> {
506        if item.kind() != ItemKind::C2pa || !self.items.iter().any(|e| std::ptr::eq(e, item)) {
507            return Err(Error::InvalidFormat(
508                "C2PA data-hash exclusions require a C2PA item from this structure".into(),
509            ));
510        }
511        let mut ranges = self.handler.c2pa_data_hash_exclusions(self, item)?;
512        for range in &ranges {
513            self.check_readable(*range)?;
514        }
515        ranges.retain(|range| !range.is_empty());
516        ranges.sort_by_key(ByteRange::offset);
517        let mut merged: Vec<ByteRange> = Vec::new();
518        for range in ranges {
519            if let Some(last) = merged.last_mut() {
520                if range.offset() <= last.end() {
521                    *last =
522                        ByteRange::new(last.offset(), last.end().max(range.end()) - last.offset())?;
523                    continue;
524                }
525            }
526            merged.push(range);
527        }
528        Ok(merged)
529    }
530
531    // ------------------------------------------------------------------
532    // Bounded data access
533    // ------------------------------------------------------------------
534
535    fn check_readable(&self, range: ByteRange) -> Result<()> {
536        if range.end() > self.total_size {
537            return Err(Error::invalid_segment(
538                range.offset(),
539                "range extends past end of asset",
540            ));
541        }
542        Ok(())
543    }
544
545    /// Read a range into memory. Fails above `MAX_SEGMENT_SIZE`; use
546    /// [`stream_range`](Self::stream_range) for large ranges.
547    pub fn read_range<R: Read + Seek>(&self, src: &mut R, range: ByteRange) -> Result<Vec<u8>> {
548        let mut out = Vec::new();
549        self.read_into(src, range, &mut out)?;
550        Ok(out)
551    }
552
553    /// Append a range to `out`. The range is validated against the asset size
554    /// before any allocation, and reads grow `out` only as data arrives.
555    fn read_into<R: Read + Seek + ?Sized>(
556        &self,
557        src: &mut R,
558        range: ByteRange,
559        out: &mut Vec<u8>,
560    ) -> Result<()> {
561        self.check_readable(range)?;
562        let total = (out.len() as u64).saturating_add(range.len());
563        if total > MAX_SEGMENT_SIZE {
564            return Err(Error::LimitExceeded {
565                what: "read size",
566                limit: MAX_SEGMENT_SIZE,
567            });
568        }
569        let start = out.len();
570        out.try_reserve(range.len() as usize)
571            .map_err(|_| Error::LimitExceeded {
572                what: "allocation",
573                limit: MAX_SEGMENT_SIZE,
574            })?;
575        src.seek(SeekFrom::Start(range.offset()))?;
576        Read::take(&mut *src, range.len()).read_to_end(out)?;
577        if (out.len() - start) as u64 != range.len() {
578            return Err(Error::invalid_segment(
579                range.offset(),
580                "unexpected end of data",
581            ));
582        }
583        Ok(())
584    }
585
586    /// Append `range` to `out` through `io`, within the same bounds as
587    /// [`read_into`](Self::read_into).
588    async fn read_in(&self, io: &mut Io, range: ByteRange, out: &mut Vec<u8>) -> Result<()> {
589        self.check_readable(range)?;
590        if (out.len() as u64).saturating_add(range.len()) > MAX_SEGMENT_SIZE {
591            return Err(Error::LimitExceeded {
592                what: "read size",
593                limit: MAX_SEGMENT_SIZE,
594            });
595        }
596        let bytes = io.read_vec(range.offset(), range.len() as usize).await?;
597        if out.is_empty() {
598            *out = bytes;
599        } else {
600            out.extend_from_slice(&bytes);
601        }
602        Ok(())
603    }
604
605    /// [`read_item`](Self::read_item), reading through `io`.
606    pub async fn read_item_async(&self, io: &mut Io, item: &Item) -> Result<Vec<u8>> {
607        let mut stored = Vec::new();
608        for extent in item.extents() {
609            self.read_in(io, extent.range, &mut stored).await?;
610        }
611        Ok(stored)
612    }
613
614    /// [`read_content`](Self::read_content), reading through `io`.
615    pub async fn read_content_async(&self, io: &mut Io, item: &Item) -> Result<Vec<u8>> {
616        item.transfer()
617            .decode(self.read_item_async(io, item).await?)
618    }
619
620    /// The asset's XMP packet, or `None` if it has none. Containers that store XMP
621    /// in several pieces return it reassembled.
622    pub fn xmp(&self, src: &mut dyn ReadSeek) -> Result<Option<Vec<u8>>> {
623        self.handler.read_xmp(self, src)
624    }
625
626    /// The C2PA manifest store item, or `None` if the asset has none. Several
627    /// stores are [`Error::Ambiguous`].
628    ///
629    /// When the store is kept as an `original` plus an `update` (ISO BMFF), this
630    /// is the `original`; [`c2pa_store`](Self::c2pa_store) reads the two combined.
631    /// A PDF that also holds the stores of earlier revisions (labelled
632    /// `superseded`) gives the latest, the active one. The item is what a caller
633    /// excludes from a hash or patches in place. Needs no I/O: the container
634    /// identified the store while parsing.
635    pub fn c2pa_item(&self) -> Result<Option<&Item>> {
636        use crate::segment::labels::{SUPERSEDED, UPDATE};
637        let mut stores = self
638            .items_of(ItemKind::C2pa)
639            .filter(|item| !matches!(item.label(), Some(UPDATE | SUPERSEDED)));
640        let found = stores.next();
641        let more = stores.count();
642        if more > 0 {
643            return Err(Error::Ambiguous {
644                what: "C2PA manifest store",
645                count: more + 1,
646            });
647        }
648        Ok(found)
649    }
650
651    /// The C2PA manifest store as a reader sees it, or `None` if the asset has
652    /// none: the [`c2pa_item`](Self::c2pa_item) with any transfer encoding undone,
653    /// an `update` appended to its `original` (ISO BMFF), and the stores of earlier
654    /// revisions read before it (PDF). The store is not interpreted.
655    pub fn c2pa_store<R: Read + Seek>(&self, src: &mut R) -> Result<Option<Vec<u8>>> {
656        block_on(self.total_size, src, |mut io| async move {
657            self.c2pa_store_async(&mut io).await
658        })
659    }
660
661    /// [`c2pa_store`](Self::c2pa_store), reading through `io`, for a
662    /// [`Task`](crate::task::Task) where the caller does the reads.
663    pub async fn c2pa_store_async(&self, io: &mut Io) -> Result<Option<Vec<u8>>> {
664        use crate::segment::labels::{ORIGINAL, SUPERSEDED, UPDATE};
665        let Some(item) = self.c2pa_item()? else {
666            return Ok(None);
667        };
668        let store = self.read_content_async(io, item).await?;
669        if item.label() == Some(ORIGINAL) {
670            if let Some(update) = self.items_labelled(ItemKind::C2pa, UPDATE).next() {
671                let update = self.read_content_async(io, update).await?;
672                return crate::jumbf::extend(&store, &update).map(Some);
673            }
674        }
675        let mut earlier: Option<Vec<u8>> = None;
676        for item in self.items_labelled(ItemKind::C2pa, SUPERSEDED) {
677            let next = self.read_content_async(io, item).await?;
678            earlier = Some(match earlier {
679                None => next,
680                Some(earlier) => crate::jumbf::combine_revisions(&earlier, &next)?,
681            });
682        }
683        match earlier {
684            None => Ok(Some(store)),
685            Some(earlier) => crate::jumbf::combine_revisions(&earlier, &store).map(Some),
686        }
687    }
688
689    /// Fill the C2PA store's placeholder in place: the counterpart of
690    /// [`c2pa_store`](Self::c2pa_store) for [`patch_exact`](Self::patch_exact).
691    ///
692    /// `store` is the whole store, as a reader sees it and as
693    /// [`Updates::set_c2pa`](crate::Updates::set_c2pa) takes it. Where the file holds
694    /// that store in parts (an ISO BMFF `original` and `update`, the stores of a PDF's
695    /// revisions), only the active part is patched, with what `store` adds to the
696    /// parts before it. Those must be unchanged, byte for byte: a patch cannot
697    /// rewrite earlier manifests, so a store that does not extend them is
698    /// [`Error::UnsupportedFeature`]. The patched length must match exactly, as
699    /// for `patch_exact`. `out` must contain the asset starting at offset 0.
700    pub fn patch_c2pa_store<W: Read + Write + Seek>(
701        &self,
702        out: &mut W,
703        store: &[u8],
704    ) -> Result<()> {
705        self.prepare_c2pa_patch(out, store)?.apply(out)
706    }
707
708    /// Check a [`patch_c2pa_store`](Self::patch_c2pa_store) against the asset in
709    /// `src`, without writing, and return it ready to apply to a copy of `src`.
710    ///
711    /// For a caller that writes its output to another stream: if this fails, the
712    /// store does not fit the placeholder, so the asset must be written instead.
713    pub fn prepare_c2pa_patch<R: Read + Seek>(
714        &self,
715        src: &mut R,
716        store: &[u8],
717    ) -> Result<C2paPatch<'_>> {
718        let (item, data) = block_on(self.total_size, src, |mut io| async move {
719            self.c2pa_patch_async(&mut io, store).await
720        })?;
721        let stored = item.transfer().encode(&data)?.into_owned();
722        // The container's refusal comes before a complaint about the length.
723        self.handler.check_patch(self, item, stored.len())?;
724        if stored.len() as u64 != item.len() {
725            return Err(Error::InvalidFormat(format!(
726                "replacement is {} bytes, the placeholder is {}",
727                stored.len(),
728                item.len()
729            )));
730        }
731        Ok(C2paPatch {
732            structure: self,
733            item,
734            stored,
735        })
736    }
737
738    /// The item [`patch_c2pa_store`](Self::patch_c2pa_store) writes, and what it
739    /// writes there.
740    async fn c2pa_patch_async<'s, 'd>(
741        &'s self,
742        io: &mut Io,
743        store: &'d [u8],
744    ) -> Result<(&'s Item, Cow<'d, [u8]>)> {
745        use crate::segment::labels::{ORIGINAL, SUPERSEDED, UPDATE};
746        let item = self.c2pa_item()?.ok_or(Error::NotFound {
747            what: "C2PA manifest store",
748        })?;
749        let not_extended = || {
750            Error::UnsupportedFeature(
751                "a patched C2PA store must keep the manifests stored before the active part",
752            )
753        };
754        if item.label() == Some(ORIGINAL) {
755            if let Some(update) = self.items_labelled(ItemKind::C2pa, UPDATE).next() {
756                let original = self.read_content_async(io, item).await?;
757                let addition =
758                    crate::jumbf::addition_to(&original, store)?.ok_or_else(not_extended)?;
759                return Ok((update, Cow::Owned(addition)));
760            }
761        }
762        let mut earlier: Option<Vec<u8>> = None;
763        for superseded in self.items_labelled(ItemKind::C2pa, SUPERSEDED) {
764            let next = self.read_content_async(io, superseded).await?;
765            earlier = Some(match earlier {
766                None => next,
767                Some(earlier) => crate::jumbf::combine_revisions(&earlier, &next)?,
768            });
769        }
770        let Some(earlier) = earlier else {
771            return Ok((item, Cow::Borrowed(store)));
772        };
773        // A latest store that a reader takes as a whole store, not an addition to the
774        // earlier ones, is patched with the whole store, as it is read.
775        let latest = self.read_content_async(io, item).await?;
776        let stands_alone = earlier == latest
777            || matches!(crate::jumbf::addition_to(&earlier, &latest), Ok(Some(_)))
778            || crate::jumbf::extend(&earlier, &latest).is_err();
779        if stands_alone {
780            return Ok((item, Cow::Borrowed(store)));
781        }
782        let addition = crate::jumbf::addition_to(&earlier, store)?.ok_or_else(not_extended)?;
783        Ok((item, Cow::Owned(addition)))
784    }
785
786    /// The boxes a C2PA box hash (`c2pa.hash.boxes`, C2PA 18.7) lists:
787    /// [`complete_boxes`](Self::complete_boxes) with the C2PA manifest store as one
788    /// box named `C2PA` and bytes after the structure as one named `c2pa.after`.
789    /// Works without a store (to plan one) and on planned structures; reads
790    /// nothing. Fails as `complete_boxes` does, and as
791    /// [`c2pa_item`](Self::c2pa_item) does for several stores.
792    pub fn c2pa_boxes(&self) -> Result<Vec<BoxInfo>> {
793        const C2PA_BOX: &str = "C2PA";
794        const AFTER_BOX: &str = "c2pa.after";
795        self.complete_boxes(self.c2pa_item()?.map(|item| (item, C2PA_BOX)), AFTER_BOX)
796    }
797
798    /// Every byte of the asset as named boxes, in file order, each byte once: the
799    /// generic [`boxes`](Self::boxes) view with no unnamed box left.
800    ///
801    /// With `group`, the segments of that item are one box with that name, as
802    /// [`boxes_with`](Self::boxes_with) gives them. Unnamed bytes past the end of
803    /// the container's own structure (data appended to a file) are one last box
804    /// named `trailing_name`. Boxes past the structure that are named (later
805    /// images of a Multi-Picture Format JPEG) are listed as they are.
806    ///
807    /// An element of the structure without a box name, or a named box after the
808    /// trailing bytes, is [`Error::UnsupportedFeature`]: the asset cannot be
809    /// described entirely by named boxes. Reads nothing.
810    pub fn complete_boxes(
811        &self,
812        group: Option<(&Item, &str)>,
813        trailing_name: &str,
814    ) -> Result<Vec<BoxInfo>> {
815        let boxes = match group {
816            Some((item, name)) => self.boxes_with(item, name)?,
817            None => self.boxes()?,
818        };
819        let structure_end = self
820            .segments
821            .get(self.boxes)
822            .map_or(self.total_size, |s| s.range().offset());
823        let unsupported = Error::UnsupportedFeature;
824        let mut result = Vec::with_capacity(boxes.len());
825        let mut after: Option<BoxInfo> = None;
826        for b in boxes {
827            if b.name.is_some() {
828                if after.is_some() {
829                    return Err(unsupported("named boxes after unnamed data"));
830                }
831                result.push(b);
832            } else {
833                if b.range.offset() < structure_end {
834                    return Err(unsupported("an element of the structure has no box name"));
835                }
836                match &mut after {
837                    Some(last) => {
838                        last.range = ByteRange::new(
839                            last.range.offset(),
840                            b.range.end() - last.range.offset(),
841                        )?;
842                        last.metadata.extend(b.metadata);
843                    }
844                    None => {
845                        after = Some(BoxInfo {
846                            name: Some(Cow::Owned(trailing_name.to_owned())),
847                            ..b
848                        });
849                    }
850                }
851            }
852        }
853        if let Some(after) = after {
854            result.push(after);
855        }
856        Ok(result)
857    }
858
859    /// Read an item's extents, concatenated: the bytes stored in the file.
860    pub fn read_item<R: Read + Seek + ?Sized>(&self, src: &mut R, item: &Item) -> Result<Vec<u8>> {
861        let mut out = Vec::new();
862        for extent in item.extents() {
863            self.read_into(src, extent.range, &mut out)?;
864        }
865        Ok(out)
866    }
867
868    /// Read an item's content: [`read_item`](Self::read_item), then the item's
869    /// [transfer encoding](Item::transfer) undone. For most items the two are the
870    /// same.
871    pub fn read_content<R: Read + Seek + ?Sized>(
872        &self,
873        src: &mut R,
874        item: &Item,
875    ) -> Result<Vec<u8>> {
876        let stored = self.read_item(src, item)?;
877        item.transfer().decode(stored)
878    }
879
880    /// Stream a range through a caller-owned buffer; no allocation.
881    pub fn stream_range<R, F>(
882        &self,
883        src: &mut R,
884        range: ByteRange,
885        buf: &mut [u8],
886        mut f: F,
887    ) -> Result<()>
888    where
889        R: Read + Seek,
890        F: FnMut(&[u8]) -> Result<()>,
891    {
892        self.check_readable(range)?;
893        if buf.is_empty() {
894            return Err(Error::InvalidFormat("empty stream buffer".into()));
895        }
896        src.seek(SeekFrom::Start(range.offset()))?;
897        let mut remaining = range.len();
898        while remaining > 0 {
899            let n = remaining.min(buf.len() as u64) as usize;
900            src.read_exact(&mut buf[..n])?;
901            f(&buf[..n])?;
902            remaining -= n as u64;
903        }
904        Ok(())
905    }
906
907    // ------------------------------------------------------------------
908    // Zero-copy access over a byte slice (for example a memory map)
909    // ------------------------------------------------------------------
910
911    /// Borrow `range` from `data`, which must hold the whole asset starting at
912    /// offset 0. No copy is made. `data` is only length-checked: it is the
913    /// caller's job to pass the bytes this structure was parsed from.
914    pub fn slice<'a>(&self, data: &'a [u8], range: ByteRange) -> Result<&'a [u8]> {
915        self.check_readable(range)?;
916        if (data.len() as u64) < self.total_size {
917            return Err(Error::invalid_segment(
918                data.len() as u64,
919                format!(
920                    "buffer holds {} bytes, asset is {}",
921                    data.len(),
922                    self.total_size
923                ),
924            ));
925        }
926        let bad = || Error::invalid_segment(range.offset(), "range does not fit in memory");
927        let start = usize::try_from(range.offset()).map_err(|_| bad())?;
928        let end = usize::try_from(range.end()).map_err(|_| bad())?;
929        data.get(start..end).ok_or_else(bad)
930    }
931
932    /// An item's bytes from `data`. Borrowed, with no copy, when the item has a
933    /// single extent; copied (up to `MAX_SEGMENT_SIZE`) when it has several.
934    pub fn slice_item<'a>(&self, data: &'a [u8], item: &Item) -> Result<Cow<'a, [u8]>> {
935        let mut extents = item.extents();
936        let Some(first) = extents.next() else {
937            return Ok(Cow::Borrowed(&[]));
938        };
939        let head = self.slice(data, first.range)?;
940        let Some(second) = extents.next() else {
941            return Ok(Cow::Borrowed(head));
942        };
943        let mut out = Vec::new();
944        for r in [first.range, second.range]
945            .into_iter()
946            .chain(extents.map(|p| p.range))
947        {
948            let b = self.slice(data, r)?;
949            if (out.len() as u64).saturating_add(b.len() as u64) > MAX_SEGMENT_SIZE {
950                return Err(Error::LimitExceeded {
951                    what: "read size",
952                    limit: MAX_SEGMENT_SIZE,
953                });
954            }
955            out.try_reserve(b.len()).map_err(|_| Error::LimitExceeded {
956                what: "allocation",
957                limit: MAX_SEGMENT_SIZE,
958            })?;
959            out.extend_from_slice(b);
960        }
961        Ok(Cow::Owned(out))
962    }
963
964    // ------------------------------------------------------------------
965    // Read-side sink
966    // ------------------------------------------------------------------
967
968    /// Deliver every byte of the asset to `sink`, in file order, tagged with its
969    /// segment and role: the read-side counterpart of [`write`](Self::write). Runs
970    /// the sink would skip ([`Sink::wants`]) are not read. Chunks are at most
971    /// `DEFAULT_CHUNK_SIZE` bytes and borrow one reused buffer.
972    pub fn read<R: Read + Seek>(&self, src: &mut R, sink: &mut dyn Sink) -> Result<()> {
973        sink.begin(self)?;
974        let mut buf = vec![0u8; DEFAULT_CHUNK_SIZE];
975        for r in self.regions() {
976            if !sink.wants(self.segment(r.segment)?, r.role) {
977                continue;
978            }
979            self.check_readable(r.range)?;
980            src.seek(SeekFrom::Start(r.range.offset()))?;
981            let mut offset = r.range.offset();
982            let mut remaining = r.range.len();
983            while remaining > 0 {
984                let n = remaining.min(buf.len() as u64) as usize;
985                src.read_exact(&mut buf[..n])?;
986                sink.chunk(Chunk {
987                    segment: r.segment,
988                    role: r.role,
989                    offset,
990                    data: &buf[..n],
991                })?;
992                offset += n as u64;
993                remaining -= n as u64;
994            }
995        }
996        Ok(())
997    }
998
999    /// Like [`read`](Self::read) over bytes already in memory
1000    /// (a memory map, say). Nothing is copied: each region reaches the sink as one
1001    /// chunk borrowed from `data`. A sink that wants parallelism can split the
1002    /// chunks itself.
1003    pub fn read_slice(&self, data: &[u8], sink: &mut dyn Sink) -> Result<()> {
1004        sink.begin(self)?;
1005        for r in self.regions() {
1006            if !sink.wants(self.segment(r.segment)?, r.role) {
1007                continue;
1008            }
1009            sink.chunk(Chunk {
1010                segment: r.segment,
1011                role: r.role,
1012                offset: r.range.offset(),
1013                data: self.slice(data, r.range)?,
1014            })?;
1015        }
1016        Ok(())
1017    }
1018
1019    // ------------------------------------------------------------------
1020    // In-place patching
1021    // ------------------------------------------------------------------
1022
1023    /// Overwrite an item's bytes in an already-written stream.
1024    ///
1025    /// `data` must fit the item's total capacity; the remainder is
1026    /// zero-filled so the structure is unchanged. Container checksums that cover
1027    /// the patched payload (PNG CRC) are recomputed. `out` must contain the
1028    /// asset starting at offset 0.
1029    pub fn patch<W: Read + Write + Seek>(
1030        &self,
1031        out: &mut W,
1032        item: &Item,
1033        data: &[u8],
1034    ) -> Result<()> {
1035        self.handler.check_patch(self, item, data.len())?;
1036        let capacity = item.len();
1037        if data.len() as u64 > capacity {
1038            return Err(Error::LimitExceeded {
1039                what: "patch exceeds payload capacity",
1040                limit: capacity,
1041            });
1042        }
1043        let mut rest = data;
1044        for extent in item.extents() {
1045            let take = (rest.len() as u64).min(extent.range.len()) as usize;
1046            out.seek(SeekFrom::Start(extent.range.offset()))?;
1047            out.write_all(&rest[..take])?;
1048            write_zeros(out, extent.range.len() - take as u64)?;
1049            rest = &rest[take..];
1050        }
1051        // Extents are in order; fix each segment's trailer once.
1052        let mut last: Option<SegmentId> = None;
1053        for extent in item.extents() {
1054            if last != Some(extent.segment) {
1055                last = Some(extent.segment);
1056                self.fix_trailer(out, extent.segment)?;
1057            }
1058        }
1059        out.flush()?;
1060        Ok(())
1061    }
1062
1063    /// Write this asset to `out` with `updates` applied, delivering every output
1064    /// byte to `sink`, and return the structure of what was written. `src` must be
1065    /// the stream this structure was parsed from. `out` is only written to, from its
1066    /// current position. The container's handler does the work; callers never name
1067    /// the format.
1068    pub fn write(
1069        &self,
1070        src: &mut dyn ReadSeek,
1071        out: &mut dyn Write,
1072        updates: &crate::Updates,
1073        sink: &mut dyn crate::sink::Sink,
1074    ) -> Result<Structure> {
1075        self.handler.write(self, src, out, updates, sink)
1076    }
1077
1078    /// The structure `write` would produce for `updates`, without writing: where each
1079    /// item would land, and the total size. `src` must be the stream this
1080    /// structure was parsed from.
1081    ///
1082    /// The result is the one `write` returns, so a caller can learn where a
1083    /// manifest will go (and size a hash exclusion for it) before producing any
1084    /// output. A container that cannot plan reports [`Error::UnsupportedFormat`].
1085    pub fn plan(&self, src: &mut dyn ReadSeek, updates: &crate::Updates) -> Result<Structure> {
1086        self.handler.plan(self, src, updates)
1087    }
1088
1089    /// Fill a placeholder: overwrite an item's bytes, in place, with `data` of
1090    /// exactly the same length.
1091    ///
1092    /// This is how a signed manifest replaces the placeholder it was sized from.
1093    /// Bytes outside the payload (box sizes, offsets, everything a hash or an
1094    /// offset table was computed over) are not touched, so none of them can move.
1095    /// Unlike [`patch`](Self::patch), which zero-fills a shorter `data`, a length
1096    /// mismatch is an error: it means the placeholder was not sized correctly.
1097    ///
1098    /// Writing the store again with `set_c2pa` is not a substitute: that is free
1099    /// to change the size.
1100    ///
1101    /// `data` is the content, not what is stored: an item with a
1102    /// [transfer encoding](Item::transfer) (SVG's base64) has `data` encoded first,
1103    /// and it is the encoded length that must match.
1104    pub fn patch_exact<W: Read + Write + Seek>(
1105        &self,
1106        out: &mut W,
1107        item: &Item,
1108        data: &[u8],
1109    ) -> Result<()> {
1110        let stored = item.transfer().encode(data)?;
1111        // The container's refusal comes before a complaint about the length.
1112        self.handler.check_patch(self, item, stored.len())?;
1113        if stored.len() as u64 != item.len() {
1114            return Err(Error::InvalidFormat(format!(
1115                "replacement is {} bytes, the placeholder is {}",
1116                stored.len(),
1117                item.len()
1118            )));
1119        }
1120        self.patch(out, item, &stored)
1121    }
1122
1123    fn fix_trailer<W: Read + Write + Seek>(&self, out: &mut W, id: SegmentId) -> Result<()> {
1124        let out: &mut dyn ReadWriteSeek = out;
1125        self.handler.fix_trailer(out, self, id)
1126    }
1127}
1128
1129/// A C2PA store patch checked against an asset by
1130/// [`Structure::prepare_c2pa_patch`], ready to write.
1131#[derive(Debug)]
1132pub struct C2paPatch<'s> {
1133    structure: &'s Structure,
1134    item: &'s Item,
1135    /// What the item holds after the patch, transfer-encoded.
1136    stored: Vec<u8>,
1137}
1138
1139impl C2paPatch<'_> {
1140    /// Write the patch into `out`, which must hold the asset the patch was
1141    /// prepared from, starting at offset 0.
1142    pub fn apply<W: Read + Write + Seek>(&self, out: &mut W) -> Result<()> {
1143        self.structure.patch(out, self.item, &self.stored)
1144    }
1145}
1146
1147fn write_zeros<W: Write>(w: &mut W, mut n: u64) -> Result<()> {
1148    static ZEROS: [u8; 4096] = [0; 4096];
1149    while n > 0 {
1150        let k = n.min(ZEROS.len() as u64) as usize;
1151        w.write_all(&ZEROS[..k])?;
1152        n -= k as u64;
1153    }
1154    Ok(())
1155}
1156
1157/// Builds a [`Structure`], rejecting anything that would violate its invariants.
1158#[derive(Debug)]
1159pub struct StructureBuilder {
1160    handler: Arc<dyn ContainerHandler>,
1161    media_type: Cow<'static, str>,
1162    total_size: u64,
1163    cursor: u64,
1164    segments: Vec<Segment>,
1165    items: Vec<Item>,
1166    /// Segment index and media type where each sub-asset after the primary starts.
1167    sub_starts: Vec<(usize, Option<Cow<'static, str>>)>,
1168    /// Segment index where data beyond the container's structure starts, if declared.
1169    boxes: Option<usize>,
1170    attachment: Option<Arc<dyn Attached>>,
1171    splits: Vec<Split>,
1172}
1173
1174impl StructureBuilder {
1175    /// Start a structure for an asset of known size, owned by `handler`.
1176    pub fn new(
1177        handler: Arc<dyn ContainerHandler>,
1178        media_type: impl Into<Cow<'static, str>>,
1179        total_size: u64,
1180    ) -> Self {
1181        Self {
1182            handler,
1183            media_type: media_type.into(),
1184            total_size,
1185            cursor: 0,
1186            segments: Vec::new(),
1187            items: Vec::new(),
1188            sub_starts: Vec::new(),
1189            boxes: None,
1190            attachment: None,
1191            splits: Vec::new(),
1192        }
1193    }
1194
1195    /// Keep `value` with the structure, for the container's own use later (read it
1196    /// back with [`crate::container_api::attachment`]). It is opaque to everything else. One
1197    /// value is kept; a second replaces the first.
1198    pub fn attach<T: std::any::Any + std::fmt::Debug + Send + Sync>(
1199        &mut self,
1200        value: T,
1201    ) -> &mut Self {
1202        self.attachment = Some(Arc::new(value));
1203        self
1204    }
1205
1206    pub(crate) fn attach_shared(&mut self, value: Option<Arc<dyn Attached>>) {
1207        self.attachment = value;
1208    }
1209
1210    /// Declare that the container's own structure ends here: segments pushed from
1211    /// now on are data beyond it (see [`Structure::trailing`]). Without a call, every
1212    /// segment is part of the structure.
1213    pub fn end_boxes(&mut self) -> Result<()> {
1214        if self.boxes.is_some() {
1215            return Err(Error::InvalidFormat("structure end declared twice".into()));
1216        }
1217        self.boxes = Some(self.segments.len());
1218        Ok(())
1219    }
1220
1221    /// Declare that the next segment pushed starts a new [`SubAsset`]. The first
1222    /// sub-asset, the primary, starts at the first segment without a call.
1223    /// `media_type` is `None` for data the container cannot identify.
1224    pub fn begin_subasset(&mut self, media_type: Option<Cow<'static, str>>) -> Result<()> {
1225        let at = self.segments.len();
1226        let last = self.sub_starts.last().map_or(0, |s| s.0);
1227        if at == 0 || at == last {
1228            return Err(Error::InvalidFormat("empty sub-asset".into()));
1229        }
1230        self.sub_starts.push((at, media_type));
1231        Ok(())
1232    }
1233
1234    /// Undo the last [`begin_subasset`](Self::begin_subasset) and everything pushed
1235    /// since, for a parser that found the sub-asset was not one after all. Returns
1236    /// the offset where it started, which is also the cursor again.
1237    ///
1238    /// Fails if there is no sub-asset to undo, or if an item already refers to one
1239    /// of the segments being removed.
1240    pub fn rollback_subasset(&mut self) -> Result<u64> {
1241        let Some(&(at, _)) = self.sub_starts.last() else {
1242            return Err(Error::InvalidFormat("no sub-asset to roll back".into()));
1243        };
1244        if self
1245            .items
1246            .iter()
1247            .any(|e| e.extents().any(|p| p.segment().index() >= at))
1248        {
1249            return Err(Error::InvalidFormat(
1250                "an item refers to the sub-asset being rolled back".into(),
1251            ));
1252        }
1253        let start = self
1254            .segments
1255            .get(at)
1256            .map_or(self.cursor, |s| s.range().offset());
1257        self.segments.truncate(at);
1258        self.sub_starts.pop();
1259        self.cursor = start;
1260        Ok(start)
1261    }
1262
1263    /// Offset where the next segment must start.
1264    pub fn cursor(&self) -> u64 {
1265        self.cursor
1266    }
1267
1268    /// Append a segment. It must start at the cursor and end within the asset.
1269    pub fn push(&mut self, seg: Segment) -> Result<SegmentId> {
1270        if self.segments.len() + self.splits.len() >= MAX_SEGMENTS {
1271            return Err(Error::LimitExceeded {
1272                what: "segments",
1273                limit: MAX_SEGMENTS as u64,
1274            });
1275        }
1276        let ext = seg.range();
1277        if ext.offset() != self.cursor {
1278            return Err(Error::invalid_segment(
1279                ext.offset(),
1280                format!("segment must start at {} (gap or overlap)", self.cursor),
1281            ));
1282        }
1283        if ext.end() > self.total_size {
1284            return Err(Error::invalid_segment(
1285                ext.offset(),
1286                "segment extends past end of asset",
1287            ));
1288        }
1289        let id = SegmentId::from_index(self.segments.len())?;
1290        self.cursor = ext.end();
1291        self.segments.push(seg);
1292        Ok(id)
1293    }
1294
1295    /// Append a segment at the cursor from its three lengths.
1296    pub fn push_span(
1297        &mut self,
1298        kind: SegmentKind,
1299        name: Name,
1300        header_len: u32,
1301        payload_len: u64,
1302        trailer_len: u16,
1303    ) -> Result<SegmentId> {
1304        let total = (header_len as u64)
1305            .checked_add(payload_len)
1306            .and_then(|v| v.checked_add(trailer_len as u64))
1307            .ok_or_else(|| Error::invalid_segment(self.cursor, "segment length overflows"))?;
1308        let seg = Segment::new(
1309            ByteRange::new(self.cursor, total)?,
1310            header_len,
1311            trailer_len,
1312            kind,
1313            name,
1314        )?;
1315        self.push(seg)
1316    }
1317
1318    /// Like [`push_span`](Self::push_span), for a container where each item of
1319    /// metadata is one segment, as chunks are: the segment's payload is also
1320    /// declared as the item `info` describes.
1321    pub fn push_item(
1322        &mut self,
1323        kind: SegmentKind,
1324        name: Name,
1325        header_len: u32,
1326        payload_len: u64,
1327        trailer_len: u16,
1328        info: ItemInfo,
1329    ) -> Result<SegmentId> {
1330        let id = self.push_span(kind, name, header_len, payload_len, trailer_len)?;
1331        self.item_of_segments(info, &[id])?;
1332        Ok(id)
1333    }
1334
1335    /// Append one unnamed segment of [`Other`](SegmentKind::Other) kind for
1336    /// whatever is left of the asset, if anything: trailing data the container does
1337    /// not account for.
1338    pub fn push_tail(&mut self) -> Result<()> {
1339        if self.cursor < self.total_size {
1340            self.push_span(
1341                SegmentKind::Other,
1342                Name::None,
1343                0,
1344                self.total_size - self.cursor,
1345                0,
1346            )?;
1347        }
1348        Ok(())
1349    }
1350
1351    /// Segment already pushed.
1352    pub fn segment(&self, id: SegmentId) -> Result<&Segment> {
1353        self.segments
1354            .get(id.index())
1355            .ok_or(Error::NotFound { what: "segment" })
1356    }
1357
1358    /// Record that pushed segment `id` holds a finer element starting at `at`,
1359    /// framed by `header_len` bytes and named `name`: the segment
1360    /// [subdivides](Segment::subdivides), and its first element runs from its own
1361    /// start to its first split. Splits are recorded in file order, inside the
1362    /// segment's payload, and count towards [`MAX_SEGMENTS`].
1363    pub fn split(&mut self, id: SegmentId, at: u64, header_len: u32, name: Name) -> Result<()> {
1364        if self.segments.len() + self.splits.len() >= MAX_SEGMENTS {
1365            return Err(Error::LimitExceeded {
1366                what: "segment count",
1367                limit: MAX_SEGMENTS as u64,
1368            });
1369        }
1370        let seg = self
1371            .segments
1372            .get_mut(id.index())
1373            .ok_or(Error::NotFound { what: "segment" })?;
1374        let fits = at
1375            .checked_add(u64::from(header_len))
1376            .is_some_and(|end| end <= seg.range().end());
1377        if at < seg.payload().offset()
1378            || !fits
1379            || self.splits.last().is_some_and(|last| last.at >= at)
1380        {
1381            return Err(Error::invalid_segment(
1382                at,
1383                "split out of order or outside its segment",
1384            ));
1385        }
1386        *seg = seg.with_subdivision();
1387        self.splits.push(Split {
1388            at,
1389            header_len,
1390            name,
1391        });
1392        Ok(())
1393    }
1394
1395    /// Copy the splits of `src`'s segment `from` to pushed segment `id`, which
1396    /// holds the same bytes.
1397    pub(crate) fn split_like(
1398        &mut self,
1399        id: SegmentId,
1400        src: &Structure,
1401        from: SegmentId,
1402    ) -> Result<()> {
1403        let from = src.segment(from)?.range();
1404        let to = self.segment(id)?.range().offset();
1405        let first = src.splits.partition_point(|s| s.at < from.offset());
1406        for split in src.splits[first..].iter().take_while(|s| s.at < from.end()) {
1407            self.split(
1408                id,
1409                to + (split.at - from.offset()),
1410                split.header_len,
1411                split.name,
1412            )?;
1413        }
1414        Ok(())
1415    }
1416
1417    /// Declare an item whose extents are the payloads of whole segments.
1418    pub fn item_of_segments(&mut self, info: ItemInfo, ids: &[SegmentId]) -> Result<()> {
1419        let mut extents = Vec::with_capacity(ids.len());
1420        for &id in ids {
1421            extents.push((id, self.segment(id)?.payload()));
1422        }
1423        self.item(info, &extents)
1424    }
1425
1426    /// Declare an item from explicit `(segment, range)` extents, in logical order.
1427    /// Each range must lie within its segment.
1428    pub fn item(&mut self, info: ItemInfo, extents: &[(SegmentId, ByteRange)]) -> Result<()> {
1429        let mut it = extents.iter();
1430        let Some(&(sid, range)) = it.next() else {
1431            return Err(Error::InvalidFormat(
1432                "item needs at least one extent".into(),
1433            ));
1434        };
1435        let first = self.make_extent(sid, range)?;
1436        let mut rest = Vec::new();
1437        for &(sid, range) in it {
1438            rest.push(self.make_extent(sid, range)?);
1439        }
1440        self.items.push(Item { info, first, rest });
1441        Ok(())
1442    }
1443
1444    fn make_extent(&self, segment: SegmentId, range: ByteRange) -> Result<Extent> {
1445        let seg = self.segment(segment)?;
1446        if !seg.range().contains(&range) {
1447            return Err(Error::invalid_segment(
1448                range.offset(),
1449                "item extent lies outside its segment",
1450            ));
1451        }
1452        Ok(Extent { range, segment })
1453    }
1454
1455    /// Finish. The segments must cover the whole asset.
1456    pub fn finish(self) -> Result<Structure> {
1457        if self.cursor != self.total_size {
1458            return Err(Error::invalid_segment(
1459                self.cursor,
1460                format!(
1461                    "segments cover {} of {} bytes",
1462                    self.cursor, self.total_size
1463                ),
1464            ));
1465        }
1466        if self
1467            .sub_starts
1468            .last()
1469            .is_some_and(|s| s.0 >= self.segments.len())
1470        {
1471            return Err(Error::InvalidFormat("empty sub-asset".into()));
1472        }
1473        let mut subassets = Vec::with_capacity(self.sub_starts.len() + 1);
1474        let mut start = 0usize;
1475        let mut media = Some(self.media_type.clone());
1476        for (i, next) in self
1477            .sub_starts
1478            .iter()
1479            .map(|(s, m)| (*s, m.clone()))
1480            .chain(std::iter::once((self.segments.len(), None)))
1481            .enumerate()
1482        {
1483            let (end, next_media) = next;
1484            let from = self
1485                .segments
1486                .get(start)
1487                .map_or(self.total_size, |s| s.range().offset());
1488            let to = self
1489                .segments
1490                .get(end)
1491                .map_or(self.total_size, |s| s.range().offset());
1492            subassets.push(SubAsset {
1493                range: ByteRange::new(from, to - from)?,
1494                segments: start..end,
1495                media_type: media,
1496                primary: i == 0,
1497            });
1498            start = end;
1499            media = next_media;
1500        }
1501        let boxes = self.boxes.unwrap_or(self.segments.len());
1502        if boxes > self.segments.len() {
1503            return Err(Error::InvalidFormat(
1504                "structure ends after the last segment".into(),
1505            ));
1506        }
1507        Ok(Structure {
1508            handler: self.handler,
1509            media_type: self.media_type,
1510            total_size: self.total_size,
1511            segments: self.segments,
1512            items: self.items,
1513            subassets,
1514            boxes,
1515            attachment: self.attachment,
1516            splits: self.splits,
1517        })
1518    }
1519}
1520
1521#[cfg(test)]
1522mod tests {
1523    use super::*;
1524    use crate::container_api::{BoxFuture, FormatSpec};
1525
1526    /// A handler that only exists to own structures in these tests.
1527    #[derive(Debug)]
1528    struct TestHandler;
1529
1530    impl ContainerHandler for TestHandler {
1531        fn id(&self) -> &'static str {
1532            "test"
1533        }
1534
1535        fn formats(&self) -> &[FormatSpec] {
1536            const F: &[FormatSpec] = &[FormatSpec::new("application/x-test", "test")];
1537            F
1538        }
1539
1540        fn box_continues(&self, structure: &Structure, segment: SegmentId, _: &Segment) -> bool {
1541            structure.attachment::<SegmentId>() == Some(&segment)
1542        }
1543
1544        fn parse_async(self: Arc<Self>, _: crate::io::Io) -> BoxFuture<'static, Result<Structure>> {
1545            Box::pin(async { Err(Error::UnsupportedFormat) })
1546        }
1547
1548        fn write(
1549            &self,
1550            _: &Structure,
1551            _: &mut dyn ReadSeek,
1552            _: &mut dyn Write,
1553            _: &crate::Updates,
1554            _: &mut dyn crate::Sink,
1555        ) -> Result<Structure> {
1556            Err(Error::UnsupportedFormat)
1557        }
1558    }
1559
1560    fn builder(total: u64) -> StructureBuilder {
1561        StructureBuilder::new(Arc::new(TestHandler), "application/x-test", total)
1562    }
1563
1564    #[test]
1565    fn named_box_support_requires_a_nonempty_named_structure() {
1566        assert!(!builder(0).finish().unwrap().supports_named_boxes());
1567
1568        let mut b = builder(8);
1569        b.push_span(SegmentKind::Other, Name::FourCC(*b"HEAD"), 0, 8, 0)
1570            .unwrap();
1571        assert!(b.finish().unwrap().supports_named_boxes());
1572    }
1573
1574    #[test]
1575    fn named_box_support_checks_subdivisions_not_just_segments() {
1576        let mut b = builder(8);
1577        let id = b
1578            .push_span(SegmentKind::MediaData, Name::FourCC(*b"SCAN"), 0, 8, 0)
1579            .unwrap();
1580        b.split(id, 4, 0, Name::None).unwrap();
1581        let s = b.finish().unwrap();
1582        assert!(s.box_name(id, s.segment(id).unwrap()).is_some());
1583        assert!(!s.supports_named_boxes());
1584    }
1585
1586    #[test]
1587    fn boxes_keep_unnamed_bytes_without_hashing_restrictions() {
1588        let mut b = builder(12);
1589        for name in [Name::FourCC(*b"HEAD"), Name::None, Name::FourCC(*b"TAIL")] {
1590            b.push_span(SegmentKind::Other, name, 0, 4, 0).unwrap();
1591        }
1592        let s = b.finish().unwrap();
1593        let boxes = s.boxes().unwrap();
1594        assert_eq!(
1595            boxes.iter().map(|b| b.name.as_deref()).collect::<Vec<_>>(),
1596            [Some("HEAD"), None, Some("TAIL")]
1597        );
1598        assert!(!s.supports_named_boxes());
1599        for (i, b) in boxes.iter().enumerate() {
1600            assert_eq!(b.range, ByteRange::new(i as u64 * 4, 4).unwrap());
1601        }
1602        assert!(matches!(
1603            s.complete_boxes(None, "after"),
1604            Err(Error::UnsupportedFeature(_))
1605        ));
1606    }
1607
1608    #[test]
1609    fn grouping_uses_item_membership_not_the_supplied_name() {
1610        let mut b = builder(24);
1611        let mut ids = Vec::new();
1612        for _ in 0..6 {
1613            ids.push(
1614                b.push_span(SegmentKind::Metadata, Name::FourCC(*b"C2PA"), 0, 4, 0)
1615                    .unwrap(),
1616            );
1617        }
1618        b.split(ids[1], 6, 0, Name::Marker(0x01)).unwrap();
1619        b.item_of_segments(ItemInfo::xmp(), &[ids[1], ids[2], ids[4]])
1620            .unwrap();
1621        let s = b.finish().unwrap();
1622        let item = s.require_item(ItemKind::Xmp).unwrap();
1623        let name = String::from("C2PA");
1624        let boxes = s.boxes_with(item, &name).unwrap();
1625        drop(name);
1626        assert_eq!(
1627            boxes.iter().map(|b| b.range).collect::<Vec<_>>(),
1628            [(0, 4), (4, 8), (12, 4), (16, 4), (20, 4)]
1629                .map(|(offset, len)| ByteRange::new(offset, len).unwrap())
1630        );
1631        assert!(boxes.iter().all(|b| b.name.as_deref() == Some("C2PA")));
1632        assert_eq!(
1633            boxes[1].metadata,
1634            [ByteRange::new(4, 4).unwrap(), ByteRange::new(8, 4).unwrap()]
1635        );
1636        assert_eq!(boxes[3].metadata, [ByteRange::new(16, 4).unwrap()]);
1637        assert_eq!(s.boxes().unwrap().len(), 7);
1638    }
1639
1640    #[test]
1641    fn box_continuations_preserve_metadata_and_do_not_depend_on_names() {
1642        let mut b = builder(8);
1643        let first = b
1644            .push_span(SegmentKind::Metadata, Name::FourCC(*b"C2PA"), 0, 4, 0)
1645            .unwrap();
1646        let rest = b
1647            .push_span(SegmentKind::Metadata, Name::None, 0, 4, 0)
1648            .unwrap();
1649        b.attach(rest);
1650        b.item_of_segments(ItemInfo::xmp(), &[first, rest]).unwrap();
1651        let s = b.finish().unwrap();
1652        let boxes = s.boxes().unwrap();
1653        assert_eq!(boxes.len(), 1);
1654        assert_eq!(boxes[0].name.as_deref(), Some("C2PA"));
1655        assert_eq!(boxes[0].range, ByteRange::new(0, 8).unwrap());
1656        assert!(s.supports_named_boxes());
1657        assert_eq!(
1658            boxes[0].metadata,
1659            [ByteRange::new(0, 4).unwrap(), ByteRange::new(4, 4).unwrap()]
1660        );
1661    }
1662
1663    #[test]
1664    fn a_continuation_needs_a_container_box_not_an_unrelated_group() {
1665        for first_name in [Name::None, Name::FourCC(*b"HEAD")] {
1666            let mut b = builder(8);
1667            let first = b
1668                .push_span(SegmentKind::Metadata, first_name, 0, 4, 0)
1669                .unwrap();
1670            let rest = b
1671                .push_span(SegmentKind::Metadata, Name::None, 0, 4, 0)
1672                .unwrap();
1673            b.attach(rest);
1674            b.item_of_segments(ItemInfo::xmp(), &[first]).unwrap();
1675            let s = b.finish().unwrap();
1676            if first_name.is_none() {
1677                assert!(matches!(s.boxes(), Err(Error::UnsupportedFeature(_))));
1678                assert!(!s.supports_named_boxes());
1679            } else {
1680                assert_eq!(s.boxes().unwrap().len(), 1);
1681            }
1682            assert!(matches!(
1683                s.boxes_with(s.require_item(ItemKind::Xmp).unwrap(), "custom"),
1684                Err(Error::UnsupportedFeature(_))
1685            ));
1686        }
1687    }
1688
1689    #[test]
1690    fn only_the_c2pa_view_names_and_combines_trailing_bytes() {
1691        let mut b = builder(12);
1692        b.push_span(SegmentKind::Other, Name::FourCC(*b"HEAD"), 0, 4, 0)
1693            .unwrap();
1694        b.end_boxes().unwrap();
1695        for _ in 0..2 {
1696            b.push_span(SegmentKind::Other, Name::None, 0, 4, 0)
1697                .unwrap();
1698        }
1699        let s = b.finish().unwrap();
1700        let boxes = s.boxes().unwrap();
1701        assert_eq!(boxes.len(), 3);
1702        assert!(boxes[1..].iter().all(|b| b.name.is_none()));
1703        assert!(s.supports_named_boxes());
1704        let c2pa = s.complete_boxes(None, "after").unwrap();
1705        assert_eq!(c2pa.len(), 2);
1706        assert_eq!(c2pa[1].name.as_deref(), Some("after"));
1707        assert_eq!(c2pa[1].range, ByteRange::new(4, 8).unwrap());
1708    }
1709
1710    #[test]
1711    fn only_complete_boxes_rejects_boxes_after_unnamed_trailing_data() {
1712        let mut b = builder(12);
1713        b.push_span(SegmentKind::Other, Name::FourCC(*b"HEAD"), 0, 4, 0)
1714            .unwrap();
1715        b.end_boxes().unwrap();
1716        b.push_span(SegmentKind::Other, Name::None, 0, 4, 0)
1717            .unwrap();
1718        b.push_span(SegmentKind::Other, Name::FourCC(*b"TAIL"), 0, 4, 0)
1719            .unwrap();
1720        let s = b.finish().unwrap();
1721        assert_eq!(s.boxes().unwrap().len(), 3);
1722        assert!(matches!(
1723            s.complete_boxes(None, "after"),
1724            Err(Error::UnsupportedFeature(_))
1725        ));
1726    }
1727
1728    #[test]
1729    fn subassets_tile_and_default_to_one() {
1730        let mut b = builder(30);
1731        b.push_span(SegmentKind::Preamble, Name::None, 30, 0, 0)
1732            .unwrap();
1733        let s = b.finish().unwrap();
1734        assert_eq!(s.subassets().len(), 1);
1735        assert!(s.subassets()[0].is_primary());
1736        assert_eq!(s.subassets()[0].range(), ByteRange::new(0, 30).unwrap());
1737
1738        let mut b = builder(30);
1739        assert!(b.begin_subasset(None).is_err(), "nothing pushed yet");
1740        b.push_span(SegmentKind::Preamble, Name::None, 10, 0, 0)
1741            .unwrap();
1742        b.begin_subasset(Some("a/b".into())).unwrap();
1743        assert!(b.begin_subasset(None).is_err(), "empty sub-asset");
1744        b.push_span(SegmentKind::Other, Name::None, 20, 0, 0)
1745            .unwrap();
1746        let s = b.finish().unwrap();
1747        let subs = s.subassets();
1748        assert_eq!(subs[0].range(), ByteRange::new(0, 10).unwrap());
1749        assert_eq!(subs[1].range(), ByteRange::new(10, 20).unwrap());
1750        assert_eq!(subs[1].segments(), 1..2);
1751        assert_eq!(subs[1].media_type(), Some("a/b"));
1752
1753        let mut b = builder(30);
1754        b.push_span(SegmentKind::Preamble, Name::None, 10, 0, 0)
1755            .unwrap();
1756        b.begin_subasset(None).unwrap();
1757        assert!(b.finish().is_err(), "trailing empty sub-asset");
1758    }
1759
1760    #[test]
1761    fn an_attachment_is_kept_by_type_and_replaced_by_another() {
1762        #[derive(Debug, PartialEq)]
1763        struct State(u32);
1764        let mut b = builder(4);
1765        b.push_span(SegmentKind::Preamble, Name::None, 4, 0, 0)
1766            .unwrap();
1767        b.attach(State(1)).attach(State(2));
1768        let s = b.finish().unwrap();
1769        assert_eq!(s.attachment::<State>(), Some(&State(2)));
1770        assert!(s.attachment::<String>().is_none());
1771
1772        let mut b = builder(4);
1773        b.push_span(SegmentKind::Preamble, Name::None, 4, 0, 0)
1774            .unwrap();
1775        assert!(b.finish().unwrap().attachment::<State>().is_none());
1776    }
1777
1778    #[test]
1779    fn rolling_back_a_subasset_restores_the_cursor() {
1780        let mut b = builder(30);
1781        assert!(b.rollback_subasset().is_err(), "nothing to roll back");
1782        b.push_span(SegmentKind::Preamble, Name::None, 10, 0, 0)
1783            .unwrap();
1784        b.begin_subasset(Some("a/b".into())).unwrap();
1785        b.push_span(SegmentKind::Other, Name::None, 5, 0, 0)
1786            .unwrap();
1787        b.push_span(SegmentKind::Other, Name::None, 5, 0, 0)
1788            .unwrap();
1789        assert_eq!(b.rollback_subasset().unwrap(), 10);
1790        assert_eq!(b.cursor(), 10);
1791        assert!(b.rollback_subasset().is_err(), "already undone");
1792        // The rest is pushed as part of the primary asset.
1793        b.push_span(SegmentKind::Other, Name::None, 20, 0, 0)
1794            .unwrap();
1795        let s = b.finish().unwrap();
1796        assert_eq!(s.subassets().len(), 1);
1797        assert_eq!(s.segments().len(), 2);
1798
1799        // A sub-asset with nothing pushed yet rolls back too.
1800        let mut b = builder(30);
1801        b.push_span(SegmentKind::Preamble, Name::None, 10, 0, 0)
1802            .unwrap();
1803        b.begin_subasset(None).unwrap();
1804        assert_eq!(b.rollback_subasset().unwrap(), 10);
1805
1806        // An item that refers to the removed segments blocks it.
1807        let mut b = builder(30);
1808        let first = b
1809            .push_span(SegmentKind::Preamble, Name::None, 10, 0, 0)
1810            .unwrap();
1811        b.begin_subasset(None).unwrap();
1812        let second = b
1813            .push_span(SegmentKind::Metadata, Name::None, 4, 16, 0)
1814            .unwrap();
1815        b.item_of_segments(ItemInfo::xmp(), &[second]).unwrap();
1816        assert!(b.rollback_subasset().is_err());
1817        let _ = first;
1818    }
1819
1820    #[test]
1821    fn tiles_exactly() {
1822        let mut b = builder(30);
1823        b.push_span(SegmentKind::Preamble, Name::None, 10, 0, 0)
1824            .unwrap();
1825        let id = b
1826            .push_span(SegmentKind::Metadata, Name::FourCC(*b"iTXt"), 8, 8, 4)
1827            .unwrap();
1828        b.item_of_segments(ItemInfo::xmp(), &[id]).unwrap();
1829        let s = b.finish().unwrap();
1830        let covered: u64 = s.regions().map(|r| r.range.len()).sum();
1831        assert_eq!(covered, 30);
1832        let e = s.require_item(ItemKind::Xmp).unwrap();
1833        assert_eq!(e.len(), 8);
1834        assert!(s.item(ItemKind::C2pa).unwrap().is_none());
1835        assert!(matches!(
1836            s.require_item(ItemKind::C2pa),
1837            Err(Error::NotFound { .. })
1838        ));
1839    }
1840
1841    #[test]
1842    fn rejects_gap_overrun_and_short_cover() {
1843        let mut b = builder(20);
1844        let gap = Segment::new(
1845            ByteRange::new(5, 5).unwrap(),
1846            0,
1847            0,
1848            SegmentKind::Other,
1849            Name::None,
1850        )
1851        .unwrap();
1852        assert!(b.push(gap).is_err());
1853        assert!(b
1854            .push_span(SegmentKind::Other, Name::None, 0, 21, 0)
1855            .is_err());
1856        b.push_span(SegmentKind::Other, Name::None, 0, 10, 0)
1857            .unwrap();
1858        assert!(b.finish().is_err());
1859    }
1860
1861    #[test]
1862    fn ambiguous_item() {
1863        let mut b = builder(8);
1864        let a = b
1865            .push_span(SegmentKind::Metadata, Name::None, 0, 4, 0)
1866            .unwrap();
1867        let c = b
1868            .push_span(SegmentKind::Metadata, Name::None, 0, 4, 0)
1869            .unwrap();
1870        b.item_of_segments(ItemInfo::c2pa(), &[a]).unwrap();
1871        b.item_of_segments(ItemInfo::c2pa(), &[c]).unwrap();
1872        let s = b.finish().unwrap();
1873        assert!(matches!(
1874            s.item(ItemKind::C2pa),
1875            Err(Error::Ambiguous { count: 2, .. })
1876        ));
1877    }
1878
1879    #[test]
1880    fn extent_must_lie_in_segment() {
1881        let mut b = builder(10);
1882        let a = b
1883            .push_span(SegmentKind::Metadata, Name::None, 0, 5, 0)
1884            .unwrap();
1885        let _ = b
1886            .push_span(SegmentKind::Other, Name::None, 0, 5, 0)
1887            .unwrap();
1888        let outside = ByteRange::new(4, 3).unwrap();
1889        assert!(b.item(ItemInfo::xmp(), &[(a, outside)]).is_err());
1890    }
1891
1892    #[test]
1893    fn read_range_is_bounded() {
1894        let mut b = builder(8);
1895        b.push_span(SegmentKind::Other, Name::None, 0, 8, 0)
1896            .unwrap();
1897        let s = b.finish().unwrap();
1898        let mut src = std::io::Cursor::new(vec![1u8, 2, 3, 4, 5, 6, 7, 8]);
1899        let got = s
1900            .read_range(&mut src, ByteRange::new(2, 3).unwrap())
1901            .unwrap();
1902        assert_eq!(got, vec![3, 4, 5]);
1903        assert!(s
1904            .read_range(&mut src, ByteRange::new(6, 3).unwrap())
1905            .is_err());
1906    }
1907}