#![expect(unsafe_code, reason = "mapping a file into memory, and reading its bytes as words")]
use std::marker::PhantomData;
use std::path::Path;
use memmap2::Mmap;
use sha2::{Digest, Sha256};
use crate::cpu::Isa;
use crate::error::{Error, Result};
use crate::kernel;
use crate::scan::TILE;
use crate::search::{Clock, HitList, Memory, Search, Share, Stop, TRIM_RUN};
use crate::snapshot::{self, Fault, Manifest};
use crate::value::Value;
#[derive(Debug)]
pub struct Mapped<V> {
manifest: Manifest,
parts: Vec<Mmap>,
starts: Vec<usize>,
stride: usize,
isa: Isa,
value: PhantomData<V>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verify {
Full,
SizesOnly,
}
impl<V: Value> Mapped<V> {
#[must_use]
pub fn path_for(isa: Isa, ids: bool) -> Isa {
let stride = V::WORDS + usize::from(ids);
kernel::interleaved_path(isa, stride, stride - V::WORDS, V::WORDS)
}
#[must_use]
pub fn path(&self) -> Isa {
kernel::interleaved_path(self.isa, self.stride, self.stride - V::WORDS, V::WORDS)
}
pub unsafe fn open(dir: &Path, verify: Verify) -> Result<Self> {
unsafe { Self::open_with_isa(dir, verify, Isa::best_for::<V>()) }
}
pub unsafe fn open_with_isa(dir: &Path, verify: Verify, isa: Isa) -> Result<Self> {
let isa = isa.require()?;
let manifest = Manifest::read::<V>(dir)?;
if cfg!(target_endian = "big") {
return Err(Fault::BigEndian.at(&dir.join(snapshot::MANIFEST), ""));
}
snapshot::check_parts(dir, &manifest)?;
let mut parts = Vec::with_capacity(manifest.parts.len());
let mut starts = vec![0];
for part in &manifest.parts {
let (path, file) = snapshot::open_part(dir, part)?;
let map = unsafe { Mmap::map(&file) }.map_err(|error| Error::io(&path, error))?;
if verify == Verify::Full {
snapshot::check_sum(&path, &part.sha256, &Sha256::digest(&map[..]))?;
}
parts.push(map);
starts.push(starts.last().copied().unwrap_or(0) + part.records as usize);
}
let stride = snapshot::record_bytes::<V>(manifest.ids) as usize / 8;
let mapped = Self {
manifest,
parts,
starts,
stride,
isa,
value: PhantomData,
};
if verify == Verify::Full && mapped.manifest.ids {
mapped.check_ids(&dir.join(snapshot::MANIFEST))?;
}
Ok(mapped)
}
#[must_use]
pub const fn manifest(&self) -> &Manifest {
&self.manifest
}
fn check_ids(&self, manifest_path: &Path) -> Result<()> {
let (mut first, mut previous): (Option<u64>, Option<u64>) = (None, None);
for part in 0..self.parts.len() {
for &id in self.words(part).iter().step_by(self.stride) {
if let Some(previous) = previous
&& id <= previous
{
return Err(Error::IdOrder { previous, id });
}
first.get_or_insert(id);
previous = Some(id);
}
}
self.manifest.check_ids(manifest_path, first, previous)
}
fn words(&self, part: usize) -> &[u64] {
let bytes: &[u8] = &self.parts[part];
let (head, words, tail) = unsafe { bytes.align_to::<u64>() };
assert!(
head.is_empty() && tail.is_empty(),
"a mapped part is whole aligned words"
);
words
}
fn record(&self, position: usize) -> &[u64] {
let part = self.starts.partition_point(|&start| start <= position) - 1;
let index = position - self.starts[part];
&self.words(part)[index * self.stride..(index + 1) * self.stride]
}
}
impl<V: Value> Search<V> for Mapped<V> {
fn variant(&self) -> String {
format!("mapped/{}", self.path())
}
fn len(&self) -> usize {
self.starts.last().copied().unwrap_or(0)
}
fn has_ids(&self) -> bool {
self.manifest.ids
}
fn id(&self, position: usize) -> Option<u64> {
self.manifest.ids.then(|| self.record(position)[0])
}
fn value(&self, position: usize) -> V {
let record = self.record(position);
let mut words = [0u64; 4];
for (word, &stored) in record[self.stride - V::WORDS..].iter().rev().enumerate() {
words[word] = stored;
}
V::from_words(&words[..V::WORDS])
}
fn memory(&self) -> Memory {
Memory {
mapped: self.parts.iter().map(|map| map.len()).sum(),
..Memory::default()
}
}
fn collect(&self, queries: &[V], radius: u32, share: Share, stop: &Stop, out: &mut [HitList<'_>]) -> bool {
let range = share.range(self.len());
let offset = self.stride - V::WORDS;
let file_order: Vec<Vec<u64>> = queries
.iter()
.map(|query| (0..V::WORDS).rev().map(|word| query.word(word)).collect())
.collect();
let mut clock = Clock::new(stop);
let mut start = range.start;
while start < range.end {
let part = self.starts.partition_point(|&first| first <= start) - 1;
let end = (start + TILE).min(range.end).min(self.starts[part + 1]);
let local = start - self.starts[part]..end - self.starts[part];
let words = &self.words(part)[local.start * self.stride..local.end * self.stride];
for (query, list) in file_order.iter().zip(out.iter_mut()) {
if clock.spend(end - start) {
return true;
}
for (run, words) in words.chunks(TRIM_RUN * self.stride).enumerate() {
list.prepare(words.len() / self.stride);
kernel::scan_interleaved(
self.isa,
words,
self.stride,
offset,
query,
radius,
(start + run * TRIM_RUN) as u32,
&mut list.hits,
);
list.trim();
}
list.candidates += (end - start) as u64;
}
start = end;
}
false
}
}