Skip to main content

asset_io/
task.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//! Code that reads a stream, written once, run by any I/O; see [`Task`].
15
16use std::{
17    future::Future,
18    io::{Read, Seek, SeekFrom},
19    marker::PhantomData,
20    pin::Pin,
21    sync::Arc,
22    task::{Context, Poll, Waker},
23};
24
25use crate::{
26    error::{Error, Result},
27    io::{Io, Link},
28};
29
30/// A suspended computation that reads a stream: run it with [`run`](Self::run), or
31/// drive it yourself with [`resume`](Self::resume).
32///
33/// Code that reads is written once, as straight-line `async` code over an [`Io`]:
34///
35/// ```
36/// # use asset_io::{Result, io::{Io}, task::{Progress, Task}};
37/// async fn first_byte(io: &mut Io) -> Result<u8> {
38///     let mut b = [0u8; 1];
39///     io.read_at(0, &mut b).await?;
40///     Ok(b[0])
41/// }
42///
43/// # fn main() -> Result<()> {
44/// let data = [7u8, 8, 9];
45/// let mut task = Task::new(data.len() as u64, |mut io| async move {
46///     first_byte(&mut io).await
47/// });
48/// let first = loop {
49///     match task.resume()? {
50///         // The task has nothing to read from; it asks. Answer however you like.
51///         Progress::Read(mut req) => {
52///             let at = req.offset() as usize;
53///             req.buffer().extend_from_slice(&data[at..]);
54///         }
55///         Progress::Done(v) => break v,
56///         _ => unreachable!(),
57///     }
58/// };
59/// assert_eq!(first, 7);
60/// # Ok(())
61/// # }
62/// ```
63///
64/// The task does not read anything itself. When it needs bytes that its [`Io`] does
65/// not already hold, it suspends, and [`resume`](Self::resume) returns a
66/// [`ReadRequest`]: where to read and how much. The caller reads however it likes
67/// (blocking, `async`, from a network buffer it already has), puts the bytes in the
68/// request's buffer, and resumes. [`run`](Self::run) is the blocking driver for a
69/// `Read + Seek`. No runtime is involved and no I/O trait is required: the task is
70/// driven by plain method calls, so it is `Send` and works under any executor.
71///
72/// [`Io`] keeps a window of the stream, so a run of tiny reads (a chunk header, a
73/// box header) becomes one request for a few KiB, and the code makes no system call
74/// of its own.
75pub struct Task<'f, T> {
76    fut: Pin<Box<dyn Future<Output = Result<T>> + Send + 'f>>,
77    link: Arc<Link>,
78    finished: bool,
79}
80
81impl<'f, T> Task<'f, T> {
82    /// A task for the stream of `total` bytes that `make` reads through the `Io` it
83    /// is given. Nothing runs until the first [`resume`](Self::resume).
84    pub fn new<F>(total: u64, make: impl FnOnce(Io) -> F) -> Self
85    where
86        F: Future<Output = Result<T>> + Send + 'f,
87    {
88        let link = Arc::new(Link::default());
89        let io = Io::new(total, link.clone());
90        Self {
91            fut: Box::pin(make(io)),
92            link,
93            finished: false,
94        }
95    }
96
97    /// Run until the task needs bytes it does not have, or finishes.
98    ///
99    /// On [`Progress::Read`], fill the request's buffer and call `resume` again.
100    /// An error is final. Calling `resume` after the task has finished is an
101    /// error.
102    pub fn resume(&mut self) -> Result<Progress<'_, T>> {
103        if self.finished {
104            return Err(Error::InvalidFormat("task already finished".into()));
105        }
106        let mut cx = Context::from_waker(Waker::noop());
107        match self.fut.as_mut().poll(&mut cx) {
108            Poll::Ready(done) => {
109                self.finished = true;
110                done.map(Progress::Done)
111            }
112            Poll::Pending => match ReadRequest::take(&self.link) {
113                Some(req) => Ok(Progress::Read(req)),
114                None => {
115                    self.finished = true;
116                    Err(Error::InvalidFormat(
117                        "task suspended on something other than a read".into(),
118                    ))
119                }
120            },
121        }
122    }
123
124    /// Run to completion, reading from `src`, which must be the stream the task was
125    /// made for.
126    pub fn run<R: Read + Seek + ?Sized>(mut self, src: &mut R) -> Result<T> {
127        // Where the stream is, so that a request that continues the last one does
128        // not seek.
129        let mut pos = None;
130        loop {
131            match self.resume()? {
132                Progress::Read(req) => pos = Some(req.fill_from(src, pos)?),
133                Progress::Done(v) => return Ok(v),
134            }
135        }
136    }
137}
138
139/// Run code that reads a stream to completion on this thread, reading from `src`.
140///
141/// This is `Task::new(total, make).run(src)` for code that does not need to be
142/// [`Send`]: it holds a callback that is not, say. The code is not boxed, and
143/// nothing outlives the call.
144pub fn block_on<R, T, F>(total: u64, src: &mut R, make: impl FnOnce(Io) -> F) -> Result<T>
145where
146    R: Read + Seek + ?Sized,
147    F: Future<Output = Result<T>>,
148{
149    let link = Arc::new(Link::default());
150    let io = Io::new(total, link.clone());
151    let mut fut = std::pin::pin!(make(io));
152    let mut cx = Context::from_waker(Waker::noop());
153    let mut pos = None;
154    loop {
155        match fut.as_mut().poll(&mut cx) {
156            Poll::Ready(done) => return done,
157            Poll::Pending => {
158                let Some(req) = ReadRequest::take(&link) else {
159                    return Err(Error::InvalidFormat(
160                        "task suspended on something other than a read".into(),
161                    ));
162                };
163                pos = Some(req.fill_from(src, pos)?);
164            }
165        }
166    }
167}
168
169/// What [`Task::resume`] found.
170#[derive(Debug)]
171#[non_exhaustive]
172pub enum Progress<'a, T> {
173    /// The task needs bytes; supply them and resume.
174    Read(ReadRequest<'a>),
175    /// The task finished with this result.
176    Done(T),
177}
178
179/// Bytes a suspended task is waiting for.
180///
181/// Put the stream's bytes from [`offset`](Self::offset) in
182/// [`buffer`](Self::buffer): at least [`min_len`](Self::min_len) of them, and up to
183/// [`window_len`](Self::window_len) if they are as easy to read. Fewer than
184/// `min_len` is an unexpected end of the stream, and the task fails. Then resume the
185/// task.
186pub struct ReadRequest<'a> {
187    link: Arc<Link>,
188    offset: u64,
189    min_len: usize,
190    window_len: usize,
191    /// The window's buffer, handed to the caller until the request is dropped.
192    buf: Vec<u8>,
193    /// Keeps the task from resuming while the request is out.
194    _task: PhantomData<&'a mut ()>,
195}
196
197impl Drop for ReadRequest<'_> {
198    fn drop(&mut self) {
199        // The task finds the buffer where it left it.
200        self.link.lock().buf = std::mem::take(&mut self.buf);
201    }
202}
203
204impl std::fmt::Debug for ReadRequest<'_> {
205    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
206        f.debug_struct("ReadRequest")
207            .field("offset", &self.offset)
208            .field("min_len", &self.min_len)
209            .field("window_len", &self.window_len)
210            .finish()
211    }
212}
213
214impl ReadRequest<'_> {
215    /// The request a suspended task has made, with the buffer it left for it.
216    fn take<'a>(link: &Arc<Link>) -> Option<ReadRequest<'a>> {
217        let mut slot = link.lock();
218        let (offset, min_len, window_len) = slot.request?;
219        Some(ReadRequest {
220            link: link.clone(),
221            offset,
222            min_len,
223            window_len,
224            buf: std::mem::take(&mut slot.buf),
225            _task: PhantomData,
226        })
227    }
228
229    /// Where in the stream the bytes are wanted.
230    pub fn offset(&self) -> u64 {
231        self.offset
232    }
233
234    /// The fewest bytes the task can go on with.
235    pub fn min_len(&self) -> usize {
236        self.min_len
237    }
238
239    /// How many bytes the task would like: at least `min_len`, and never past the
240    /// end of the stream.
241    pub fn window_len(&self) -> usize {
242        self.window_len
243    }
244
245    /// The buffer to fill. It starts empty; put the bytes in it, replacing what it
246    /// holds. Its capacity is reused between requests. The request owns it, so a
247    /// request can be held across an `.await`, and the task is given the buffer
248    /// back when the request is dropped.
249    pub fn buffer(&mut self) -> &mut Vec<u8> {
250        &mut self.buf
251    }
252
253    /// Fill the buffer from `src`, a seekable stream: seek to the offset and read up
254    /// to `window_len` bytes. The buffer is not zeroed first.
255    pub fn fill<R: Read + Seek + ?Sized>(self, src: &mut R) -> Result<()> {
256        self.fill_from(src, None).map(|_| ())
257    }
258
259    /// [`fill`](Self::fill), not seeking if `pos`, where the stream is now, is
260    /// already the offset. Returns where the stream is afterwards.
261    fn fill_from<R: Read + Seek + ?Sized>(mut self, src: &mut R, pos: Option<u64>) -> Result<u64> {
262        let (offset, window) = (self.offset, self.window_len);
263        if pos != Some(offset) {
264            src.seek(SeekFrom::Start(offset))?;
265        }
266        let buf = self.buffer();
267        buf.clear();
268        // Room for the whole window, so that the read does not probe and grow.
269        buf.reserve(window);
270        Read::take(&mut *src, window as u64).read_to_end(buf)?;
271        Ok(offset + buf.len() as u64)
272    }
273}
274
275#[cfg(test)]
276mod tests {
277    use std::io::Cursor;
278
279    use super::*;
280    use crate::io::DEFAULT_WINDOW;
281
282    /// Records `[len][len bytes]`; the sum of each record's bytes.
283    async fn sums(io: &mut Io) -> Result<Vec<u32>> {
284        let (mut at, mut out) = (0u64, Vec::new());
285        while at < io.len() {
286            let mut l = [0u8; 1];
287            io.read_at(at, &mut l).await?;
288            let body = io.fetch(at + 1, l[0] as usize).await?;
289            out.push(body[..l[0] as usize].iter().map(|&b| b as u32).sum());
290            at += 1 + l[0] as u64;
291        }
292        Ok(out)
293    }
294
295    fn records(n: usize) -> Vec<u8> {
296        let mut v = Vec::new();
297        for i in 0..n {
298            let len = (i * 7 % 23) as u8;
299            v.push(len);
300            v.extend((0..len).map(|j| (i as u8).wrapping_add(j)));
301        }
302        v
303    }
304
305    fn direct(data: &[u8]) -> Vec<u32> {
306        let (mut at, mut out) = (0usize, Vec::new());
307        while at < data.len() {
308            let l = data[at] as usize;
309            out.push(data[at + 1..at + 1 + l].iter().map(|&b| b as u32).sum());
310            at += 1 + l;
311        }
312        out
313    }
314
315    /// Run `sums`, counting the requests made.
316    fn run_counting(data: &[u8]) -> (Vec<u32>, usize) {
317        let mut task = Task::new(
318            data.len() as u64,
319            |mut io| async move { sums(&mut io).await },
320        );
321        let mut src = Cursor::new(data);
322        let mut requests = 0;
323        loop {
324            match task.resume().unwrap() {
325                Progress::Read(req) => {
326                    requests += 1;
327                    req.fill(&mut src).unwrap();
328                }
329                Progress::Done(v) => return (v, requests),
330            }
331        }
332    }
333
334    #[test]
335    fn a_task_runs_to_the_same_result_as_direct_code() {
336        let data = records(5_000);
337        let (got, _) = run_counting(&data);
338        assert_eq!(got, direct(&data));
339        // And through the blocking driver.
340        let t = Task::new(
341            data.len() as u64,
342            |mut io| async move { sums(&mut io).await },
343        );
344        assert_eq!(t.run(&mut Cursor::new(&data)).unwrap(), direct(&data));
345    }
346
347    #[test]
348    fn tiny_reads_become_few_requests() {
349        let data = records(5_000); // ~60 KB of records, ~10,000 reads
350        let (_, requests) = run_counting(&data);
351        let windows = data.len().div_ceil(DEFAULT_WINDOW);
352        assert!(
353            requests <= windows + 2,
354            "{requests} requests, {windows} windows"
355        );
356    }
357
358    #[test]
359    fn nothing_is_read_before_the_first_resume() {
360        let t = Task::new(10, |mut io| async move {
361            let mut b = [0u8; 1];
362            io.read_at(0, &mut b).await?;
363            Ok(b[0])
364        });
365        // Dropping an unstarted task is fine.
366        drop(t);
367    }
368
369    #[test]
370    fn requests_say_where_and_how_much() {
371        let mut task = Task::new(100_000, |mut io| async move {
372            let mut b = [0u8; 4];
373            io.read_at(50_000, &mut b).await?;
374            io.fetch_with(60_000, 10, 32 * 1024).await?;
375            Ok(())
376        });
377        let mut seen = Vec::new();
378        let src = vec![0u8; 100_000];
379        while let Progress::Read(req) = task.resume().unwrap() {
380            seen.push((req.offset(), req.min_len(), req.window_len()));
381            req.fill(&mut Cursor::new(&src)).unwrap();
382        }
383        assert_eq!(seen, vec![(50_000, 4, 4096), (60_000, 10, 32 * 1024)]);
384    }
385
386    #[test]
387    fn a_window_is_not_asked_for_past_the_end() {
388        let mut task = Task::new(100, |mut io| async move {
389            io.fetch(90, 4).await?;
390            Ok(())
391        });
392        let Progress::Read(req) = task.resume().unwrap() else {
393            panic!("expected a request");
394        };
395        assert_eq!((req.offset(), req.min_len(), req.window_len()), (90, 4, 10));
396    }
397
398    #[test]
399    fn reads_outside_the_stream_fail_without_a_request() {
400        let mut task = Task::new(10, |mut io| async move {
401            let mut b = [0u8; 4];
402            io.read_at(8, &mut b).await
403        });
404        assert!(matches!(task.resume(), Err(Error::Io(_))));
405        assert!(task.resume().is_err()); // finished
406    }
407
408    #[test]
409    fn a_short_answer_is_an_unexpected_end() {
410        let mut task = Task::new(100, |mut io| async move {
411            let mut b = [0u8; 8];
412            io.read_at(0, &mut b).await
413        });
414        match task.resume().unwrap() {
415            Progress::Read(mut req) => req.buffer().extend_from_slice(&[1, 2, 3]),
416            Progress::Done(_) => panic!("expected a request"),
417        }
418        let Err(Error::Io(e)) = task.resume() else {
419            panic!("expected an I/O error");
420        };
421        assert_eq!(e.kind(), std::io::ErrorKind::UnexpectedEof);
422    }
423
424    #[test]
425    fn read_vec_takes_the_window_without_a_copy() {
426        let data: Vec<u8> = (0..=255u8).cycle().take(50_000).collect();
427        let t = Task::new(data.len() as u64, |mut io| async move {
428            let mut head = [0u8; 2];
429            io.read_at(10, &mut head).await?;
430            let big = io.read_vec(1_000, 30_000).await?;
431            // The window was handed over; the next read asks again.
432            let mut again = [0u8; 2];
433            io.read_at(1_000, &mut again).await?;
434            Ok((head, big, again))
435        });
436        let (head, big, again) = t.run(&mut Cursor::new(&data)).unwrap();
437        assert_eq!(head, [10, 11]);
438        assert_eq!(big, data[1_000..31_000]);
439        assert_eq!(again, [(1_000 % 256) as u8, (1_001 % 256) as u8]);
440    }
441
442    #[test]
443    fn read_vec_of_nothing_is_empty_wherever_it_is() {
444        let data = vec![1u8; 100];
445        let t = Task::new(100, |mut io| async move {
446            let first = io.read_vec(10, 50).await?; // takes the window
447            let nothing = io.read_vec(100, 0).await?;
448            let also = io.read_vec(40, 0).await?;
449            Ok((first.len(), nothing, also))
450        });
451        let (n, nothing, also) = t.run(&mut Cursor::new(&data)).unwrap();
452        assert_eq!(n, 50);
453        assert!(nothing.is_empty() && also.is_empty());
454    }
455
456    #[test]
457    fn a_read_inside_the_window_makes_no_request() {
458        let data = vec![7u8; 8_000];
459        let mut task = Task::new(8_000, |mut io| async move {
460            let mut b = [0u8; 8];
461            for at in [0u64, 8, 100, 4_000] {
462                io.read_at(at, &mut b).await?;
463            }
464            Ok(())
465        });
466        let mut n = 0;
467        while let Progress::Read(req) = task.resume().unwrap() {
468            n += 1;
469            req.fill(&mut Cursor::new(&data)).unwrap();
470        }
471        assert_eq!(n, 1); // offsets 0..4095 held by the first window
472    }
473
474    #[test]
475    fn a_reader_reads_fields_in_order_and_tracks_its_position() {
476        let data: Vec<u8> = (0u8..64).collect();
477        let t = Task::new(64, |mut io| async move {
478            let mut r = io.reader(4);
479            let a = r.u8().await?;
480            let b = r.u16_be().await?;
481            let c = r.u16_le().await?;
482            let d = r.u32_be().await?;
483            let e = r.u32_le().await?;
484            let f = r.u64_be().await?;
485            let g = r.u64_le().await?;
486            let arr = r.array::<2>().await?;
487            let pos = r.pos();
488            r.skip(3);
489            let taken = r.take(2).await?.to_vec();
490            let after = r.pos();
491            r.seek(0);
492            let rem = r.remaining();
493            Ok((a, b, c, d, e, f, g, arr, pos, taken, after, rem))
494        });
495        let (a, b, c, d, e, f, g, arr, pos, taken, after, rem) =
496            t.run(&mut Cursor::new(&data)).unwrap();
497        assert_eq!(a, 4);
498        assert_eq!(b, 0x0506);
499        assert_eq!(c, 0x0807);
500        assert_eq!(d, 0x090a_0b0c);
501        assert_eq!(e, 0x100f_0e0d);
502        assert_eq!(f, 0x1112_1314_1516_1718);
503        assert_eq!(g, 0x201f_1e1d_1c1b_1a19);
504        assert_eq!(arr, [0x21, 0x22]);
505        assert_eq!(pos, 4 + 1 + 2 + 2 + 4 + 4 + 8 + 8 + 2);
506        assert_eq!(taken, vec![pos as u8 + 3, pos as u8 + 4]);
507        assert_eq!(after, pos + 3 + 2);
508        assert_eq!(rem, 64);
509    }
510
511    #[test]
512    fn a_reader_past_the_end_fails() {
513        let t = Task::new(6, |mut io| async move {
514            let mut r = io.reader(4);
515            r.u32_be().await
516        });
517        assert!(matches!(
518            t.run(&mut Cursor::new(vec![0u8; 6])),
519            Err(Error::Io(_))
520        ));
521    }
522
523    #[test]
524    fn empty_reads_need_nothing() {
525        let t = Task::new(4, |mut io| async move {
526            io.read_at(3, &mut []).await?;
527            assert!(io.fetch(2, 0).await?.is_empty());
528            Ok(io.reader(1).take(0).await?.len())
529        });
530        let mut n = 0;
531        let mut task = t;
532        while let Ok(Progress::Read(_)) = task.resume() {
533            n += 1;
534        }
535        assert_eq!(n, 0);
536    }
537
538    #[test]
539    fn a_task_and_its_requests_are_send() {
540        fn needs_send<T: Send>(_: &T) {}
541        let mut t: Task<'_, ()> =
542            Task::new(
543                8,
544                |mut io| async move { io.read_at(0, &mut [0u8; 4]).await },
545            );
546        needs_send(&t);
547        // A request can be held across an `.await` in a spawned task.
548        let Ok(Progress::Read(req)) = t.resume() else {
549            panic!("expected a request");
550        };
551        needs_send(&req);
552    }
553
554    #[test]
555    fn a_request_gives_the_buffer_back_when_dropped() {
556        let mut task = Task::new(8_000, |mut io| async move {
557            let mut b = [0u8; 4];
558            io.read_at(0, &mut b).await?;
559            io.read_at(5_000, &mut b).await?;
560            Ok(b)
561        });
562        let data: Vec<u8> = (0..8_000u32).map(|i| i as u8).collect();
563        let mut cap = 0;
564        loop {
565            match task.resume().unwrap() {
566                Progress::Read(mut req) => {
567                    let at = req.offset() as usize;
568                    let to = (at + req.window_len()).min(data.len());
569                    req.buffer().extend_from_slice(&data[at..to]);
570                    cap = cap.max(req.buffer().capacity());
571                }
572                Progress::Done(b) => {
573                    assert_eq!(b, [(5_000 % 256) as u8, 137, 138, 139]);
574                    break;
575                }
576            }
577        }
578        assert!(cap >= 4096);
579    }
580
581    #[test]
582    fn a_task_that_suspends_on_something_else_is_an_error() {
583        struct Never;
584        impl Future for Never {
585            type Output = ();
586
587            fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<()> {
588                Poll::Pending
589            }
590        }
591        let mut task: Task<'_, ()> = Task::new(1, |_| async {
592            Never.await;
593            Ok(())
594        });
595        assert!(task.resume().is_err());
596    }
597}