asset-io 0.3.0

Streaming, container-agnostic access to media file structure and metadata (JUMBF, XMP)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
// Copyright 2026 Adobe. All rights reserved.
// This file is licensed to you under the Apache License,
// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// or the MIT license (http://opensource.org/licenses/MIT),
// at your option.

// Unless required by applicable law or agreed to in writing,
// this software is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
// specific language governing permissions and limitations under
// each license.

//! Code that reads a stream, written once, run by any I/O; see [`Task`].

use std::{
    future::Future,
    io::{Read, Seek, SeekFrom},
    marker::PhantomData,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll, Waker},
};

use crate::{
    error::{Error, Result},
    io::{Io, Link},
};

/// A suspended computation that reads a stream: run it with [`run`](Self::run), or
/// drive it yourself with [`resume`](Self::resume).
///
/// Code that reads is written once, as straight-line `async` code over an [`Io`]:
///
/// ```
/// # use asset_io::{Result, io::{Io}, task::{Progress, Task}};
/// async fn first_byte(io: &mut Io) -> Result<u8> {
///     let mut b = [0u8; 1];
///     io.read_at(0, &mut b).await?;
///     Ok(b[0])
/// }
///
/// # fn main() -> Result<()> {
/// let data = [7u8, 8, 9];
/// let mut task = Task::new(data.len() as u64, |mut io| async move {
///     first_byte(&mut io).await
/// });
/// let first = loop {
///     match task.resume()? {
///         // The task has nothing to read from; it asks. Answer however you like.
///         Progress::Read(mut req) => {
///             let at = req.offset() as usize;
///             req.buffer().extend_from_slice(&data[at..]);
///         }
///         Progress::Done(v) => break v,
///         _ => unreachable!(),
///     }
/// };
/// assert_eq!(first, 7);
/// # Ok(())
/// # }
/// ```
///
/// The task does not read anything itself. When it needs bytes that its [`Io`] does
/// not already hold, it suspends, and [`resume`](Self::resume) returns a
/// [`ReadRequest`]: where to read and how much. The caller reads however it likes
/// (blocking, `async`, from a network buffer it already has), puts the bytes in the
/// request's buffer, and resumes. [`run`](Self::run) is the blocking driver for a
/// `Read + Seek`. No runtime is involved and no I/O trait is required: the task is
/// driven by plain method calls, so it is `Send` and works under any executor.
///
/// [`Io`] keeps a window of the stream, so a run of tiny reads (a chunk header, a
/// box header) becomes one request for a few KiB, and the code makes no system call
/// of its own.
pub struct Task<'f, T> {
    fut: Pin<Box<dyn Future<Output = Result<T>> + Send + 'f>>,
    link: Arc<Link>,
    finished: bool,
}

impl<'f, T> Task<'f, T> {
    /// A task for the stream of `total` bytes that `make` reads through the `Io` it
    /// is given. Nothing runs until the first [`resume`](Self::resume).
    pub fn new<F>(total: u64, make: impl FnOnce(Io) -> F) -> Self
    where
        F: Future<Output = Result<T>> + Send + 'f,
    {
        let link = Arc::new(Link::default());
        let io = Io::new(total, link.clone());
        Self {
            fut: Box::pin(make(io)),
            link,
            finished: false,
        }
    }

    /// Run until the task needs bytes it does not have, or finishes.
    ///
    /// On [`Progress::Read`], fill the request's buffer and call `resume` again.
    /// An error is final. Calling `resume` after the task has finished is an
    /// error.
    pub fn resume(&mut self) -> Result<Progress<'_, T>> {
        if self.finished {
            return Err(Error::InvalidFormat("task already finished".into()));
        }
        let mut cx = Context::from_waker(Waker::noop());
        match self.fut.as_mut().poll(&mut cx) {
            Poll::Ready(done) => {
                self.finished = true;
                done.map(Progress::Done)
            }
            Poll::Pending => match ReadRequest::take(&self.link) {
                Some(req) => Ok(Progress::Read(req)),
                None => {
                    self.finished = true;
                    Err(Error::InvalidFormat(
                        "task suspended on something other than a read".into(),
                    ))
                }
            },
        }
    }

    /// Run to completion, reading from `src`, which must be the stream the task was
    /// made for.
    pub fn run<R: Read + Seek + ?Sized>(mut self, src: &mut R) -> Result<T> {
        // Where the stream is, so that a request that continues the last one does
        // not seek.
        let mut pos = None;
        loop {
            match self.resume()? {
                Progress::Read(req) => pos = Some(req.fill_from(src, pos)?),
                Progress::Done(v) => return Ok(v),
            }
        }
    }
}

/// Run code that reads a stream to completion on this thread, reading from `src`.
///
/// This is `Task::new(total, make).run(src)` for code that does not need to be
/// [`Send`]: it holds a callback that is not, say. The code is not boxed, and
/// nothing outlives the call.
pub fn block_on<R, T, F>(total: u64, src: &mut R, make: impl FnOnce(Io) -> F) -> Result<T>
where
    R: Read + Seek + ?Sized,
    F: Future<Output = Result<T>>,
{
    let link = Arc::new(Link::default());
    let io = Io::new(total, link.clone());
    let mut fut = std::pin::pin!(make(io));
    let mut cx = Context::from_waker(Waker::noop());
    let mut pos = None;
    loop {
        match fut.as_mut().poll(&mut cx) {
            Poll::Ready(done) => return done,
            Poll::Pending => {
                let Some(req) = ReadRequest::take(&link) else {
                    return Err(Error::InvalidFormat(
                        "task suspended on something other than a read".into(),
                    ));
                };
                pos = Some(req.fill_from(src, pos)?);
            }
        }
    }
}

/// What [`Task::resume`] found.
#[derive(Debug)]
#[non_exhaustive]
pub enum Progress<'a, T> {
    /// The task needs bytes; supply them and resume.
    Read(ReadRequest<'a>),
    /// The task finished with this result.
    Done(T),
}

/// Bytes a suspended task is waiting for.
///
/// Put the stream's bytes from [`offset`](Self::offset) in
/// [`buffer`](Self::buffer): at least [`min_len`](Self::min_len) of them, and up to
/// [`window_len`](Self::window_len) if they are as easy to read. Fewer than
/// `min_len` is an unexpected end of the stream, and the task fails. Then resume the
/// task.
pub struct ReadRequest<'a> {
    link: Arc<Link>,
    offset: u64,
    min_len: usize,
    window_len: usize,
    /// The window's buffer, handed to the caller until the request is dropped.
    buf: Vec<u8>,
    /// Keeps the task from resuming while the request is out.
    _task: PhantomData<&'a mut ()>,
}

impl Drop for ReadRequest<'_> {
    fn drop(&mut self) {
        // The task finds the buffer where it left it.
        self.link.lock().buf = std::mem::take(&mut self.buf);
    }
}

impl std::fmt::Debug for ReadRequest<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ReadRequest")
            .field("offset", &self.offset)
            .field("min_len", &self.min_len)
            .field("window_len", &self.window_len)
            .finish()
    }
}

impl ReadRequest<'_> {
    /// The request a suspended task has made, with the buffer it left for it.
    fn take<'a>(link: &Arc<Link>) -> Option<ReadRequest<'a>> {
        let mut slot = link.lock();
        let (offset, min_len, window_len) = slot.request?;
        Some(ReadRequest {
            link: link.clone(),
            offset,
            min_len,
            window_len,
            buf: std::mem::take(&mut slot.buf),
            _task: PhantomData,
        })
    }

    /// Where in the stream the bytes are wanted.
    pub fn offset(&self) -> u64 {
        self.offset
    }

    /// The fewest bytes the task can go on with.
    pub fn min_len(&self) -> usize {
        self.min_len
    }

    /// How many bytes the task would like: at least `min_len`, and never past the
    /// end of the stream.
    pub fn window_len(&self) -> usize {
        self.window_len
    }

    /// The buffer to fill. It starts empty; put the bytes in it, replacing what it
    /// holds. Its capacity is reused between requests. The request owns it, so a
    /// request can be held across an `.await`, and the task is given the buffer
    /// back when the request is dropped.
    pub fn buffer(&mut self) -> &mut Vec<u8> {
        &mut self.buf
    }

    /// Fill the buffer from `src`, a seekable stream: seek to the offset and read up
    /// to `window_len` bytes. The buffer is not zeroed first.
    pub fn fill<R: Read + Seek + ?Sized>(self, src: &mut R) -> Result<()> {
        self.fill_from(src, None).map(|_| ())
    }

    /// [`fill`](Self::fill), not seeking if `pos`, where the stream is now, is
    /// already the offset. Returns where the stream is afterwards.
    fn fill_from<R: Read + Seek + ?Sized>(mut self, src: &mut R, pos: Option<u64>) -> Result<u64> {
        let (offset, window) = (self.offset, self.window_len);
        if pos != Some(offset) {
            src.seek(SeekFrom::Start(offset))?;
        }
        let buf = self.buffer();
        buf.clear();
        // Room for the whole window, so that the read does not probe and grow.
        buf.reserve(window);
        Read::take(&mut *src, window as u64).read_to_end(buf)?;
        Ok(offset + buf.len() as u64)
    }
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use super::*;
    use crate::io::DEFAULT_WINDOW;

    /// Records `[len][len bytes]`; the sum of each record's bytes.
    async fn sums(io: &mut Io) -> Result<Vec<u32>> {
        let (mut at, mut out) = (0u64, Vec::new());
        while at < io.len() {
            let mut l = [0u8; 1];
            io.read_at(at, &mut l).await?;
            let body = io.fetch(at + 1, l[0] as usize).await?;
            out.push(body[..l[0] as usize].iter().map(|&b| b as u32).sum());
            at += 1 + l[0] as u64;
        }
        Ok(out)
    }

    fn records(n: usize) -> Vec<u8> {
        let mut v = Vec::new();
        for i in 0..n {
            let len = (i * 7 % 23) as u8;
            v.push(len);
            v.extend((0..len).map(|j| (i as u8).wrapping_add(j)));
        }
        v
    }

    fn direct(data: &[u8]) -> Vec<u32> {
        let (mut at, mut out) = (0usize, Vec::new());
        while at < data.len() {
            let l = data[at] as usize;
            out.push(data[at + 1..at + 1 + l].iter().map(|&b| b as u32).sum());
            at += 1 + l;
        }
        out
    }

    /// Run `sums`, counting the requests made.
    fn run_counting(data: &[u8]) -> (Vec<u32>, usize) {
        let mut task = Task::new(
            data.len() as u64,
            |mut io| async move { sums(&mut io).await },
        );
        let mut src = Cursor::new(data);
        let mut requests = 0;
        loop {
            match task.resume().unwrap() {
                Progress::Read(req) => {
                    requests += 1;
                    req.fill(&mut src).unwrap();
                }
                Progress::Done(v) => return (v, requests),
            }
        }
    }

    #[test]
    fn a_task_runs_to_the_same_result_as_direct_code() {
        let data = records(5_000);
        let (got, _) = run_counting(&data);
        assert_eq!(got, direct(&data));
        // And through the blocking driver.
        let t = Task::new(
            data.len() as u64,
            |mut io| async move { sums(&mut io).await },
        );
        assert_eq!(t.run(&mut Cursor::new(&data)).unwrap(), direct(&data));
    }

    #[test]
    fn tiny_reads_become_few_requests() {
        let data = records(5_000); // ~60 KB of records, ~10,000 reads
        let (_, requests) = run_counting(&data);
        let windows = data.len().div_ceil(DEFAULT_WINDOW);
        assert!(
            requests <= windows + 2,
            "{requests} requests, {windows} windows"
        );
    }

    #[test]
    fn nothing_is_read_before_the_first_resume() {
        let t = Task::new(10, |mut io| async move {
            let mut b = [0u8; 1];
            io.read_at(0, &mut b).await?;
            Ok(b[0])
        });
        // Dropping an unstarted task is fine.
        drop(t);
    }

    #[test]
    fn requests_say_where_and_how_much() {
        let mut task = Task::new(100_000, |mut io| async move {
            let mut b = [0u8; 4];
            io.read_at(50_000, &mut b).await?;
            io.fetch_with(60_000, 10, 32 * 1024).await?;
            Ok(())
        });
        let mut seen = Vec::new();
        let src = vec![0u8; 100_000];
        while let Progress::Read(req) = task.resume().unwrap() {
            seen.push((req.offset(), req.min_len(), req.window_len()));
            req.fill(&mut Cursor::new(&src)).unwrap();
        }
        assert_eq!(seen, vec![(50_000, 4, 4096), (60_000, 10, 32 * 1024)]);
    }

    #[test]
    fn a_window_is_not_asked_for_past_the_end() {
        let mut task = Task::new(100, |mut io| async move {
            io.fetch(90, 4).await?;
            Ok(())
        });
        let Progress::Read(req) = task.resume().unwrap() else {
            panic!("expected a request");
        };
        assert_eq!((req.offset(), req.min_len(), req.window_len()), (90, 4, 10));
    }

    #[test]
    fn reads_outside_the_stream_fail_without_a_request() {
        let mut task = Task::new(10, |mut io| async move {
            let mut b = [0u8; 4];
            io.read_at(8, &mut b).await
        });
        assert!(matches!(task.resume(), Err(Error::Io(_))));
        assert!(task.resume().is_err()); // finished
    }

    #[test]
    fn a_short_answer_is_an_unexpected_end() {
        let mut task = Task::new(100, |mut io| async move {
            let mut b = [0u8; 8];
            io.read_at(0, &mut b).await
        });
        match task.resume().unwrap() {
            Progress::Read(mut req) => req.buffer().extend_from_slice(&[1, 2, 3]),
            Progress::Done(_) => panic!("expected a request"),
        }
        let Err(Error::Io(e)) = task.resume() else {
            panic!("expected an I/O error");
        };
        assert_eq!(e.kind(), std::io::ErrorKind::UnexpectedEof);
    }

    #[test]
    fn read_vec_takes_the_window_without_a_copy() {
        let data: Vec<u8> = (0..=255u8).cycle().take(50_000).collect();
        let t = Task::new(data.len() as u64, |mut io| async move {
            let mut head = [0u8; 2];
            io.read_at(10, &mut head).await?;
            let big = io.read_vec(1_000, 30_000).await?;
            // The window was handed over; the next read asks again.
            let mut again = [0u8; 2];
            io.read_at(1_000, &mut again).await?;
            Ok((head, big, again))
        });
        let (head, big, again) = t.run(&mut Cursor::new(&data)).unwrap();
        assert_eq!(head, [10, 11]);
        assert_eq!(big, data[1_000..31_000]);
        assert_eq!(again, [(1_000 % 256) as u8, (1_001 % 256) as u8]);
    }

    #[test]
    fn read_vec_of_nothing_is_empty_wherever_it_is() {
        let data = vec![1u8; 100];
        let t = Task::new(100, |mut io| async move {
            let first = io.read_vec(10, 50).await?; // takes the window
            let nothing = io.read_vec(100, 0).await?;
            let also = io.read_vec(40, 0).await?;
            Ok((first.len(), nothing, also))
        });
        let (n, nothing, also) = t.run(&mut Cursor::new(&data)).unwrap();
        assert_eq!(n, 50);
        assert!(nothing.is_empty() && also.is_empty());
    }

    #[test]
    fn a_read_inside_the_window_makes_no_request() {
        let data = vec![7u8; 8_000];
        let mut task = Task::new(8_000, |mut io| async move {
            let mut b = [0u8; 8];
            for at in [0u64, 8, 100, 4_000] {
                io.read_at(at, &mut b).await?;
            }
            Ok(())
        });
        let mut n = 0;
        while let Progress::Read(req) = task.resume().unwrap() {
            n += 1;
            req.fill(&mut Cursor::new(&data)).unwrap();
        }
        assert_eq!(n, 1); // offsets 0..4095 held by the first window
    }

    #[test]
    fn a_reader_reads_fields_in_order_and_tracks_its_position() {
        let data: Vec<u8> = (0u8..64).collect();
        let t = Task::new(64, |mut io| async move {
            let mut r = io.reader(4);
            let a = r.u8().await?;
            let b = r.u16_be().await?;
            let c = r.u16_le().await?;
            let d = r.u32_be().await?;
            let e = r.u32_le().await?;
            let f = r.u64_be().await?;
            let g = r.u64_le().await?;
            let arr = r.array::<2>().await?;
            let pos = r.pos();
            r.skip(3);
            let taken = r.take(2).await?.to_vec();
            let after = r.pos();
            r.seek(0);
            let rem = r.remaining();
            Ok((a, b, c, d, e, f, g, arr, pos, taken, after, rem))
        });
        let (a, b, c, d, e, f, g, arr, pos, taken, after, rem) =
            t.run(&mut Cursor::new(&data)).unwrap();
        assert_eq!(a, 4);
        assert_eq!(b, 0x0506);
        assert_eq!(c, 0x0807);
        assert_eq!(d, 0x090a_0b0c);
        assert_eq!(e, 0x100f_0e0d);
        assert_eq!(f, 0x1112_1314_1516_1718);
        assert_eq!(g, 0x201f_1e1d_1c1b_1a19);
        assert_eq!(arr, [0x21, 0x22]);
        assert_eq!(pos, 4 + 1 + 2 + 2 + 4 + 4 + 8 + 8 + 2);
        assert_eq!(taken, vec![pos as u8 + 3, pos as u8 + 4]);
        assert_eq!(after, pos + 3 + 2);
        assert_eq!(rem, 64);
    }

    #[test]
    fn a_reader_past_the_end_fails() {
        let t = Task::new(6, |mut io| async move {
            let mut r = io.reader(4);
            r.u32_be().await
        });
        assert!(matches!(
            t.run(&mut Cursor::new(vec![0u8; 6])),
            Err(Error::Io(_))
        ));
    }

    #[test]
    fn empty_reads_need_nothing() {
        let t = Task::new(4, |mut io| async move {
            io.read_at(3, &mut []).await?;
            assert!(io.fetch(2, 0).await?.is_empty());
            Ok(io.reader(1).take(0).await?.len())
        });
        let mut n = 0;
        let mut task = t;
        while let Ok(Progress::Read(_)) = task.resume() {
            n += 1;
        }
        assert_eq!(n, 0);
    }

    #[test]
    fn a_task_and_its_requests_are_send() {
        fn needs_send<T: Send>(_: &T) {}
        let mut t: Task<'_, ()> =
            Task::new(
                8,
                |mut io| async move { io.read_at(0, &mut [0u8; 4]).await },
            );
        needs_send(&t);
        // A request can be held across an `.await` in a spawned task.
        let Ok(Progress::Read(req)) = t.resume() else {
            panic!("expected a request");
        };
        needs_send(&req);
    }

    #[test]
    fn a_request_gives_the_buffer_back_when_dropped() {
        let mut task = Task::new(8_000, |mut io| async move {
            let mut b = [0u8; 4];
            io.read_at(0, &mut b).await?;
            io.read_at(5_000, &mut b).await?;
            Ok(b)
        });
        let data: Vec<u8> = (0..8_000u32).map(|i| i as u8).collect();
        let mut cap = 0;
        loop {
            match task.resume().unwrap() {
                Progress::Read(mut req) => {
                    let at = req.offset() as usize;
                    let to = (at + req.window_len()).min(data.len());
                    req.buffer().extend_from_slice(&data[at..to]);
                    cap = cap.max(req.buffer().capacity());
                }
                Progress::Done(b) => {
                    assert_eq!(b, [(5_000 % 256) as u8, 137, 138, 139]);
                    break;
                }
            }
        }
        assert!(cap >= 4096);
    }

    #[test]
    fn a_task_that_suspends_on_something_else_is_an_error() {
        struct Never;
        impl Future for Never {
            type Output = ();

            fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<()> {
                Poll::Pending
            }
        }
        let mut task: Task<'_, ()> = Task::new(1, |_| async {
            Never.await;
            Ok(())
        });
        assert!(task.resume().is_err());
    }
}