asset-io 0.7.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
// 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.

//! Windowed, asynchronous stream reads for handlers and advanced clients.
//!
//! Compose reads inside a [`crate::task::Task`], or use the async methods on
//! [`crate::Structure`]. Handler authors can import [`Io`] and [`BoxFuture`]
//! through [`crate::container_api`].

use std::{
    future::Future,
    pin::Pin,
    sync::{Arc, Mutex, MutexGuard},
    task::{Context, Poll},
};

use crate::error::{Error, Result};

/// How much of the stream is requested at a time unless the code asks for more. The
/// markers of a typical JPEG, and the headers of a typical PNG, fit in a few KiB.
/// Measured on 24 fixtures (Apple M2): 4 KiB was as fast as or faster than 8, 16
/// and 32 KiB, from memory and from a file.
pub const DEFAULT_WINDOW: usize = 4 * 1024;

/// A boxed future that can move between threads, as the `async` parts of a
/// [`ContainerHandler`](crate::container_api::ContainerHandler) return.
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// What a suspended reader is waiting for, and the buffer it will be given.
#[derive(Default)]
pub(super) struct Slot {
    /// `(offset, minimum length, window length)` of the outstanding request.
    pub(super) request: Option<(u64, usize, usize)>,
    /// The window's buffer while the reader is suspended, so the caller can fill it
    /// and no copy is made.
    pub(super) buf: Vec<u8>,
}

/// The one thing a reader and its driver share. It is locked only when the reader
/// suspends or resumes, never on a read that the window already holds.
#[derive(Default)]
pub(super) struct Link {
    slot: Mutex<Slot>,
}

impl Link {
    pub(super) fn lock(&self) -> MutexGuard<'_, Slot> {
        self.slot.lock().unwrap_or_else(|e| e.into_inner())
    }
}

/// A window onto a stream of known length, for code that reads it.
///
/// Reads are `async`: each either completes at once from the window, or suspends
/// until the driver has supplied the bytes.
pub struct Io {
    link: Arc<Link>,
    total: u64,
    /// The window: stream bytes `[start, start + win.len())`.
    win: Vec<u8>,
    start: u64,
}

impl Io {
    pub(super) fn new(total: u64, link: Arc<Link>) -> Self {
        Self {
            link,
            total,
            win: Vec::new(),
            start: 0,
        }
    }

    /// Length of the stream.
    pub fn len(&self) -> u64 {
        self.total
    }

    /// Whether the stream is empty.
    pub fn is_empty(&self) -> bool {
        self.total == 0
    }

    /// Another `Io` over the same stream and driver, with an empty window, for
    /// code that takes an `Io` by value (a handler's
    /// [`parse_async`](crate::container_api::ContainerHandler::parse_async)) inside a longer task.
    /// The callee owns the fork, leaving this `Io` available after it finishes.
    /// This does not create a new task, thread, or independent I/O driver.
    ///
    /// The fork shares the stream length and read-request channel, but not this
    /// `Io`'s cached bytes. It starts with an empty window and may request bytes
    /// already cached here. Its window is not transferred back when it finishes;
    /// dropping it discards that window. Creating a fork only clones the channel's
    /// `Arc`, without allocating another channel or copying bytes.
    ///
    /// # Sequential use only
    ///
    /// Finish the operation using the fork before reading through this `Io` or
    /// another fork, for example by immediately awaiting the callee. The shared
    /// channel holds only one outstanding request and response buffer: concurrent
    /// reads can overwrite requests or consume another reader's response. Its
    /// mutex protects memory access, not concurrent-reader correctness. The owned
    /// fork does not borrow this `Io`, so Rust does not enforce this sequencing.
    ///
    /// A fork is neither a substream nor a snapshot: offsets still address the
    /// same complete stream, whose bytes must remain unchanged while cached.
    pub fn fork(&self) -> Io {
        Io::new(self.total, self.link.clone())
    }

    #[cfg(feature = "svg")]
    pub(crate) fn into_tokio_reader(self) -> TokioReader {
        TokioReader {
            io: self,
            pos: 0,
            asked: false,
        }
    }

    fn covers(&self, offset: u64, len: usize) -> bool {
        offset >= self.start
            && offset
                .checked_add(len as u64)
                .is_some_and(|end| end <= self.start + self.win.len() as u64)
    }

    /// Read exactly `buf.len()` bytes at `offset`. Fails with an unexpected-end
    /// error if they are not all inside the stream.
    pub async fn read_at(&mut self, offset: u64, buf: &mut [u8]) -> Result<()> {
        // Most reads are held by the window already.
        if buf.is_empty() {
            return Ok(());
        }
        if self.covers(offset, buf.len()) {
            let from = (offset - self.start) as usize;
            buf.copy_from_slice(&self.win[from..from + buf.len()]);
            return Ok(());
        }
        let bytes = self.fetch(offset, buf.len()).await?;
        buf.copy_from_slice(&bytes[..buf.len()]);
        Ok(())
    }

    /// The bytes of the stream from `offset` to the end of the window, at least
    /// `min` of them, without copying. Use them before the next read: the slice
    /// borrows the `Io`.
    pub async fn fetch(&mut self, offset: u64, min: usize) -> Result<&[u8]> {
        self.fetch_with(offset, min, DEFAULT_WINDOW).await
    }

    /// Like [`fetch`](Self::fetch), asking the driver for a window of `window`
    /// bytes when the data is not already held: a scan that will read on from here
    /// asks for more than the default.
    pub async fn fetch_with(&mut self, offset: u64, min: usize, window: usize) -> Result<&[u8]> {
        if min == 0 {
            return Ok(&[]);
        }
        if self.covers(offset, min) {
            return Ok(&self.win[(offset - self.start) as usize..]);
        }
        Fetch {
            io: &mut *self,
            offset,
            min,
            window: window.max(min),
            asked: false,
        }
        .await?;
        let from = (offset - self.start) as usize;
        Ok(&self.win[from..])
    }

    /// `len` bytes at `offset` in a new `Vec`. The bytes are read straight into it,
    /// so a large read is not copied. The caller bounds `len`.
    pub async fn read_vec(&mut self, offset: u64, len: usize) -> Result<Vec<u8>> {
        if len == 0 {
            return Ok(Vec::new());
        }
        // A window of exactly the length wanted, taken whole.
        self.fetch_with(offset, len, len).await?;
        let from = (offset - self.start) as usize;
        let mut v = std::mem::take(&mut self.win);
        v.drain(..from);
        v.truncate(len);
        self.start = 0;
        Ok(v)
    }
}

#[cfg(feature = "svg")]
/// Adapts task-driven reads to Tokio's I/O traits without requiring a runtime.
pub(crate) struct TokioReader {
    io: Io,
    pos: u64,
    asked: bool,
}

#[cfg(feature = "svg")]
impl tokio::io::AsyncRead for TokioReader {
    fn poll_read(
        self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
        buf: &mut tokio::io::ReadBuf<'_>,
    ) -> Poll<std::io::Result<()>> {
        let this = self.get_mut();
        if buf.remaining() == 0 {
            return Poll::Ready(Ok(()));
        }

        if this.asked {
            let mut slot = this.io.link.lock();
            this.io.win = std::mem::take(&mut slot.buf);
            slot.request = None;
            this.io.start = this.pos;
            this.asked = false;
            if !this.io.covers(this.pos, 1) {
                return Poll::Ready(Err(std::io::Error::new(
                    std::io::ErrorKind::UnexpectedEof,
                    "failed to fill whole buffer",
                )));
            }
        }

        if this.io.covers(this.pos, 1) {
            let from = (this.pos - this.io.start) as usize;
            let count = (this.io.win.len() - from).min(buf.remaining());
            buf.put_slice(&this.io.win[from..from + count]);
            this.pos += count as u64;
            return Poll::Ready(Ok(()));
        }

        if this.pos == this.io.total {
            return Poll::Ready(Ok(()));
        }

        let window = (DEFAULT_WINDOW as u64).min(this.io.total - this.pos) as usize;
        let mut bytes = std::mem::take(&mut this.io.win);
        bytes.clear();
        let mut slot = this.io.link.lock();
        slot.request = Some((this.pos, 1, window));
        slot.buf = bytes;
        this.asked = true;
        Poll::Pending
    }
}

impl Io {
    /// A cursor over the stream, starting at `at`, for reading a run of fields one
    /// after another. It borrows the `Io`, so its position is visible only where it
    /// is used; the `Io` itself has no position.
    pub fn reader(&mut self, at: u64) -> Reader<'_> {
        Reader { io: self, pos: at }
    }
}

/// A position in the stream and the reads that move it; see [`Io::reader`].
pub struct Reader<'a> {
    io: &'a mut Io,
    pos: u64,
}

impl Reader<'_> {
    /// Where the next read starts.
    pub fn pos(&self) -> u64 {
        self.pos
    }

    /// Move to `to`.
    pub fn seek(&mut self, to: u64) {
        self.pos = to;
    }

    /// Move `n` bytes on, without reading them.
    pub fn skip(&mut self, n: u64) {
        self.pos = self.pos.saturating_add(n);
    }

    /// Bytes from the position to the end of the stream.
    pub fn remaining(&self) -> u64 {
        self.io.total.saturating_sub(self.pos)
    }

    /// The next `n` bytes, borrowed from the window, and move past them.
    pub async fn take(&mut self, n: usize) -> Result<&[u8]> {
        let at = self.pos;
        self.pos = at.saturating_add(n as u64);
        let bytes = self.io.fetch(at, n).await?;
        Ok(&bytes[..n])
    }

    /// Fill `buf` from the next bytes, and move past them.
    pub async fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
        let at = self.pos;
        self.pos = at.saturating_add(buf.len() as u64);
        self.io.read_at(at, buf).await
    }

    /// The next `N` bytes, if the window holds them: no suspension, so no future to
    /// build. Most reads of a field are this.
    fn held<const N: usize>(&mut self) -> Option<[u8; N]> {
        if !self.io.covers(self.pos, N) {
            return None;
        }
        let from = (self.pos - self.io.start) as usize;
        self.pos += N as u64;
        self.io.win[from..from + N].try_into().ok()
    }

    /// The next `N` bytes.
    pub async fn array<const N: usize>(&mut self) -> Result<[u8; N]> {
        if let Some(a) = self.held::<N>() {
            return Ok(a);
        }
        let mut a = [0u8; N];
        self.read_exact(&mut a).await?;
        Ok(a)
    }

    /// One byte.
    pub async fn u8(&mut self) -> Result<u8> {
        if let Some([b]) = self.held::<1>() {
            return Ok(b);
        }
        Ok(self.array::<1>().await?[0])
    }

    /// A big-endian `u16`.
    pub async fn u16_be(&mut self) -> Result<u16> {
        if let Some(a) = self.held() {
            return Ok(u16::from_be_bytes(a));
        }
        Ok(u16::from_be_bytes(self.array().await?))
    }

    /// A little-endian `u16`.
    pub async fn u16_le(&mut self) -> Result<u16> {
        if let Some(a) = self.held() {
            return Ok(u16::from_le_bytes(a));
        }
        Ok(u16::from_le_bytes(self.array().await?))
    }

    /// A big-endian `u32`.
    pub async fn u32_be(&mut self) -> Result<u32> {
        if let Some(a) = self.held() {
            return Ok(u32::from_be_bytes(a));
        }
        Ok(u32::from_be_bytes(self.array().await?))
    }

    /// A little-endian `u32`.
    pub async fn u32_le(&mut self) -> Result<u32> {
        if let Some(a) = self.held() {
            return Ok(u32::from_le_bytes(a));
        }
        Ok(u32::from_le_bytes(self.array().await?))
    }

    /// A big-endian `u64`.
    pub async fn u64_be(&mut self) -> Result<u64> {
        if let Some(a) = self.held() {
            return Ok(u64::from_be_bytes(a));
        }
        Ok(u64::from_be_bytes(self.array().await?))
    }

    /// A little-endian `u64`.
    pub async fn u64_le(&mut self) -> Result<u64> {
        if let Some(a) = self.held() {
            return Ok(u64::from_le_bytes(a));
        }
        Ok(u64::from_le_bytes(self.array().await?))
    }
}

/// The future behind [`Io::fetch_with`].
struct Fetch<'a> {
    io: &'a mut Io,
    offset: u64,
    min: usize,
    window: usize,
    asked: bool,
}

/// The error a short read gives: the same one `Read::read_exact` does, so that the
/// message does not depend on how the bytes were read.
fn eof() -> Error {
    Error::Io(std::io::Error::new(
        std::io::ErrorKind::UnexpectedEof,
        "failed to fill whole buffer",
    ))
}

impl Future for Fetch<'_> {
    type Output = Result<()>;

    fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
        let this = &mut *self;
        if this.asked {
            // Resumed: the driver has filled the buffer.
            let mut slot = this.io.link.lock();
            this.io.win = std::mem::take(&mut slot.buf);
            slot.request = None;
            this.io.start = this.offset;
            this.asked = false;
            return Poll::Ready(if this.io.covers(this.offset, this.min) {
                Ok(())
            } else {
                Err(eof())
            });
        }
        if this.io.covers(this.offset, this.min) {
            return Poll::Ready(Ok(()));
        }
        let inside = this
            .offset
            .checked_add(this.min as u64)
            .is_some_and(|end| end <= this.io.total);
        if !inside {
            return Poll::Ready(Err(eof()));
        }
        // Not held: suspend and ask for a window, no longer than the stream.
        let window = (this.window as u64).min(this.io.total - this.offset) as usize;
        let mut buf = std::mem::take(&mut this.io.win);
        buf.clear();
        let mut slot = this.io.link.lock();
        slot.request = Some((this.offset, this.min, window.max(this.min)));
        slot.buf = buf;
        this.asked = true;
        Poll::Pending
    }
}