coip-reader 0.2.0

High-performance read-only reader for COI (.coi) columnar IP databases with projection, LRU caching, and serde support
Documentation
//! Backing storage abstractions (`&[u8]`, `Vec<u8>`, `mmap`, `File`).

use std::borrow::Cow;
use std::fs::File;
use std::sync::Mutex;

use coip_format::FormatError;

use crate::error::Result;

pub enum Backing<'a> {
    Slice(&'a [u8]),
    Owned(Vec<u8>),
    #[cfg(feature = "mmap")]
    Mmap(memmap2::Mmap),
    File {
        file: Mutex<File>,
        len: u64,
    },
}

impl<'a> Backing<'a> {
    #[inline]
    pub fn len(&self) -> u64 {
        match self {
            Self::Slice(s) => s.len() as u64,
            Self::Owned(v) => v.len() as u64,
            #[cfg(feature = "mmap")]
            Self::Mmap(m) => m.len() as u64,
            Self::File { len, .. } => *len,
        }
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Read `[offset .. offset + len]`, borrowing zero-copy when backed by memory/mmap.
    #[inline]
    pub fn read_slice(&self, offset: u64, len: usize) -> Result<Cow<'_, [u8]>> {
        let end = offset
            .checked_add(len as u64)
            .ok_or(FormatError::UnexpectedEof)?;
        if end > self.len() {
            return Err(FormatError::UnexpectedEof.into());
        }
        match self {
            Self::Slice(s) => {
                let start = offset as usize;
                Ok(Cow::Borrowed(&s[start..start + len]))
            }
            Self::Owned(v) => {
                let start = offset as usize;
                Ok(Cow::Borrowed(&v[start..start + len]))
            }
            #[cfg(feature = "mmap")]
            Self::Mmap(m) => {
                let start = offset as usize;
                Ok(Cow::Borrowed(&m[start..start + len]))
            }
            Self::File { file, .. } => {
                use std::io::{Read, Seek, SeekFrom};
                let mut buf = vec![0u8; len];
                let mut guard = file.lock().expect("file lock poisoned");
                guard.seek(SeekFrom::Start(offset))?;
                guard.read_exact(&mut buf)?;
                Ok(Cow::Owned(buf))
            }
        }
    }
}