use std::collections::HashMap;
use std::fs::File;
use std::path::Path;
use std::sync::Arc;
use anyhow::Result;
use memmap2::Mmap;
use crate::transcripts::models::Transcript;
use crate::transcripts::store::{
fnv1a_64, linear_probe, parse_header, read_record, ReadonlyTxStore, TxBytes, INDEX_ENTRY_SIZE,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TxBackend {
Mmap,
Pread,
}
pub struct PreadSource {
file: Arc<File>,
len: usize,
}
impl PreadSource {
#[inline]
pub(crate) fn len(&self) -> usize {
self.len
}
pub(crate) fn read_at(&self, offset: usize, len: usize) -> Option<Vec<u8>> {
let end = offset.checked_add(len)?;
if end > self.len {
return None;
}
crate::posread::read_exact_window(&self.file, offset, len).ok()
}
}
pub struct TxStore {
bytes: TxBytes,
record_count: u64,
index_offset: u64,
mane_index_offset: u64,
decoded_cache: HashMap<u64, Transcript>,
}
impl TxStore {
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
Self::open_mmap(path)
}
pub fn open_mmap<P: AsRef<Path>>(path: P) -> Result<Self> {
let file = File::open(path.as_ref())?;
let mmap = unsafe { Mmap::map(&file)? };
let bytes = TxBytes::Mmap(mmap);
let header = parse_header(&bytes)?;
Ok(Self {
bytes,
record_count: header.record_count,
index_offset: header.index_offset,
mane_index_offset: header.mane_index_offset,
decoded_cache: HashMap::new(),
})
}
#[inline]
pub fn len(&self) -> u64 {
self.record_count
}
#[inline]
pub fn is_empty(&self) -> bool {
self.record_count == 0
}
pub fn lookup(&self, accession: &str) -> Option<Transcript> {
let hash = fnv1a_64(accession.as_bytes());
self.lookup_by_hash(accession, hash)
}
fn lookup_by_hash(&self, accession: &str, hash: u64) -> Option<Transcript> {
let bytes = &self.bytes;
let idx_start = self.index_offset as usize;
let record_bound = self.index_offset as usize;
let count = self.record_count as usize;
let mut lo = 0usize;
let mut hi = count;
while lo < hi {
let mid = lo + (hi - lo) / 2;
let entry_offset = idx_start + mid * INDEX_ENTRY_SIZE;
let entry_hash = bytes.read_u64_le(entry_offset)?;
match entry_hash.cmp(&hash) {
std::cmp::Ordering::Less => lo = mid + 1,
std::cmp::Ordering::Greater => hi = mid,
std::cmp::Ordering::Equal => {
let record_offset = bytes.read_u64_le(entry_offset + 8)? as usize;
let tx = read_record(bytes, record_offset, record_bound)?;
if tx.accession == accession {
return Some(tx);
}
return linear_probe(
bytes,
self.index_offset,
record_bound,
accession,
hash,
mid,
count,
);
}
}
}
None
}
pub fn ensure_decoded(&mut self, accession: &str) -> Result<()> {
let hash = fnv1a_64(accession.as_bytes());
if self.decoded_cache.contains_key(&hash) {
return Ok(());
}
if let Some(tx) = self.lookup_by_hash(accession, hash) {
self.decoded_cache.insert(hash, tx);
}
Ok(())
}
pub fn ensure_decoded_where<F>(&mut self, predicate: F) -> Result<usize>
where
F: Fn(&Transcript) -> bool,
{
let idx_start = self.index_offset as usize;
let record_bound = self.index_offset as usize;
let mut decoded: Vec<(u64, Transcript)> = Vec::new();
for i in 0..self.record_count as usize {
let entry_offset = idx_start + i * INDEX_ENTRY_SIZE;
let hash = self
.bytes
.read_u64_le(entry_offset)
.ok_or_else(|| anyhow::anyhow!("index entry out of bounds"))?;
let record_offset = self
.bytes
.read_u64_le(entry_offset + 8)
.ok_or_else(|| anyhow::anyhow!("index entry out of bounds"))?
as usize;
if let Some(tx) = read_record(&self.bytes, record_offset, record_bound)
&& predicate(&tx)
{
decoded.push((hash, tx));
}
}
let count = decoded.len();
for (hash, tx) in decoded {
self.decoded_cache.insert(hash, tx);
}
Ok(count)
}
pub fn into_readonly(mut self) -> ReadonlyTxStore {
if self.record_count < 500_000 && self.decoded_cache.is_empty() {
let _ = self.ensure_decoded_where(|_| true);
}
self.build_readonly()
}
pub fn into_readonly_lazy(self) -> ReadonlyTxStore {
self.build_readonly()
}
fn build_readonly(self) -> ReadonlyTxStore {
ReadonlyTxStore::from_parts(
self.bytes,
self.record_count,
self.index_offset,
self.mane_index_offset,
self.decoded_cache,
)
}
}
impl ReadonlyTxStore {
pub fn open_with_backend<P: AsRef<Path>>(path: P, backend: TxBackend) -> Result<Self> {
match backend {
TxBackend::Mmap => Self::open_mmap(path),
TxBackend::Pread => Self::open_pread(path),
}
}
pub fn open_mmap<P: AsRef<Path>>(path: P) -> Result<Self> {
let file = File::open(path.as_ref())?;
let mmap = unsafe { Mmap::map(&file)? };
Self::from_byte_source(TxBytes::Mmap(mmap))
}
pub fn open_pread<P: AsRef<Path>>(path: P) -> Result<Self> {
let file = File::open(path.as_ref())?;
let len = file.metadata()?.len() as usize;
let source = PreadSource {
file: Arc::new(file),
len,
};
Self::from_byte_source(TxBytes::Pread(source))
}
}