Skip to main content

f_office_opc/
source.rs

1//! Seekable backing sources for lazy ZIP package reading.
2
3use std::io::{self, Read, Seek, SeekFrom};
4use std::sync::Arc;
5#[cfg(not(target_arch = "wasm32"))]
6use std::sync::Mutex;
7
8/// Random-access byte source for opening a [`crate::Package`] without copying the entire ZIP
9/// archive into memory (for example, backed by a browser `Blob`/`File.slice()` or OPFS
10/// `FileSystemSyncAccessHandle`).
11pub trait RandomAccessRead: Send + Sync {
12    /// Total byte length of the source.
13    fn len(&self) -> u64;
14
15    /// Returns `true` when the source has zero bytes.
16    fn is_empty(&self) -> bool {
17        self.len() == 0
18    }
19
20    /// Reads bytes starting at `offset` into `buf`, returning the number of bytes read (0 at EOF).
21    ///
22    /// # Errors
23    ///
24    /// Returns an I/O error if reading from the underlying storage fails.
25    fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize>;
26}
27
28/// Random-access byte source behind a [`crate::Package`].
29pub(crate) enum Backing {
30    /// Shared in-memory ZIP bytes.
31    Memory(Arc<[u8]>),
32    /// A native file read lazily via seek + read so large packages never load into RAM.
33    #[cfg(not(target_arch = "wasm32"))]
34    File {
35        /// Open handle protected by a mutex for `Sync`.
36        file: Mutex<std::fs::File>,
37        /// File length in bytes at open time.
38        len: u64,
39    },
40    /// Caller-provided random-access byte source (such as browser `File.slice()` or OPFS).
41    Custom(Arc<dyn RandomAccessRead>),
42}
43
44impl Backing {
45    /// Total byte length of the backing source.
46    pub(crate) fn len(&self) -> u64 {
47        match self {
48            Self::Memory(bytes) => bytes.len() as u64,
49            #[cfg(not(target_arch = "wasm32"))]
50            Self::File { len, .. } => *len,
51            Self::Custom(source) => source.len(),
52        }
53    }
54}
55
56/// Independent `Read + Seek` cursor over a shared [`Backing`].
57#[derive(Clone)]
58pub(crate) struct BackingReader {
59    backing: Arc<Backing>,
60    pos: u64,
61}
62
63impl BackingReader {
64    /// Creates a reader positioned at byte 0 of `backing`.
65    pub(crate) const fn new(backing: Arc<Backing>) -> Self {
66        Self { backing, pos: 0 }
67    }
68}
69
70impl Read for BackingReader {
71    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
72        match self.backing.as_ref() {
73            Backing::Memory(bytes) => {
74                let Ok(offset) = usize::try_from(self.pos) else {
75                    return Ok(0);
76                };
77                let Some(rest) = bytes.get(offset..) else {
78                    return Ok(0);
79                };
80                let count = rest.len().min(buf.len());
81                if let (Some(src), Some(dst)) = (rest.get(..count), buf.get_mut(..count)) {
82                    dst.copy_from_slice(src);
83                    self.pos = self.pos.saturating_add(count as u64);
84                    Ok(count)
85                } else {
86                    Ok(0)
87                }
88            }
89            #[cfg(not(target_arch = "wasm32"))]
90            Backing::File { file, .. } => {
91                let mut guard = file
92                    .lock()
93                    .map_err(|_| io::Error::other("package file lock poisoned"))?;
94                guard.seek(SeekFrom::Start(self.pos))?;
95                let count = guard.read(buf)?;
96                drop(guard);
97                self.pos = self.pos.saturating_add(count as u64);
98                Ok(count)
99            }
100            Backing::Custom(source) => {
101                let count = source.read_at(self.pos, buf)?;
102                self.pos = self.pos.saturating_add(count as u64);
103                Ok(count)
104            }
105        }
106    }
107}
108
109impl Seek for BackingReader {
110    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
111        let len = self.backing.len();
112        let target: i128 = match pos {
113            SeekFrom::Start(offset) => i128::from(offset),
114            SeekFrom::End(delta) => i128::from(len) + i128::from(delta),
115            SeekFrom::Current(delta) => i128::from(self.pos) + i128::from(delta),
116        };
117        let next = u64::try_from(target).map_err(|_| {
118            io::Error::new(
119                io::ErrorKind::InvalidInput,
120                "cannot seek to a negative position",
121            )
122        })?;
123        self.pos = next;
124        Ok(next)
125    }
126}