Skip to main content

laminapdf_cos/
source.rs

1//! The input a [`Document`](crate::Document) owns: [`ByteSource`] ([ADR 0005] §2).
2//!
3//! [ADR 0005]: https://github.com/laudebugs/laminapdf/blob/main/docs/decisions/0005-document-model.md
4
5use std::borrow::Cow;
6use std::collections::BTreeMap;
7use std::fmt;
8use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
9
10use crate::error::{Error, Result as CosResult};
11
12/// Random-access input bytes: in memory, memory-mapped, a browser `Blob`, an HTTP range cache.
13///
14/// Synchronous by design (the core has no async runtime): a source whose bytes have not
15/// arrived yet answers [`SourceError::Pending`], and the shell fetches them and retries.
16/// In-memory sources return their bytes from [`ByteSource::as_slice`], which lets the
17/// parser work on them in place.
18///
19/// A source without `as_slice` is read in aligned 64 KiB windows (and small probes for xref
20/// entry checks); `read_at` may return fewer bytes than asked for and is called again for the
21/// rest. A [`SourceError::Pending`] is reported to the caller as
22/// [`Error::DataPending`](crate::Error::DataPending) with the range the source gave.
23///
24/// Core implementations: `Vec<u8>` (moved in), `Arc<[u8]>` (shared), `&'static [u8]`.
25/// Platform sources (mmap, `Blob`, OPFS) live in edge crates.
26///
27/// Added in 0.2.0.
28pub trait ByteSource: Send + Sync {
29    /// Total length in bytes.
30    ///
31    /// Added in 0.2.0.
32    fn len(&self) -> u64;
33
34    /// Whether the source holds no bytes.
35    ///
36    /// Added in 0.2.0.
37    fn is_empty(&self) -> bool {
38        self.len() == 0
39    }
40
41    /// Fills `buf` from `offset`; returns the bytes read (short only at the end of input).
42    ///
43    /// # Errors
44    /// [`SourceError::Pending`] when the range is not available yet, [`SourceError::Failed`]
45    /// when it cannot be read.
46    ///
47    /// Added in 0.2.0.
48    fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<usize, SourceError>;
49
50    /// The whole input, when it is already in memory (lets the parser skip copies).
51    ///
52    /// Added in 0.2.0.
53    fn as_slice(&self) -> Option<&[u8]> {
54        None
55    }
56}
57
58/// Why a [`ByteSource`] could not deliver a range.
59///
60/// Added in 0.2.0.
61#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
62#[non_exhaustive]
63pub enum SourceError {
64    /// The range has not been fetched yet; fetch it and retry the call.
65    #[error("bytes {offset}..+{len} are not available yet")]
66    Pending {
67        /// First byte of the missing range.
68        offset: u64,
69        /// Length of the missing range.
70        len: u64,
71    },
72    /// The range cannot be read.
73    #[error("bytes {offset}..+{len} could not be read")]
74    Failed {
75        /// First byte of the failed range.
76        offset: u64,
77        /// Length of the failed range.
78        len: u64,
79    },
80}
81
82/// Copies from an in-memory slice (the shared [`ByteSource::read_at`] of the core impls).
83fn read_slice(bytes: &[u8], offset: u64, buf: &mut [u8]) -> usize {
84    let Some(tail) = usize::try_from(offset).ok().and_then(|o| bytes.get(o..)) else {
85        return 0;
86    };
87    let n = tail.len().min(buf.len());
88    if let (Some(dst), Some(src)) = (buf.get_mut(..n), tail.get(..n)) {
89        dst.copy_from_slice(src);
90    }
91    n
92}
93
94macro_rules! in_memory_source {
95    ($ty:ty) => {
96        impl ByteSource for $ty {
97            fn len(&self) -> u64 {
98                u64::try_from(<[u8]>::len(self)).unwrap_or(u64::MAX)
99            }
100
101            fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<usize, SourceError> {
102                Ok(read_slice(self, offset, buf))
103            }
104
105            fn as_slice(&self) -> Option<&[u8]> {
106                let bytes: &[u8] = self;
107                Some(bytes)
108            }
109        }
110    };
111}
112
113in_memory_source!(Vec<u8>);
114in_memory_source!(Arc<[u8]>);
115in_memory_source!(&'static [u8]);
116
117/// Bytes per window: the unit in which a source without [`ByteSource::as_slice`] is read,
118/// cached and grown (ADR 0005 §2).
119pub(crate) const WINDOW: usize = 64 * 1024;
120
121/// Windows a [`Source`] keeps for reuse (4 MiB with [`WINDOW`]), shared by its clones. The
122/// least recently used one is dropped first, so a hostile file can't make the cache hold the
123/// whole input.
124const CACHE_WINDOWS: usize = 64;
125
126/// Reads that span at most this many windows go through the cache (an object across a window
127/// boundary, a scan chunk with its overlap). Longer ones (a large stream, a window grown for
128/// one object) are read past it, so they don't evict the windows everything else uses.
129const CACHED_SPAN: usize = 4;
130
131/// Missing ranges one call collects before it stops reading and reports them (1 024 windows,
132/// 64 MiB): a source whose `len()` claims far more than it has costs a bounded number of
133/// `read_at` calls per round, not one per window it claims.
134const MAX_PENDING: usize = 1024;
135
136/// A shared [`ByteSource`]: what [`Document::open`](crate::Document::open) takes.
137///
138/// Every [`ByteSource`] converts into one (`Vec<u8>`, `Arc<[u8]>`, `&'static [u8]`, or your
139/// own type), and so does an `Arc<dyn ByteSource>`. Cloning a `Source` is cheap and shares
140/// everything, including the window cache of a source that has no
141/// [`as_slice`](ByteSource::as_slice): documents opened on several threads (ADR 0005 §7) from
142/// clones of one `Source` reuse the windows each other read while they stay cached (two
143/// threads missing the same window at once may both read it).
144///
145/// A source without `as_slice` is never read whole: the reader asks for 64 KiB windows
146/// around the offsets it needs (grown while an object runs past the window's end, up to
147/// [`Limits::max_read_window`](crate::Limits::max_read_window)), keeps the 64 most recently
148/// used, checks xref entries with small reads, and reports the ranges a source answers
149/// [`SourceError::Pending`] for as [`Error::DataPending`](crate::Error::DataPending).
150///
151/// ```
152/// use std::sync::Arc;
153/// use laminapdf_cos::{ByteSource, Source};
154///
155/// let shared: Arc<dyn ByteSource> = Arc::new(b"%PDF-1.7".to_vec());
156/// let a = Source::from(shared);
157/// let b = a.clone();
158/// assert!(Arc::ptr_eq(a.get(), b.get()));
159/// ```
160///
161/// Added in 0.2.0.
162#[derive(Clone)]
163pub struct Source(Arc<Shared>);
164
165struct Shared {
166    source: Arc<dyn ByteSource>,
167    /// Recently read windows of a source without `as_slice`.
168    cache: Mutex<Cache>,
169}
170
171/// Windows by index (`offset / WINDOW`), each with the tick of its last use.
172#[derive(Default)]
173struct Cache {
174    windows: BTreeMap<usize, (Arc<[u8]>, u64)>,
175    tick: u64,
176}
177
178impl Cache {
179    /// Window `index`; `touch` marks it as just used (one-off reads don't, so they can't keep
180    /// a window alive that nothing else needs).
181    fn get(&mut self, index: usize, touch: bool) -> Option<Arc<[u8]>> {
182        self.tick += 1;
183        let tick = self.tick;
184        self.windows.get_mut(&index).map(|(bytes, used)| {
185            if touch {
186                *used = tick;
187            }
188            Arc::clone(bytes)
189        })
190    }
191
192    fn insert(&mut self, index: usize, bytes: Arc<[u8]>) {
193        self.tick += 1;
194        self.windows.insert(index, (bytes, self.tick));
195        while self.windows.len() > CACHE_WINDOWS {
196            let oldest = self.windows.iter().min_by_key(|(_, (_, used))| *used).map(|(&i, _)| i);
197            match oldest {
198                Some(i) => self.windows.remove(&i),
199                None => break,
200            };
201        }
202    }
203}
204
205/// How [`Source::read`] treats the cache.
206#[derive(Debug, Clone, Copy, PartialEq, Eq)]
207pub(crate) enum Fetch {
208    /// Read missing windows whole and keep them (for reads of at most [`CACHED_SPAN`]
209    /// windows; longer ones behave like [`Fetch::Exact`]).
210    Cached,
211    /// Use cached windows, read only the bytes asked for, keep nothing: for one-off looks
212    /// (probes) and long spans.
213    Exact,
214}
215
216/// A run of input bytes and where it starts.
217pub(crate) struct Window<'s> {
218    start: usize,
219    bytes: Bytes<'s>,
220    at_end: bool,
221}
222
223enum Bytes<'s> {
224    /// The whole in-memory input.
225    Borrowed(&'s [u8]),
226    /// One cached window, shared.
227    Shared(Arc<[u8]>),
228    /// Copied together from several windows, or read exactly.
229    Owned(Vec<u8>),
230}
231
232impl Window<'_> {
233    /// The bytes; `bytes()[0]` is input byte [`Window::start`].
234    pub(crate) fn bytes(&self) -> &[u8] {
235        match &self.bytes {
236            Bytes::Borrowed(b) => b,
237            Bytes::Shared(b) => b,
238            Bytes::Owned(b) => b,
239        }
240    }
241
242    /// The input offset of the first byte.
243    pub(crate) const fn start(&self) -> usize {
244        self.start
245    }
246
247    /// The input offset after the last byte.
248    pub(crate) fn end(&self) -> usize {
249        self.start + self.bytes().len()
250    }
251
252    /// Whether the window runs to the end of the input.
253    pub(crate) const fn at_end(&self) -> bool {
254        self.at_end
255    }
256
257    /// The bytes, owned (no copy when they already are).
258    pub(crate) fn into_vec(self) -> Vec<u8> {
259        match self.bytes {
260            Bytes::Owned(v) => v,
261            Bytes::Borrowed(b) => b.to_vec(),
262            Bytes::Shared(b) => b.to_vec(),
263        }
264    }
265
266    /// This window followed by (a copy of) `next`, which must start where this one ends.
267    pub(crate) fn append(self, next: &Self) -> Self {
268        let (start, at_end) = (self.start, next.at_end);
269        let mut bytes = self.into_vec();
270        bytes.extend_from_slice(next.bytes());
271        Window {
272            start,
273            bytes: Bytes::Owned(bytes),
274            at_end,
275        }
276    }
277
278    /// `before` followed by this window; `before` must end where this one starts.
279    pub(crate) fn prepend(self, before: Self) -> Self {
280        let (start, at_end) = (before.start, self.at_end);
281        let mut bytes = before.into_vec();
282        bytes.extend_from_slice(self.bytes());
283        Window {
284            start,
285            bytes: Bytes::Owned(bytes),
286            at_end,
287        }
288    }
289}
290
291/// Ranges sources answered [`SourceError::Pending`] for, collected so the shell can fetch
292/// them all in one round.
293#[derive(Debug, Default)]
294pub(crate) struct Pending(Vec<(u64, u64)>);
295
296impl Pending {
297    /// Keeps the ranges of an [`Error::DataPending`]; any other error is returned.
298    pub(crate) fn absorb(&mut self, e: Error) -> CosResult<()> {
299        match e {
300            Error::DataPending { ranges } => {
301                self.0.extend(ranges);
302                Ok(())
303            }
304            other => Err(other),
305        }
306    }
307
308    /// Whether nothing is pending.
309    pub(crate) const fn is_empty(&self) -> bool {
310        self.0.is_empty()
311    }
312
313    /// Whether enough is pending for one round ([`MAX_PENDING`] ranges): callers stop
314    /// reading.
315    pub(crate) const fn is_full(&self) -> bool {
316        self.0.len() >= MAX_PENDING
317    }
318
319    /// `Ok` when nothing is pending, else [`Error::DataPending`] with the ranges sorted and
320    /// overlapping or adjacent ones merged.
321    pub(crate) fn finish(self) -> CosResult<()> {
322        if self.0.is_empty() {
323            return Ok(());
324        }
325        Err(self.into_error())
326    }
327
328    /// [`Error::DataPending`] with the ranges sorted and merged.
329    pub(crate) fn into_error(self) -> Error {
330        Error::DataPending {
331            ranges: merge_ranges(self.0),
332        }
333    }
334}
335
336/// Sorts `(offset, len)` ranges and merges those that overlap or touch (the form
337/// [`Error::DataPending`] reports them in).
338///
339/// Added in 0.2.0.
340#[must_use]
341pub fn merge_ranges(mut ranges: Vec<(u64, u64)>) -> Vec<(u64, u64)> {
342    ranges.sort_unstable();
343    let mut merged: Vec<(u64, u64)> = Vec::with_capacity(ranges.len());
344    for (offset, len) in ranges {
345        let end = offset.saturating_add(len);
346        match merged.last_mut() {
347            Some((start, run)) if offset <= start.saturating_add(*run) => {
348                *run = end.max(start.saturating_add(*run)) - *start;
349            }
350            _ => merged.push((offset, len)),
351        }
352    }
353    merged
354}
355
356fn to_u64(n: usize) -> u64 {
357    u64::try_from(n).unwrap_or(u64::MAX)
358}
359
360/// A source length as an offset on this target, or an error when the target can't address
361/// all of it (a file over 4 GiB on wasm32): reading a prefix as if it were the whole file
362/// would give wrong results.
363fn addressable(len: u64, max: usize) -> CosResult<usize> {
364    usize::try_from(len)
365        .ok()
366        .filter(|&len| len <= max)
367        .ok_or(Error::InvalidStructure {
368            kind: "source",
369            message: "the input is larger than this target can address",
370        })
371}
372
373/// Fills `buf` from `offset` with as many `read_at` calls as it takes (a source that claims
374/// more bytes than `buf` has room for counts as having read only what fits).
375///
376/// # Errors
377/// The source's errors ([`Error::DataPending`] for [`SourceError::Pending`]);
378/// [`SourceError::Failed`] when the source ends before `buf` is full.
379///
380/// Added in 0.2.0.
381pub fn read_exact(source: &dyn ByteSource, offset: u64, buf: &mut [u8]) -> CosResult<()> {
382    let mut done = 0;
383    while let Some(rest) = buf.get_mut(done..).filter(|rest| !rest.is_empty()) {
384        let at = offset.saturating_add(to_u64(done));
385        let n = source.read_at(at, rest)?.min(rest.len());
386        if n == 0 {
387            return Err(Error::Source(SourceError::Failed {
388                offset: at,
389                len: to_u64(rest.len()),
390            }));
391        }
392        done += n;
393    }
394    Ok(())
395}
396
397/// One window's share of a [`Source::read`].
398enum Part {
399    /// A whole cached window.
400    Window(usize, Arc<[u8]>),
401    /// Bytes read just for this call.
402    Read(Vec<u8>),
403}
404
405impl Source {
406    fn new(source: Arc<dyn ByteSource>) -> Self {
407        Self(Arc::new(Shared {
408            source,
409            cache: Mutex::new(Cache::default()),
410        }))
411    }
412
413    /// The underlying source.
414    ///
415    /// Added in 0.2.0.
416    #[must_use]
417    pub fn get(&self) -> &Arc<dyn ByteSource> {
418        &self.0.source
419    }
420
421    /// The whole input, when the source holds it in memory ([`ByteSource::as_slice`]).
422    pub(crate) fn in_memory(&self) -> Option<&[u8]> {
423        self.0.source.as_slice()
424    }
425
426    /// The input length.
427    ///
428    /// # Errors
429    /// [`Error::InvalidStructure`] when the input is larger than this target can address.
430    pub(crate) fn len(&self) -> CosResult<usize> {
431        match self.in_memory() {
432            Some(slice) => Ok(slice.len()),
433            None => addressable(self.0.source.len(), usize::MAX),
434        }
435    }
436
437    fn cache(&self) -> MutexGuard<'_, Cache> {
438        // A panic while the lock was held can only have left a stale entry out, never a
439        // wrong one: every entry is inserted whole.
440        self.0.cache.lock().unwrap_or_else(PoisonError::into_inner)
441    }
442
443    /// Window `index` read whole and cached. The lock is not held while reading, so two
444    /// threads missing the same window may both read it.
445    fn read_window(&self, index: usize, total: usize) -> CosResult<Arc<[u8]>> {
446        let start = index.saturating_mul(WINDOW);
447        let mut buf = vec![0; total.saturating_sub(start).min(WINDOW)];
448        read_exact(self.0.source.as_ref(), to_u64(start), &mut buf)?;
449        let bytes: Arc<[u8]> = buf.into();
450        self.cache().insert(index, Arc::clone(&bytes));
451        Ok(bytes)
452    }
453
454    /// Input bytes `start..start + len`, cut at the end of the input. An in-memory input
455    /// returns all of itself instead, without copying. An empty range reads nothing.
456    ///
457    /// Cached windows are always used. Missing ones are read and kept with [`Fetch::Cached`]
458    /// when the range spans at most [`CACHED_SPAN`] windows; otherwise only the bytes asked
459    /// for are read, and nothing is kept.
460    ///
461    /// # Errors
462    /// [`Error::DataPending`] with the ranges the source does not have yet (up to
463    /// [`MAX_PENDING`] of them); [`Error::Source`] when it fails; [`Error::InvalidStructure`]
464    /// as [`Source::len`].
465    pub(crate) fn read(&self, start: usize, len: usize, fetch: Fetch) -> CosResult<Window<'_>> {
466        if let Some(slice) = self.in_memory() {
467            return Ok(Window {
468                start: 0,
469                bytes: Bytes::Borrowed(slice),
470                at_end: true,
471            });
472        }
473        let total = self.len()?;
474        let start = start.min(total);
475        let end = start.saturating_add(len).min(total);
476        let at_end = end == total;
477        if start == end {
478            return Ok(Window {
479                start,
480                bytes: Bytes::Owned(Vec::new()),
481                at_end,
482            });
483        }
484        let windows = start / WINDOW..end.div_ceil(WINDOW);
485        let keep = fetch == Fetch::Cached && windows.len() <= CACHED_SPAN;
486        let mut parts = Vec::new();
487        let mut pending = Pending::default();
488        for index in windows {
489            let window_start = index * WINDOW;
490            let (from, to) = (start.max(window_start), end.min(window_start + WINDOW));
491            // Bound first: a guard in the `match` scrutinee would be held through the arms,
492            // and `read_window` takes the lock again.
493            let cached = self.cache().get(index, keep);
494            let part = match cached {
495                Some(bytes) => Ok(Part::Window(window_start, bytes)),
496                None if keep => self.read_window(index, total).map(|b| Part::Window(window_start, b)),
497                None => {
498                    let mut buf = vec![0; to - from];
499                    read_exact(self.0.source.as_ref(), to_u64(from), &mut buf).map(|()| Part::Read(buf))
500                }
501            };
502            match part {
503                Ok(part) if pending.is_empty() => parts.push(part),
504                Ok(_) => {}
505                Err(e) => {
506                    pending.absorb(e)?;
507                    if pending.is_full() {
508                        break;
509                    }
510                }
511            }
512        }
513        pending.finish()?;
514        Ok(Window {
515            start,
516            bytes: assemble(parts, start, end),
517            at_end,
518        })
519    }
520
521    /// Reads (and caches) the windows holding each `(offset, len)` range, so that every range
522    /// a source is still missing is reported in one [`Error::DataPending`].
523    ///
524    /// # Errors
525    /// As [`Source::read`].
526    pub(crate) fn prefetch(&self, ranges: &[(usize, usize)]) -> CosResult<()> {
527        if self.in_memory().is_some() {
528            return Ok(());
529        }
530        let mut pending = Pending::default();
531        // `read` caches only spans of at most `CACHED_SPAN` windows, so a longer range is
532        // read in chunks of that size; otherwise its bytes would be fetched and dropped.
533        let chunk = WINDOW * CACHED_SPAN;
534        for &(start, len) in ranges {
535            let end = start.saturating_add(len);
536            let mut at = start;
537            while at < end {
538                let next = (at - at % WINDOW).saturating_add(chunk).min(end);
539                if let Err(e) = self.read(at, next - at, Fetch::Cached) {
540                    pending.absorb(e)?;
541                }
542                at = next;
543            }
544        }
545        pending.finish()
546    }
547
548    /// The whole input: borrowed when it is in memory, otherwise copied from cached windows
549    /// and read directly for the rest, without filling the cache. The buffer grows only as
550    /// bytes arrive, and a source missing much of its input is asked for the first
551    /// [`MAX_PENDING`] missing windows per round. Only for callers whose output holds the
552    /// whole input anyway (the incremental writer).
553    ///
554    /// # Errors
555    /// As [`Source::read`].
556    pub(crate) fn whole(&self) -> CosResult<Cow<'_, [u8]>> {
557        if let Some(slice) = self.in_memory() {
558            return Ok(Cow::Borrowed(slice));
559        }
560        let total = self.len()?;
561        Ok(Cow::Owned(self.read(0, total, Fetch::Exact)?.into_vec()))
562    }
563}
564
565/// The bytes `start..end` out of consecutive parts: a cached window itself when it is exactly
566/// that range, the bytes read when they are the only part, otherwise a copy.
567fn assemble(mut parts: Vec<Part>, start: usize, end: usize) -> Bytes<'static> {
568    if let [Part::Window(offset, bytes)] = parts.as_slice()
569        && *offset == start
570        && offset + <[u8]>::len(bytes) == end
571    {
572        return Bytes::Shared(Arc::clone(bytes));
573    }
574    if let [Part::Read(_)] = parts.as_slice()
575        && let Some(Part::Read(bytes)) = parts.pop()
576    {
577        return Bytes::Owned(bytes);
578    }
579    let mut out = Vec::new();
580    for part in &parts {
581        match part {
582            Part::Window(offset, bytes) => {
583                let from = start.saturating_sub(*offset);
584                let to = end.saturating_sub(*offset).min(<[u8]>::len(bytes));
585                out.extend_from_slice(bytes.get(from..to).unwrap_or_default());
586            }
587            Part::Read(bytes) => out.extend_from_slice(bytes),
588        }
589    }
590    Bytes::Owned(out)
591}
592
593impl fmt::Debug for Source {
594    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
595        f.debug_struct("Source")
596            .field("len", &self.0.source.len())
597            .field("in_memory", &self.0.source.as_slice().is_some())
598            .field("cached_windows", &self.cache().windows.len())
599            .finish()
600    }
601}
602
603impl<S: ByteSource + 'static> From<S> for Source {
604    fn from(source: S) -> Self {
605        Self::new(Arc::new(source))
606    }
607}
608
609impl From<Arc<dyn ByteSource>> for Source {
610    fn from(source: Arc<dyn ByteSource>) -> Self {
611        Self::new(source)
612    }
613}
614
615#[cfg(test)]
616pub(crate) mod tests {
617    use std::sync::atomic::{AtomicUsize, Ordering};
618
619    use super::*;
620
621    /// A source without `as_slice` over `data`, counting its `read_at` calls.
622    pub(crate) struct NoSlice {
623        data: Vec<u8>,
624        reads: AtomicUsize,
625    }
626
627    impl NoSlice {
628        pub(crate) fn source(data: impl Into<Vec<u8>>) -> (Source, Arc<Self>) {
629            let inner = Arc::new(Self {
630                data: data.into(),
631                reads: AtomicUsize::new(0),
632            });
633            (Source::from(Arc::clone(&inner) as Arc<dyn ByteSource>), inner)
634        }
635
636        pub(crate) fn reads(&self) -> usize {
637            self.reads.load(Ordering::Relaxed)
638        }
639    }
640
641    impl ByteSource for NoSlice {
642        fn len(&self) -> u64 {
643            u64::try_from(self.data.len()).unwrap()
644        }
645
646        fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<usize, SourceError> {
647            self.reads.fetch_add(1, Ordering::Relaxed);
648            Ok(read_slice(&self.data, offset, buf))
649        }
650    }
651
652    /// `len` bytes counting up, so every offset is recognisable.
653    pub(crate) fn numbered(len: usize) -> Vec<u8> {
654        (0..len).map(|i| u8::try_from(i % 251).unwrap()).collect()
655    }
656
657    #[test]
658    fn window_reads_whole_aligned_windows_and_cuts_the_requested_range() {
659        let data = numbered(3 * WINDOW);
660        let (source, inner) = NoSlice::source(data.clone());
661        let window = source.read(WINDOW - 10, 20, Fetch::Cached).unwrap();
662        assert_eq!(
663            (window.start(), window.bytes(), window.at_end(), inner.reads()),
664            (WINDOW - 10, &data[WINDOW - 10..WINDOW + 10], false, 2)
665        );
666    }
667
668    #[test]
669    fn a_window_that_is_exactly_one_cached_window_is_shared_not_copied() {
670        let (source, _) = NoSlice::source(numbered(2 * WINDOW));
671        let first = source.read(WINDOW, WINDOW, Fetch::Cached).unwrap();
672        let second = source.read(WINDOW, WINDOW, Fetch::Cached).unwrap();
673        assert!(std::ptr::eq(first.bytes(), second.bytes()));
674    }
675
676    #[test]
677    fn a_prefetch_longer_than_the_cached_span_is_kept_for_later_reads() {
678        let windows = 2 * CACHED_SPAN + 1;
679        let (source, inner) = NoSlice::source(numbered(windows * WINDOW));
680        source.prefetch(&[(0, windows * WINDOW)]).unwrap();
681        let after_prefetch = inner.reads();
682        for w in 0..windows {
683            source.read(w * WINDOW, WINDOW, Fetch::Cached).unwrap();
684        }
685        assert_eq!(inner.reads(), after_prefetch);
686    }
687
688    #[test]
689    fn a_window_past_the_end_is_cut_and_marked_at_end() {
690        let (source, _) = NoSlice::source(numbered(WINDOW + 5));
691        let window = source.read(WINDOW, 4 * WINDOW, Fetch::Cached).unwrap();
692        assert_eq!((window.bytes().len(), window.at_end()), (5, true));
693    }
694
695    #[test]
696    fn cached_windows_are_not_read_again() {
697        let (source, inner) = NoSlice::source(numbered(2 * WINDOW));
698        source.read(0, 2 * WINDOW, Fetch::Cached).unwrap();
699        source.read(10, 2 * WINDOW, Fetch::Cached).unwrap();
700        assert_eq!(inner.reads(), 2);
701    }
702
703    #[test]
704    fn the_cache_keeps_a_bounded_number_of_windows() {
705        let (source, _) = NoSlice::source(numbered((CACHE_WINDOWS + 3) * WINDOW));
706        for index in 0..CACHE_WINDOWS + 3 {
707            source.read(index * WINDOW, WINDOW, Fetch::Cached).unwrap();
708        }
709        assert_eq!(source.cache().windows.len(), CACHE_WINDOWS);
710    }
711
712    #[test]
713    fn the_least_recently_used_window_is_evicted_first() {
714        let (source, inner) = NoSlice::source(numbered((CACHE_WINDOWS + 1) * WINDOW));
715        for index in 0..CACHE_WINDOWS {
716            source.read(index * WINDOW, 1, Fetch::Cached).unwrap();
717        }
718        source.read(0, 1, Fetch::Cached).unwrap(); // window 0 is now the most recently used
719        source.read(CACHE_WINDOWS * WINDOW, 1, Fetch::Cached).unwrap(); // evicts window 1
720        let before = inner.reads();
721        source.read(0, 1, Fetch::Cached).unwrap();
722        let after_0 = inner.reads();
723        source.read(WINDOW, 1, Fetch::Cached).unwrap();
724        assert_eq!((after_0 - before, inner.reads() - after_0), (0, 1));
725    }
726
727    #[test]
728    fn exact_reads_only_the_range_and_does_not_cache_it() {
729        let data = numbered(2 * WINDOW);
730        let (source, _) = NoSlice::source(data.clone());
731        let probe = source.read(100, 32, Fetch::Exact).unwrap();
732        assert_eq!((probe.bytes(), source.cache().windows.len()), (&data[100..132], 0));
733    }
734
735    #[test]
736    fn exact_uses_cached_windows_when_they_hold_the_range() {
737        let (source, inner) = NoSlice::source(numbered(WINDOW));
738        source.read(0, WINDOW, Fetch::Cached).unwrap();
739        source.read(100, 32, Fetch::Exact).unwrap();
740        assert_eq!(inner.reads(), 1);
741    }
742
743    #[test]
744    fn an_in_memory_source_returns_all_of_itself_without_copying() {
745        let data: Arc<[u8]> = numbered(100).into();
746        let source = Source::from(Arc::clone(&data));
747        let window = source.read(40, 10, Fetch::Cached).unwrap();
748        assert!(window.start() == 0 && std::ptr::eq(window.bytes(), data.as_ref()));
749    }
750
751    /// Answers `Pending` for every read of window 1 and window 3.
752    struct Holes(Vec<u8>);
753
754    impl ByteSource for Holes {
755        fn len(&self) -> u64 {
756            u64::try_from(self.0.len()).unwrap()
757        }
758
759        fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<usize, SourceError> {
760            let index = usize::try_from(offset).unwrap() / WINDOW;
761            if index == 1 || index == 3 {
762                return Err(SourceError::Pending {
763                    offset,
764                    len: u64::try_from(buf.len()).unwrap(),
765                });
766            }
767            Ok(read_slice(&self.0, offset, buf))
768        }
769    }
770
771    #[test]
772    fn a_window_reports_every_missing_part_at_once() {
773        let source = Source::from(Holes(numbered(5 * WINDOW)));
774        let w = to_u64(WINDOW);
775        assert_eq!(
776            source.read(0, 5 * WINDOW, Fetch::Cached).err(),
777            Some(Error::DataPending {
778                ranges: vec![(w, w), (3 * w, w)]
779            })
780        );
781    }
782
783    #[test]
784    fn whole_reads_every_window_or_reports_the_missing_ones() {
785        let source = Source::from(Holes(numbered(5 * WINDOW)));
786        let w = to_u64(WINDOW);
787        assert_eq!(
788            source.whole().err(),
789            Some(Error::DataPending {
790                ranges: vec![(w, w), (3 * w, w)]
791            })
792        );
793    }
794
795    #[test]
796    fn merge_ranges_sorts_and_joins_overlapping_and_adjacent_ranges() {
797        assert_eq!(
798            merge_ranges(vec![(50, 10), (0, 10), (10, 5), (12, 1), (58, 4), (100, 1)]),
799            vec![(0, 15), (50, 12), (100, 1)]
800        );
801    }
802
803    #[test]
804    fn read_exact_fails_cleanly_when_a_source_ends_before_its_length() {
805        /// Claims a terabyte, holds three bytes.
806        struct Liar;
807        impl ByteSource for Liar {
808            fn len(&self) -> u64 {
809                1 << 40
810            }
811            fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<usize, SourceError> {
812                Ok(read_slice(b"abc", offset, buf))
813            }
814        }
815        let mut buf = [0; 10];
816        assert_eq!(
817            read_exact(&Liar, 0, &mut buf),
818            Err(Error::Source(SourceError::Failed { offset: 3, len: 7 }))
819        );
820    }
821
822    fn read(source: &dyn ByteSource, offset: u64, len: usize) -> Vec<u8> {
823        let mut buf = vec![0; len];
824        let n = source.read_at(offset, &mut buf).unwrap();
825        buf.truncate(n);
826        buf
827    }
828
829    #[test]
830    fn vec_source_reads_a_range() {
831        assert_eq!(read(&b"abcdef".to_vec(), 2, 3), b"cde");
832    }
833
834    #[test]
835    fn arc_source_reads_short_at_the_end() {
836        let source: Arc<[u8]> = Arc::from(&b"abcdef"[..]);
837        assert_eq!(read(&source, 4, 10), b"ef");
838    }
839
840    #[test]
841    fn static_source_reads_nothing_past_the_end() {
842        let source: &'static [u8] = b"abc";
843        assert_eq!(read(&source, 99, 4), b"");
844    }
845
846    #[test]
847    fn in_memory_sources_expose_their_slice() {
848        let source: &'static [u8] = b"abc";
849        assert_eq!(ByteSource::as_slice(&source), Some(&b"abc"[..]));
850    }
851
852    #[test]
853    fn empty_vec_source_is_empty() {
854        assert!(ByteSource::is_empty(&Vec::<u8>::new()));
855    }
856
857    #[test]
858    fn len_counts_bytes() {
859        let source: Arc<[u8]> = Arc::from(&b"abcdef"[..]);
860        assert_eq!(ByteSource::len(&source), 6);
861    }
862
863    #[test]
864    fn an_empty_range_reads_nothing() {
865        let (source, inner) = NoSlice::source(numbered(2 * WINDOW));
866        let window = source.read(WINDOW + 7, 0, Fetch::Cached).unwrap();
867        assert_eq!((window.bytes().len(), inner.reads()), (0, 0));
868    }
869
870    #[test]
871    fn a_long_read_does_not_evict_the_cached_windows() {
872        let (source, inner) = NoSlice::source(numbered((CACHE_WINDOWS + 10) * WINDOW));
873        source.read(0, WINDOW, Fetch::Cached).unwrap();
874        source
875            .read(WINDOW, (CACHE_WINDOWS + 5) * WINDOW, Fetch::Cached)
876            .unwrap();
877        let before = inner.reads();
878        source.read(0, WINDOW, Fetch::Cached).unwrap();
879        assert_eq!((inner.reads() - before, source.cache().windows.len()), (0, 1));
880    }
881
882    #[test]
883    fn an_exact_read_uses_the_cached_part_and_reads_only_the_rest() {
884        let data = numbered(2 * WINDOW);
885        let (source, inner) = NoSlice::source(data.clone());
886        source.read(0, WINDOW, Fetch::Cached).unwrap();
887        let before = inner.reads();
888        let window = source.read(WINDOW - 10, 20, Fetch::Exact).unwrap();
889        assert_eq!(
890            (window.bytes(), inner.reads() - before),
891            (&data[WINDOW - 10..WINDOW + 10], 1)
892        );
893    }
894
895    #[test]
896    fn whole_copies_cached_windows_and_reads_the_rest_without_caching() {
897        let data = numbered(3 * WINDOW + 5);
898        let (source, inner) = NoSlice::source(data.clone());
899        source.read(WINDOW, WINDOW, Fetch::Cached).unwrap();
900        let whole = source.whole().unwrap().into_owned();
901        assert_eq!(
902            (whole == data, inner.reads(), source.cache().windows.len()),
903            (true, 4, 1)
904        );
905    }
906
907    /// Claims a terabyte and answers `Pending` for all of it.
908    struct PendingTerabyte(AtomicUsize);
909
910    impl ByteSource for PendingTerabyte {
911        fn len(&self) -> u64 {
912            1 << 40
913        }
914
915        fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<usize, SourceError> {
916            self.0.fetch_add(1, Ordering::Relaxed);
917            Err(SourceError::Pending {
918                offset,
919                len: u64::try_from(buf.len()).unwrap(),
920            })
921        }
922    }
923
924    #[test]
925    fn whole_on_a_source_that_overstates_its_length_stops_after_one_round_of_ranges() {
926        let inner = Arc::new(PendingTerabyte(AtomicUsize::new(0)));
927        let source = Source::from(Arc::clone(&inner) as Arc<dyn ByteSource>);
928        let Err(Error::DataPending { ranges }) = source.whole() else {
929            panic!("expected DataPending");
930        };
931        assert_eq!(
932            (inner.0.load(Ordering::Relaxed), ranges,),
933            (MAX_PENDING, vec![(0, to_u64(MAX_PENDING * WINDOW))])
934        );
935    }
936
937    #[test]
938    fn a_length_over_what_the_target_addresses_is_an_error_not_a_prefix() {
939        let wasm32_max = usize::try_from(u32::MAX).unwrap();
940        assert_eq!(
941            (
942                addressable(5 << 30, wasm32_max).is_err(),
943                addressable(5 << 20, wasm32_max)
944            ),
945            (true, Ok(5 << 20))
946        );
947    }
948}