Skip to main content

asset_io/
plan.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//! Declarative write plans.
15//!
16//! A handler describes a write as data: the structure of the output and an ordered
17//! list of [`Step`]s that produce it. It does not touch the output stream or the
18//! sink. [`WritePlan::execute`] is the reference executor: it runs the steps
19//! synchronously, coalesces reads, delivers every byte to the sink tagged with its
20//! segment and role, and checks that the bytes land where the structure says. A caller
21//! can run the same plan some other way (asynchronously, or from a state machine
22//! that does no I/O itself), because the plan is plain data.
23
24use std::{
25    borrow::Cow,
26    io::{Read, Seek, SeekFrom, Write},
27    sync::Arc,
28};
29
30use crate::{
31    error::{Error, Result},
32    execute::{Action, Execution},
33    range::ByteRange,
34    segment::{Role, Segment},
35    sink::Sink,
36    structure::{SegmentId, Structure},
37    task::Task,
38};
39
40/// Where bytes moved: `(end of the old region, size change)` for each edit.
41///
42/// A file offset that points at or past the end of an edited region moves by that
43/// edit's size change. Containers that store absolute file offsets (ISO BMFF chunk
44/// tables, for one) use it to say how those offsets change when an edit shifts the
45/// data after it.
46#[derive(Debug, Clone, Default, PartialEq, Eq)]
47pub struct OffsetMap {
48    edits: Vec<(u64, i64)>,
49}
50
51impl OffsetMap {
52    /// A map that moves nothing.
53    pub fn new() -> Self {
54        Self::default()
55    }
56
57    /// Record that the region of the source that ended at `old_end` changed size
58    /// by `delta` bytes. A zero change is not recorded.
59    pub fn add(&mut self, old_end: u64, delta: i64) {
60        if delta != 0 {
61            self.edits.push((old_end, delta));
62        }
63    }
64
65    /// Whether no offset moves.
66    pub fn is_identity(&self) -> bool {
67        self.edits.is_empty()
68    }
69
70    /// Where the source offset `v` is in the output.
71    pub fn apply(&self, v: u64) -> Result<u64> {
72        let shift: i128 = self
73            .edits
74            .iter()
75            .filter(|(end, _)| *end <= v)
76            .map(|(_, d)| *d as i128)
77            .sum();
78        u64::try_from(v as i128 + shift)
79            .map_err(|_| Error::InvalidFormat("offset adjustment out of range".into()))
80    }
81}
82
83/// Largest entry [`Relocate`] handles.
84pub const MAX_RELOCATE_STRIDE: u32 = 4096;
85
86/// How the bytes of a [`Step::Relocate`] are rewritten: they are a table of
87/// `stride`-byte entries, each holding a big-endian file offset `width` bytes
88/// wide (4 or 8) at `field_off`, and every offset is replaced by its position in
89/// the output according to an [`OffsetMap`]. The rest of each entry is unchanged.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct Relocate {
92    map: Arc<OffsetMap>,
93    stride: u32,
94    field_off: u32,
95    width: u8,
96}
97
98impl Relocate {
99    /// A rewrite rule. Fails if `width` is not 4 or 8, the field does not fit in an
100    /// entry, or the entry is empty or longer than [`MAX_RELOCATE_STRIDE`].
101    pub fn new(map: Arc<OffsetMap>, stride: u32, field_off: u32, width: u8) -> Result<Self> {
102        let fits = field_off
103            .checked_add(width as u32)
104            .is_some_and(|end| end <= stride);
105        if !matches!(width, 4 | 8) || stride == 0 || stride > MAX_RELOCATE_STRIDE || !fits {
106            return Err(Error::InvalidFormat("invalid offset table geometry".into()));
107        }
108        Ok(Self {
109            map,
110            stride,
111            field_off,
112            width,
113        })
114    }
115
116    /// Bytes per entry.
117    pub fn stride(&self) -> u32 {
118        self.stride
119    }
120
121    /// Rewrite the offset in each whole entry of `block`.
122    pub(crate) fn apply(&self, block: &mut [u8]) -> Result<()> {
123        let (off, w) = (self.field_off as usize, self.width as usize);
124        for entry in block.chunks_exact_mut(self.stride as usize) {
125            let f = &mut entry[off..off + w];
126            let v = self
127                .map
128                .apply(f.iter().fold(0u64, |a, &b| (a << 8) | b as u64))?;
129            let range = || Error::InvalidFormat("offset adjustment does not fit its field".into());
130            match w {
131                4 => f.copy_from_slice(&u32::try_from(v).map_err(|_| range())?.to_be_bytes()),
132                _ => f.copy_from_slice(&v.to_be_bytes()),
133            }
134        }
135        Ok(())
136    }
137}
138
139/// One piece of the output.
140///
141/// Steps are executed in order and must tile the output: each step supplies the
142/// next bytes of segment `dest`, in the `role` (header, payload or trailer) of that
143/// segment's structure, and the segments follow one another as the structure lists them.
144#[derive(Debug, Clone)]
145#[non_exhaustive]
146pub enum Step<'a> {
147    /// Copy bytes of the source asset.
148    Copy {
149        /// The output segment the bytes belong to.
150        dest: SegmentId,
151        /// Which part of that segment they are.
152        role: Role,
153        /// The source bytes.
154        src: ByteRange,
155    },
156    /// Write bytes the handler supplies.
157    Put {
158        /// The output segment the bytes belong to.
159        dest: SegmentId,
160        /// Which part of that segment they are.
161        role: Role,
162        /// The bytes.
163        data: Cow<'a, [u8]>,
164    },
165    /// Copy bytes of the source asset that are a table of file offsets, rewriting
166    /// the offsets. The source range is a whole number of entries.
167    Relocate {
168        /// The output segment the bytes belong to.
169        dest: SegmentId,
170        /// Which part of that segment they are.
171        role: Role,
172        /// The source bytes.
173        src: ByteRange,
174        /// How the offsets change.
175        rule: Relocate,
176    },
177}
178
179impl Step<'_> {
180    /// The output segment this step writes to.
181    pub fn dest(&self) -> SegmentId {
182        match self {
183            Step::Copy { dest, .. } | Step::Put { dest, .. } | Step::Relocate { dest, .. } => *dest,
184        }
185    }
186
187    /// Which part of the output segment this step writes.
188    pub fn role(&self) -> Role {
189        match self {
190            Step::Copy { role, .. } | Step::Put { role, .. } | Step::Relocate { role, .. } => *role,
191        }
192    }
193
194    /// How many output bytes this step produces.
195    pub fn len(&self) -> u64 {
196        match self {
197            Step::Copy { src, .. } | Step::Relocate { src, .. } => src.len(),
198            Step::Put { data, .. } => data.len() as u64,
199        }
200    }
201
202    /// Whether this step produces no bytes.
203    pub fn is_empty(&self) -> bool {
204        self.len() == 0
205    }
206}
207
208/// A write, described but not performed.
209///
210/// Holds the [`Structure`] of the output and the [`Step`]s that produce it.
211/// Borrows from the [`Updates`](crate::Updates) it was made from, so the new
212/// metadata is not copied.
213#[derive(Debug)]
214pub struct WritePlan<'a> {
215    structure: Structure,
216    steps: Vec<Step<'a>>,
217}
218
219impl<'a> WritePlan<'a> {
220    /// A plan for the output `structure`, with no steps yet.
221    pub fn new(structure: Structure) -> Self {
222        Self {
223            structure,
224            steps: Vec::new(),
225        }
226    }
227
228    pub(crate) fn from_parts(structure: Structure, steps: Vec<Step<'a>>) -> Self {
229        Self { structure, steps }
230    }
231
232    /// Append a step that copies `src` of the source asset into `role` of `dest`.
233    pub fn copy(&mut self, dest: SegmentId, role: Role, src: ByteRange) -> &mut Self {
234        self.steps.push(Step::Copy { dest, role, src });
235        self
236    }
237
238    /// Append a step that writes `data` as `role` of `dest`.
239    pub fn put(
240        &mut self,
241        dest: SegmentId,
242        role: Role,
243        data: impl Into<Cow<'a, [u8]>>,
244    ) -> &mut Self {
245        self.steps.push(Step::Put {
246            dest,
247            role,
248            data: data.into(),
249        });
250        self
251    }
252
253    /// Append a step that copies `src` of the source asset into `role` of `dest`,
254    /// rewriting the file offsets in it as `rule` says.
255    pub fn relocate(
256        &mut self,
257        dest: SegmentId,
258        role: Role,
259        src: ByteRange,
260        rule: Relocate,
261    ) -> &mut Self {
262        self.steps.push(Step::Relocate {
263            dest,
264            role,
265            src,
266            rule,
267        });
268        self
269    }
270
271    /// Replace the steps that write `role` of `dest` with one that writes `data`,
272    /// for bytes that depend on the rest of the output. It must be as long as what
273    /// it replaces. Fails if `dest` has no step for `role`.
274    pub fn replace(
275        &mut self,
276        dest: SegmentId,
277        role: Role,
278        data: impl Into<Cow<'a, [u8]>>,
279    ) -> Result<&mut Self> {
280        let hit = |s: &Step<'_>| s.dest() == dest && s.role() == role;
281        let at = self
282            .steps
283            .iter()
284            .position(hit)
285            .ok_or(Error::NotFound { what: "step" })?;
286        self.steps.retain(|s| !hit(s));
287        self.steps.insert(
288            at,
289            Step::Put {
290                dest,
291                role,
292                data: data.into(),
293            },
294        );
295        Ok(self)
296    }
297
298    /// Append the steps that copy the source segment `src` unchanged into `dest`.
299    pub fn copy_segment(&mut self, dest: SegmentId, src: &Segment) -> &mut Self {
300        for (role, range) in src.regions() {
301            self.copy(dest, role, range);
302        }
303        self
304    }
305
306    /// The structure of the output.
307    pub fn structure(&self) -> &Structure {
308        &self.structure
309    }
310
311    /// The steps, in output order.
312    pub fn steps(&self) -> &[Step<'a>] {
313        &self.steps
314    }
315
316    /// The structure of the output, discarding the steps.
317    pub fn into_structure(self) -> Structure {
318        self.structure
319    }
320
321    /// Where each step starts in the output, plus the end of the last one.
322    fn step_offsets(&self) -> Vec<u64> {
323        let mut offsets = Vec::with_capacity(self.steps.len() + 1);
324        let mut at = 0u64;
325        offsets.push(at);
326        for step in &self.steps {
327            at = at.saturating_add(step.len());
328            offsets.push(at);
329        }
330        offsets
331    }
332
333    /// The steps that produce any byte of `range` of the output, in order.
334    fn steps_over<'p>(
335        &'p self,
336        offsets: &'p [u64],
337        range: ByteRange,
338    ) -> impl Iterator<Item = &'p Step<'a>> + 'p {
339        // The first step ending after the range starts.
340        let first = offsets[1..].partition_point(|&end| end <= range.offset());
341        self.steps[first..]
342            .iter()
343            .zip(&offsets[first..])
344            .take_while(move |(_, &start)| start < range.end())
345            .filter(|(step, _)| !step.is_empty())
346            .map(|(step, _)| step)
347    }
348
349    /// Whether any byte of `range` of the output is written by a
350    /// [`Step::Relocate`]: a table of file offsets that the write rewrites, so its
351    /// output differs from its source.
352    pub fn is_relocated(&self, range: ByteRange) -> bool {
353        let offsets = self.step_offsets();
354        let relocated = self
355            .steps_over(&offsets, range)
356            .any(|step| matches!(step, Step::Relocate { .. }));
357        relocated
358    }
359
360    /// The items of `kind` in the output whose bytes the plan writes from data it
361    /// was given ([`Step::Put`]) rather than copying from the source: the items an
362    /// [`Updates`](crate::Updates) value set or replaced. Items the write keeps are
363    /// copied and not listed. Reads nothing.
364    pub fn written_items(&self, kind: crate::ItemKind) -> impl Iterator<Item = &crate::Item> + '_ {
365        let offsets = self.step_offsets();
366        self.structure.items_of(kind).filter(move |item| {
367            let mut extents = item.extents().peekable();
368            extents.peek().is_some()
369                && extents.all(|extent| {
370                    self.steps_over(&offsets, extent.range())
371                        .all(|step| matches!(step, Step::Put { .. }))
372                })
373        })
374    }
375
376    /// The output as a reader, without writing it: reads return the bytes
377    /// [`execute`](Self::execute) would write, taking source bytes from `src` (the
378    /// stream the plan was made from) and rewriting relocated offsets. Only the
379    /// requested bytes are read; nothing is buffered beyond one offset-table entry.
380    ///
381    /// For inspecting a planned output, such as walking its structure or reading
382    /// an item, before committing to the write.
383    pub fn reader<R: Read + Seek>(&self, src: R) -> PlanReader<'_, 'a, R> {
384        PlanReader {
385            offsets: self.step_offsets(),
386            plan: self,
387            src,
388            position: 0,
389            entry: Vec::new(),
390        }
391    }
392
393    /// Start carrying the plan out, step by step, with the I/O left to the caller;
394    /// see [`Execution`].
395    pub fn start(&self) -> Execution<'_, 'a> {
396        Execution::new(self)
397    }
398
399    /// Perform the write: run every step against `src`, write the bytes to `out`
400    /// and deliver them to `sink`. `out` is written from its current position;
401    /// offsets reported to the sink are relative to the first byte written.
402    ///
403    /// Fails, and may leave partial output, if the steps do not produce exactly
404    /// the structure: bytes at the wrong offset, in the wrong role, or too few or too
405    /// many of them.
406    ///
407    /// This drives [`start`](Self::start) with blocking reads and writes.
408    pub fn execute<R, W, S>(&self, src: &mut R, out: &mut W, sink: &mut S) -> Result<()>
409    where
410        R: Read + Seek + ?Sized,
411        W: Write + ?Sized,
412        S: Sink + ?Sized,
413    {
414        let mut run = self.start();
415        // Where the source stream is, so that a read that continues the last one
416        // does not seek.
417        let mut at: Option<u64> = None;
418        loop {
419            match run.step(sink)? {
420                Action::Read { offset, buf } => {
421                    if at != Some(offset) {
422                        src.seek(SeekFrom::Start(offset))?;
423                    }
424                    src.read_exact(buf)?;
425                    at = Some(offset + buf.len() as u64);
426                }
427                Action::Write(bytes) => out.write_all(bytes)?,
428                Action::Done => break,
429            }
430        }
431        out.flush()?;
432        Ok(())
433    }
434}
435
436/// A planned output read without writing it; see [`WritePlan::reader`].
437#[derive(Debug)]
438pub struct PlanReader<'p, 'a, R> {
439    plan: &'p WritePlan<'a>,
440    offsets: Vec<u64>,
441    src: R,
442    position: u64,
443    entry: Vec<u8>,
444}
445
446impl<R> PlanReader<'_, '_, R> {
447    /// The source stream, giving it back.
448    pub fn into_inner(self) -> R {
449        self.src
450    }
451}
452
453impl<R: Read + Seek> Read for PlanReader<'_, '_, R> {
454    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
455        let index = self.offsets[1..].partition_point(|&end| end <= self.position);
456        let Some(step) = self.plan.steps.get(index) else {
457            return Ok(0);
458        };
459        let relative = self.position - self.offsets[index];
460        let len = (buf.len() as u64).min(step.len() - relative) as usize;
461        let n = match step {
462            Step::Copy { src, .. } => {
463                self.src.seek(SeekFrom::Start(src.offset() + relative))?;
464                self.src.read(&mut buf[..len])?
465            }
466            Step::Put { data, .. } => {
467                let start = relative as usize;
468                buf[..len].copy_from_slice(&data[start..start + len]);
469                len
470            }
471            Step::Relocate { src, rule, .. } => {
472                // Rewrite the whole entry holding `relative`, then hand out its bytes.
473                let stride = u64::from(rule.stride());
474                let entry_start = relative - relative % stride;
475                self.entry.resize(stride as usize, 0);
476                self.src.seek(SeekFrom::Start(src.offset() + entry_start))?;
477                self.src.read_exact(&mut self.entry)?;
478                rule.apply(&mut self.entry).map_err(std::io::Error::other)?;
479                let at = (relative - entry_start) as usize;
480                let n = len.min(self.entry.len() - at);
481                buf[..n].copy_from_slice(&self.entry[at..at + n]);
482                n
483            }
484        };
485        self.position += n as u64;
486        Ok(n)
487    }
488}
489
490impl<R> Seek for PlanReader<'_, '_, R> {
491    fn seek(&mut self, from: SeekFrom) -> std::io::Result<u64> {
492        let base = match from {
493            SeekFrom::Start(offset) => Some(offset),
494            SeekFrom::Current(delta) => self.position.checked_add_signed(delta),
495            SeekFrom::End(delta) => self.plan.structure.total_size().checked_add_signed(delta),
496        };
497        self.position = base.ok_or_else(|| {
498            std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid planned seek")
499        })?;
500        Ok(self.position)
501    }
502}
503
504impl Structure {
505    /// The plan for writing this asset with `updates`; see [`WritePlan`]. `src` must
506    /// be the stream this structure was parsed from. The container's handler builds
507    /// it, and reports [`Error::UnsupportedFormat`] if it describes its writes some
508    /// other way.
509    ///
510    /// An XMP or C2PA value that `updates` sets must appear in the plan's output;
511    /// if the handler cannot place it the plan is [`Error::UnsupportedItem`].
512    pub fn write_plan<'a>(
513        &self,
514        src: &mut dyn crate::handler::ReadSeek,
515        updates: &'a crate::Updates,
516    ) -> Result<WritePlan<'a>> {
517        let plan = self.handler().write_plan(self, src, updates)?;
518        check_updates_placed(&plan, updates)?;
519        Ok(plan)
520    }
521}
522
523/// [`Error::UnsupportedItem`] for a value `updates` sets that the plan does not
524/// write, so no handler can silently drop one.
525pub(crate) fn check_updates_placed(plan: &WritePlan<'_>, updates: &crate::Updates) -> Result<()> {
526    use crate::{updates::MetadataUpdate, ItemKind};
527    for (kind, update) in [
528        (ItemKind::Xmp, updates.xmp()),
529        (ItemKind::C2pa, updates.c2pa()),
530    ] {
531        if matches!(update, MetadataUpdate::Set(data) if !data.is_empty())
532            && plan.written_items(kind).next().is_none()
533        {
534            return Err(Error::UnsupportedItem(kind));
535        }
536    }
537    Ok(())
538}
539
540impl Structure {
541    /// A task that builds the plan for writing this asset with `updates`, for a
542    /// caller that does its own I/O; see [`Task`]. The task reads the source (a
543    /// stream of [`total_size`](Self::total_size) bytes), which it asks for as it
544    /// needs it. The result is the plan [`write_plan`](Self::write_plan) returns.
545    pub fn write_plan_task<'f, 'a: 'f>(
546        &'f self,
547        updates: &'a crate::Updates,
548    ) -> Task<'f, WritePlan<'a>> {
549        Task::new(self.total_size(), move |io| async move {
550            let plan = self.handler().write_plan_async(self, io, updates).await?;
551            check_updates_placed(&plan, updates)?;
552            Ok(plan)
553        })
554    }
555}
556
557/// Checks a plan's steps against its structure without performing any I/O.
558///
559/// Useful in tests of a handler: the steps must tile the structure exactly, in the
560/// structure's segment and role order, and copy only from inside `source_len` bytes.
561pub fn validate(plan: &WritePlan<'_>, source_len: u64) -> Result<()> {
562    let structure = plan.structure();
563    let mut pos = 0u64;
564    for step in plan.steps() {
565        let seg = structure.segment(step.dest())?;
566        if step.is_empty() {
567            continue;
568        }
569        let region = match step.role() {
570            Role::Header => seg.header(),
571            Role::Payload => seg.payload(),
572            Role::Trailer => seg.trailer(),
573        };
574        let end = pos.checked_add(step.len());
575        let fits = region.offset() <= pos && end.is_some_and(|e| e <= region.end());
576        if !fits {
577            return Err(Error::invalid_segment(
578                pos,
579                format!(
580                    "step of {} bytes does not fit the {:?} of its segment",
581                    step.len(),
582                    step.role()
583                ),
584            ));
585        }
586        if let Step::Relocate { src, rule, .. } = step {
587            if !src.len().is_multiple_of(rule.stride() as u64) {
588                return Err(Error::invalid_segment(
589                    src.offset(),
590                    "offset table is not a whole number of entries",
591                ));
592            }
593        }
594        if let Step::Copy { src, .. } | Step::Relocate { src, .. } = step {
595            if src.end() > source_len {
596                return Err(Error::invalid_segment(
597                    src.offset(),
598                    "copy reads past the end of the source",
599                ));
600            }
601        }
602        pos += step.len();
603    }
604    if pos != structure.total_size() {
605        return Err(Error::invalid_segment(
606            pos,
607            format!(
608                "steps write {pos} bytes, structure is {}",
609                structure.total_size()
610            ),
611        ));
612    }
613    Ok(())
614}