f-office-opc 0.2.2

Open Packaging Conventions container: ZIP package and relationships, with input limits.
Documentation
//! Seekable backing sources for lazy ZIP package reading.

use std::io::{self, Read, Seek, SeekFrom};
use std::sync::Arc;
#[cfg(not(target_arch = "wasm32"))]
use std::sync::Mutex;

/// Random-access byte source for opening a [`crate::Package`] without copying the entire ZIP
/// archive into memory (for example, backed by a browser `Blob`/`File.slice()` or OPFS
/// `FileSystemSyncAccessHandle`).
pub trait RandomAccessRead: Send + Sync {
    /// Total byte length of the source.
    fn len(&self) -> u64;

    /// Returns `true` when the source has zero bytes.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Reads bytes starting at `offset` into `buf`, returning the number of bytes read (0 at EOF).
    ///
    /// # Errors
    ///
    /// Returns an I/O error if reading from the underlying storage fails.
    fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize>;
}

/// Random-access byte source behind a [`crate::Package`].
pub(crate) enum Backing {
    /// Shared in-memory ZIP bytes.
    Memory(Arc<[u8]>),
    /// A native file read lazily via seek + read so large packages never load into RAM.
    #[cfg(not(target_arch = "wasm32"))]
    File {
        /// Open handle protected by a mutex for `Sync`.
        file: Mutex<std::fs::File>,
        /// File length in bytes at open time.
        len: u64,
    },
    /// Caller-provided random-access byte source (such as browser `File.slice()` or OPFS).
    Custom(Arc<dyn RandomAccessRead>),
}

impl Backing {
    /// Total byte length of the backing source.
    pub(crate) fn len(&self) -> u64 {
        match self {
            Self::Memory(bytes) => bytes.len() as u64,
            #[cfg(not(target_arch = "wasm32"))]
            Self::File { len, .. } => *len,
            Self::Custom(source) => source.len(),
        }
    }
}

/// Independent `Read + Seek` cursor over a shared [`Backing`].
#[derive(Clone)]
pub(crate) struct BackingReader {
    backing: Arc<Backing>,
    pos: u64,
}

impl BackingReader {
    /// Creates a reader positioned at byte 0 of `backing`.
    pub(crate) const fn new(backing: Arc<Backing>) -> Self {
        Self { backing, pos: 0 }
    }
}

impl Read for BackingReader {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self.backing.as_ref() {
            Backing::Memory(bytes) => {
                let Ok(offset) = usize::try_from(self.pos) else {
                    return Ok(0);
                };
                let Some(rest) = bytes.get(offset..) else {
                    return Ok(0);
                };
                let count = rest.len().min(buf.len());
                if let (Some(src), Some(dst)) = (rest.get(..count), buf.get_mut(..count)) {
                    dst.copy_from_slice(src);
                    self.pos = self.pos.saturating_add(count as u64);
                    Ok(count)
                } else {
                    Ok(0)
                }
            }
            #[cfg(not(target_arch = "wasm32"))]
            Backing::File { file, .. } => {
                let mut guard = file
                    .lock()
                    .map_err(|_| io::Error::other("package file lock poisoned"))?;
                guard.seek(SeekFrom::Start(self.pos))?;
                let count = guard.read(buf)?;
                drop(guard);
                self.pos = self.pos.saturating_add(count as u64);
                Ok(count)
            }
            Backing::Custom(source) => {
                let count = source.read_at(self.pos, buf)?;
                self.pos = self.pos.saturating_add(count as u64);
                Ok(count)
            }
        }
    }
}

impl Seek for BackingReader {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        let len = self.backing.len();
        let target: i128 = match pos {
            SeekFrom::Start(offset) => i128::from(offset),
            SeekFrom::End(delta) => i128::from(len) + i128::from(delta),
            SeekFrom::Current(delta) => i128::from(self.pos) + i128::from(delta),
        };
        let next = u64::try_from(target).map_err(|_| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                "cannot seek to a negative position",
            )
        })?;
        self.pos = next;
        Ok(next)
    }
}