Skip to main content

asset_io/
execute.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//! Running a [`WritePlan`] one piece of I/O at a time; see [`Execution`].
15//!
16//! Obtain an execution with [`WritePlan::start`] and service each [`Action`].
17//! This module is the advanced client write driver; synchronous clients use
18//! [`crate::Asset::write`] or [`crate::Structure::write`] instead.
19
20use std::mem;
21
22use crate::{
23    error::{Error, Result},
24    plan::{Relocate, Step, WritePlan},
25    range::ByteRange,
26    segment::Role,
27    sink::{Chunk, Sink},
28    structure::{SegmentId, Structure},
29};
30
31/// What the caller of [`Execution::step`] must do before calling it again.
32#[derive(Debug)]
33#[non_exhaustive]
34pub enum Action<'a> {
35    /// Fill `buf` completely with the source asset's bytes from `offset`.
36    ///
37    /// A source that has fewer bytes than that is not the stream the plan was made
38    /// from; report it as an error and stop.
39    Read {
40        /// Where in the source asset the bytes are.
41        offset: u64,
42        /// The buffer to fill. Its length is how many bytes are wanted.
43        buf: &'a mut [u8],
44    },
45    /// Write these bytes to the output, which is written from its start, in order.
46    Write(&'a [u8]),
47    /// The plan has been carried out in full.
48    Done,
49}
50
51/// How many copy buffers a run may span before it is flushed. Bounds the pieces
52/// held at once, however many small segments the asset has.
53const RUN_WINDOWS: u64 = 16;
54
55/// Copy buffer for large writes. Measured on one machine (Apple M2, 128 MB PNGs): 64
56/// and 128 KiB were slow in memory, 16 and 32 KiB slow from disk, 256 KiB good in
57/// both. Not measured on other CPUs.
58const WRITE_BUFFER: usize = 256 * 1024;
59
60/// Smallest copy buffer. It must hold at least one entry of any offset table
61/// ([`MAX_RELOCATE_STRIDE`](crate::plan::MAX_RELOCATE_STRIDE) bytes).
62const MIN_WRITE_BUFFER: usize = 4096;
63
64/// Size of the copy buffer for writing an output of `total` bytes. It is also the
65/// read and write window of a run, so a small asset gets a buffer no larger than
66/// itself and does not pay for a large allocation.
67fn default_buffer_len(total: u64) -> usize {
68    (total.min(WRITE_BUFFER as u64) as usize).max(MIN_WRITE_BUFFER)
69}
70
71/// One source region of a run, and the segment and role it lands in.
72#[derive(Debug, Clone, Copy)]
73struct Piece {
74    dest: SegmentId,
75    role: Role,
76    range: ByteRange,
77}
78
79/// A run of source regions that are contiguous in the source and land in
80/// consecutive output segments. Each window of it is read once, shown to the sink as
81/// slices tagged with their segment and role, and written once, so reads and writes
82/// are a function of the run's length, not of how many segments it crosses.
83struct Run {
84    pieces: Vec<Piece>,
85    /// Source offset of the next window to read.
86    at: u64,
87    /// Bytes of the run not yet read.
88    left: u64,
89    /// The piece the next delivered byte belongs to, and how much of it is done.
90    piece: usize,
91    done: u64,
92}
93
94/// A table of offsets being copied and rewritten, block by block.
95struct Table<'a> {
96    role: Role,
97    rule: &'a Relocate,
98    at: u64,
99    entries_left: u64,
100    per_block: u64,
101}
102
103/// What a transition of the state machine asks for, as plain data, so that no
104/// borrow of the machine outlives the transition.
105enum Out<'a> {
106    Continue,
107    Read { offset: u64, len: usize },
108    WriteBuf(usize),
109    WriteData(&'a [u8]),
110    Done,
111}
112
113enum State<'a> {
114    Start,
115    Idle,
116    /// A read of `n` bytes of a run was handed out.
117    RunRead(Run, usize),
118    /// The write of a window of a run was handed out.
119    RunWrite(Run),
120    /// A read of `n` entries of a table was handed out.
121    TableRead(Table<'a>, usize),
122    /// The write of a block of a table was handed out.
123    TableWrite(Table<'a>),
124    Done,
125}
126
127/// Checks that every byte lands where the structure says, and shows it to the sink.
128struct Tracker<'a> {
129    structure: &'a Structure,
130    pos: u64,
131    cur: Option<SegmentId>,
132}
133
134impl Tracker<'_> {
135    /// Start a segment. Fails if the output position has drifted from the plan.
136    fn begin_segment(&mut self, id: SegmentId) -> Result<()> {
137        let seg = self.structure.segment(id)?;
138        if self.pos != seg.range().offset() {
139            return Err(Error::invalid_segment(
140                self.pos,
141                format!(
142                    "output position diverged from planned structure (expected {})",
143                    seg.range().offset()
144                ),
145            ));
146        }
147        self.cur = Some(id);
148        Ok(())
149    }
150
151    /// Start `id` unless it is already the current segment, which a run split
152    /// inside one segment leaves it.
153    fn enter_segment(&mut self, id: SegmentId) -> Result<()> {
154        if self.cur == Some(id) {
155            return Ok(());
156        }
157        self.begin_segment(id)
158    }
159
160    /// Show `data` to the sink as bytes of the current segment and advance the
161    /// output position.
162    fn deliver<S: Sink + ?Sized>(&mut self, sink: &mut S, role: Role, data: &[u8]) -> Result<()> {
163        let id = self
164            .cur
165            .ok_or_else(|| Error::InvalidFormat("write outside of a segment".into()))?;
166        let seg = self.structure.segment(id)?;
167        let region = match role {
168            Role::Header => seg.header(),
169            Role::Payload => seg.payload(),
170            Role::Trailer => seg.trailer(),
171        };
172        let end = self.pos.saturating_add(data.len() as u64);
173        if self.pos < region.offset() || end > region.end() {
174            return Err(Error::invalid_segment(
175                self.pos,
176                format!(
177                    "{} bytes do not lie in the {role:?} of their segment",
178                    data.len()
179                ),
180            ));
181        }
182        if sink.wants(seg, role) {
183            sink.chunk(Chunk::new(id, role, self.pos, data))?;
184        }
185        self.pos = self
186            .pos
187            .checked_add(data.len() as u64)
188            .ok_or(Error::LimitExceeded {
189                what: "output size",
190                limit: u64::MAX,
191            })?;
192        Ok(())
193    }
194
195    /// Verify the whole structure was written.
196    fn finish(&self) -> Result<()> {
197        if self.pos != self.structure.total_size() {
198            return Err(Error::invalid_segment(
199                self.pos,
200                format!(
201                    "wrote {} bytes, planned structure is {}",
202                    self.pos,
203                    self.structure.total_size()
204                ),
205            ));
206        }
207        Ok(())
208    }
209}
210
211/// A [`WritePlan`] being carried out, one piece of I/O at a time.
212///
213/// An `Execution` does no I/O. It tells its caller what to do next: read these
214/// source bytes into this buffer, write these bytes to the output, or stop. The
215/// caller performs that however it likes (blocking, `async`, from a state machine
216/// of its own) and calls [`Execution::step`] again. The sink, the checking of every
217/// byte against the plan's structure, and the coalescing of reads all happen
218/// inside `step`, so every way of running a plan behaves the same.
219///
220/// ```no_run
221/// # use asset_io::{NullSink, execute::{Action}, plan::{WritePlan}};
222/// # use std::io::{Read, Seek, SeekFrom, Write};
223/// # fn run(plan: &WritePlan<'_>, mut src: impl Read + Seek, mut out: impl Write)
224/// #     -> asset_io::Result<()> {
225/// let mut run = plan.start();
226/// loop {
227///     match run.step(&mut NullSink)? {
228///         Action::Read { offset, buf } => {
229///             src.seek(SeekFrom::Start(offset))?;
230///             src.read_exact(buf)?;
231///         }
232///         Action::Write(bytes) => out.write_all(bytes)?,
233///         Action::Done => break,
234///         _ => unreachable!(),
235///     }
236/// }
237/// # Ok(())
238/// # }
239/// ```
240///
241/// [`WritePlan::execute`] is that loop.
242pub struct Execution<'a, 'p> {
243    plan: &'a WritePlan<'p>,
244    tracker: Tracker<'a>,
245    next: usize,
246    buf: Vec<u8>,
247    state: State<'a>,
248}
249
250impl<'a, 'p> Execution<'a, 'p> {
251    pub(crate) fn new(plan: &'a WritePlan<'p>) -> Self {
252        let structure = plan.structure();
253        Self {
254            plan,
255            tracker: Tracker {
256                structure,
257                pos: 0,
258                cur: None,
259            },
260            next: 0,
261            buf: vec![0u8; default_buffer_len(structure.total_size())],
262            state: State::Start,
263        }
264    }
265
266    /// Use a buffer (the most bytes one [`Action::Read`] asks for) of `len` bytes,
267    /// at least 4 KiB. The default is 256 KiB, or the output size if that is
268    /// smaller. Call it before the first [`step`](Self::step).
269    pub fn with_buffer_len(mut self, len: usize) -> Self {
270        self.buf = vec![0u8; len.max(MIN_WRITE_BUFFER)];
271        self
272    }
273
274    /// Carry the plan one step further: do the sink's part, check the bytes against
275    /// the plan's structure, and say what the caller must do next. Call it again
276    /// when that is done. Errors are final.
277    ///
278    /// Every byte of the output reaches `sink` once, in order, tagged with its
279    /// segment and role, before the [`Action::Write`] that carries it.
280    pub fn step<S: Sink + ?Sized>(&mut self, sink: &mut S) -> Result<Action<'_>> {
281        loop {
282            return Ok(match self.advance(sink)? {
283                Out::Continue => continue,
284                Out::Read { offset, len } => Action::Read {
285                    offset,
286                    buf: &mut self.buf[..len],
287                },
288                Out::WriteBuf(len) => Action::Write(&self.buf[..len]),
289                Out::WriteData(data) => Action::Write(data),
290                Out::Done => Action::Done,
291            });
292        }
293    }
294
295    /// Move the state machine on by one transition.
296    fn advance<S: Sink + ?Sized>(&mut self, sink: &mut S) -> Result<Out<'a>> {
297        match mem::replace(&mut self.state, State::Idle) {
298            State::Start => {
299                sink.begin(self.plan.structure())?;
300                Ok(Out::Continue)
301            }
302            State::Idle => self.begin_next(sink),
303            State::RunRead(mut run, n) => {
304                self.deliver_run(sink, &mut run, n)?;
305                self.state = State::RunWrite(run);
306                Ok(Out::WriteBuf(n))
307            }
308            State::RunWrite(run) => Ok(if run.left == 0 {
309                Out::Continue
310            } else {
311                self.read_run(run)
312            }),
313            State::TableRead(table, n) => {
314                let bytes = n * table.rule.stride() as usize;
315                table.rule.apply(&mut self.buf[..bytes])?;
316                self.tracker.deliver(sink, table.role, &self.buf[..bytes])?;
317                self.state = State::TableWrite(table);
318                Ok(Out::WriteBuf(bytes))
319            }
320            State::TableWrite(table) => Ok(if table.entries_left == 0 {
321                Out::Continue
322            } else {
323                self.read_table(table)
324            }),
325            State::Done => {
326                self.state = State::Done;
327                Ok(Out::Done)
328            }
329        }
330    }
331
332    /// Look at the next step of the plan.
333    fn begin_next<S: Sink + ?Sized>(&mut self, sink: &mut S) -> Result<Out<'a>> {
334        let plan = self.plan;
335        let Some(step) = plan.steps().get(self.next) else {
336            self.tracker.finish()?;
337            self.state = State::Done;
338            return Ok(Out::Continue);
339        };
340        match step {
341            Step::Copy { .. } => {
342                let run = self.collect_run();
343                match run.pieces.first() {
344                    Some(first) => {
345                        self.tracker.enter_segment(first.dest)?;
346                        Ok(self.read_run(run))
347                    }
348                    None => Ok(Out::Continue),
349                }
350            }
351            Step::Put { dest, role, data } => {
352                self.next += 1;
353                if data.is_empty() {
354                    return Ok(Out::Continue);
355                }
356                self.tracker.enter_segment(*dest)?;
357                self.tracker.deliver(sink, *role, data)?;
358                Ok(Out::WriteData(data))
359            }
360            Step::Relocate {
361                dest,
362                role,
363                src,
364                rule,
365            } => {
366                self.next += 1;
367                let stride = rule.stride() as u64;
368                if !src.len().is_multiple_of(stride) {
369                    return Err(Error::invalid_segment(
370                        src.offset(),
371                        "offset table is not a whole number of entries",
372                    ));
373                }
374                if src.is_empty() {
375                    return Ok(Out::Continue);
376                }
377                self.tracker.enter_segment(*dest)?;
378                let table = Table {
379                    role: *role,
380                    rule,
381                    at: src.offset(),
382                    entries_left: src.len() / stride,
383                    per_block: (self.buf.len() as u64 / stride).max(1),
384                };
385                Ok(self.read_table(table))
386            }
387        }
388    }
389
390    /// Gather the copy steps from `next` on that form one run: contiguous in the
391    /// source, and cut between segments once the run spans enough buffers.
392    fn collect_run(&mut self) -> Run {
393        let run_limit = (self.buf.len() as u64).saturating_mul(RUN_WINDOWS);
394        let mut pieces: Vec<Piece> = Vec::new();
395        let mut run_len = 0u64;
396        while let Some(Step::Copy { dest, role, src }) = self.plan.steps().get(self.next) {
397            if !src.is_empty() {
398                if let Some(last) = pieces.last() {
399                    let gap = last.range.end() != src.offset();
400                    if gap || (last.dest != *dest && run_len >= run_limit) {
401                        break;
402                    }
403                }
404                run_len = run_len.saturating_add(src.len());
405                pieces.push(Piece {
406                    dest: *dest,
407                    role: *role,
408                    range: *src,
409                });
410            }
411            self.next += 1;
412        }
413        Run {
414            at: pieces.first().map_or(0, |p| p.range.offset()),
415            left: run_len,
416            pieces,
417            piece: 0,
418            done: 0,
419        }
420    }
421
422    /// Ask for the next window of `run`.
423    fn read_run(&mut self, mut run: Run) -> Out<'a> {
424        let len = run.left.min(self.buf.len() as u64) as usize;
425        let offset = run.at;
426        run.at += len as u64;
427        run.left -= len as u64;
428        self.state = State::RunRead(run, len);
429        Out::Read { offset, len }
430    }
431
432    /// Ask for the next block of `table`.
433    fn read_table(&mut self, mut table: Table<'a>) -> Out<'a> {
434        let n = table.entries_left.min(table.per_block) as usize;
435        let offset = table.at;
436        let len = n * table.rule.stride() as usize;
437        table.at += len as u64;
438        table.entries_left -= n as u64;
439        self.state = State::TableRead(table, n);
440        Out::Read { offset, len }
441    }
442
443    /// Show the `n` bytes of the buffer to the sink, as slices of the pieces they
444    /// belong to.
445    fn deliver_run<S: Sink + ?Sized>(
446        &mut self,
447        sink: &mut S,
448        run: &mut Run,
449        n: usize,
450    ) -> Result<()> {
451        let mut w = 0usize;
452        while w < n {
453            let p = run
454                .pieces
455                .get(run.piece)
456                .ok_or_else(|| Error::InvalidFormat("copy run exhausted".into()))?;
457            if run.done == 0 && self.tracker.cur != Some(p.dest) {
458                self.tracker.begin_segment(p.dest)?;
459            }
460            let take = (p.range.len() - run.done).min((n - w) as u64) as usize;
461            self.tracker.deliver(sink, p.role, &self.buf[w..w + take])?;
462            w += take;
463            run.done += take as u64;
464            if run.done == p.range.len() {
465                run.piece += 1;
466                run.done = 0;
467            }
468        }
469        Ok(())
470    }
471}