use std::fs::File;
use std::ops::Range;
use std::sync::Mutex;
use datafusion::arrow::buffer::Buffer;
pub const MAPS: bool = cfg!(all(
unix,
target_endian = "little",
not(target_arch = "wasm32")
));
#[cfg(all(unix, target_endian = "little", not(target_arch = "wasm32")))]
pub fn map(file: &File, len: u64) -> Result<Buffer, String> {
use std::ptr::NonNull;
use std::sync::Arc;
use rustix::mm::{mmap, munmap, MapFlags, ProtFlags};
struct Mapping {
ptr: NonNull<u8>,
len: usize,
}
unsafe impl Send for Mapping {}
unsafe impl Sync for Mapping {}
impl std::panic::RefUnwindSafe for Mapping {}
impl Drop for Mapping {
fn drop(&mut self) {
let _ = unsafe { munmap(self.ptr.as_ptr().cast(), self.len) };
}
}
let len = usize::try_from(len).map_err(|e| e.to_string())?;
if len == 0 {
return Ok(Buffer::from_vec(Vec::<u8>::new()));
}
let ptr = unsafe {
mmap(
std::ptr::null_mut(),
len,
ProtFlags::READ,
MapFlags::SHARED,
file,
0,
)
}
.map_err(|e| format!("cannot map the file: {e}"))?;
let ptr = NonNull::new(ptr.cast::<u8>()).ok_or("cannot map the file")?;
let owner = Arc::new(Mapping { ptr, len });
Ok(unsafe { Buffer::from_custom_allocation(ptr, len, owner) })
}
#[cfg(not(all(unix, target_endian = "little", not(target_arch = "wasm32"))))]
pub fn map(_file: &File, _len: u64) -> Result<Buffer, String> {
Err("index files are not mapped on this platform".into())
}
const PIECE: usize = 32 << 20;
fn threads_for(len: usize) -> usize {
let pieces = len.div_ceil(PIECE).max(1);
#[cfg(not(target_arch = "wasm32"))]
{
let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
cores.min(pieces)
}
#[cfg(target_arch = "wasm32")]
{
pieces.min(1)
}
}
pub fn read_whole(file: &File, len: u64) -> Result<Buffer, String> {
let len = usize::try_from(len).map_err(|e| e.to_string())?;
let mut words = vec![0u64; len.div_ceil(8)];
{
let bytes: &mut [u8] =
unsafe { std::slice::from_raw_parts_mut(words.as_mut_ptr().cast::<u8>(), len) };
read_parallel(file, bytes)?;
}
Ok(Buffer::from_vec(words).slice_with_length(0, len))
}
fn read_parallel(file: &File, bytes: &mut [u8]) -> Result<(), String> {
let threads = threads_for(bytes.len());
if threads <= 1 {
return read_exact_at(file, bytes, 0);
}
#[cfg(not(target_arch = "wasm32"))]
{
let piece = bytes.len().div_ceil(threads);
std::thread::scope(|scope| {
let reads: Vec<_> = bytes
.chunks_mut(piece)
.enumerate()
.map(|(i, part)| scope.spawn(move || read_exact_at(file, part, (i * piece) as u64)))
.collect();
reads
.into_iter()
.try_for_each(|r| r.join().unwrap_or_else(|_| Err("a read failed".into())))
})
}
#[cfg(target_arch = "wasm32")]
{
read_exact_at(file, bytes, 0)
}
}
fn read_exact_at(file: &File, buf: &mut [u8], offset: u64) -> Result<(), String> {
let short = |e: std::io::Error| match e.kind() {
std::io::ErrorKind::UnexpectedEof => "the file is truncated".to_string(),
_ => e.to_string(),
};
#[cfg(unix)]
{
std::os::unix::fs::FileExt::read_exact_at(file, buf, offset).map_err(short)
}
#[cfg(windows)]
{
let (mut buf, mut offset) = (buf, offset);
while !buf.is_empty() {
match std::os::windows::fs::FileExt::seek_read(file, buf, offset) {
Ok(0) => return Err("the file is truncated".into()),
Ok(n) => {
buf = &mut buf[n..];
offset += n as u64;
}
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(e) => return Err(e.to_string()),
}
}
Ok(())
}
#[cfg(not(any(unix, windows)))]
{
use std::io::{Read, Seek, SeekFrom};
let mut file = file;
file.seek(SeekFrom::Start(offset)).map_err(short)?;
file.read_exact(buf).map_err(short)
}
}
pub fn crc(bytes: &[u8]) -> u32 {
let threads = threads_for(bytes.len());
if threads <= 1 {
return crc32fast::hash(bytes);
}
#[cfg(not(target_arch = "wasm32"))]
{
let piece = bytes.len().div_ceil(threads);
let parts: Vec<crc32fast::Hasher> = std::thread::scope(|scope| {
let parts: Vec<_> = bytes
.chunks(piece)
.map(|part| {
scope.spawn(move || {
let mut hasher = crc32fast::Hasher::new();
hasher.update(part);
hasher
})
})
.collect();
parts
.into_iter()
.map(|p| p.join().expect("a CRC thread does not panic"))
.collect()
});
let mut parts = parts.into_iter();
let mut all = parts.next().unwrap_or_default();
for part in parts {
all.combine(&part);
}
all.finalize()
}
#[cfg(target_arch = "wasm32")]
{
crc32fast::hash(bytes)
}
}
#[derive(Debug, Clone)]
pub struct Region {
pub what: &'static str,
pub range: Range<usize>,
pub crc: u32,
}
pub struct Unverified {
data: Buffer,
state: Mutex<Checks>,
}
#[derive(Default)]
struct Checks {
pending: Vec<Region>,
verified: bool,
damage: Option<String>,
on_damage: Option<Box<dyn FnOnce() + Send>>,
}
impl std::fmt::Debug for Unverified {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let state = self.lock();
write!(
f,
"Unverified({} pending, verified: {}, damage: {:?})",
state.pending.len(),
state.verified,
state.damage
)
}
}
impl Unverified {
pub fn new(data: Buffer, regions: Vec<Region>) -> Self {
Self {
data,
state: Mutex::new(Checks {
pending: regions,
..Checks::default()
}),
}
}
fn lock(&self) -> std::sync::MutexGuard<'_, Checks> {
self.state.lock().unwrap_or_else(|e| e.into_inner())
}
pub fn on_damage(&self, f: Box<dyn FnOnce() + Send>) {
self.lock().on_damage = Some(f);
}
pub fn verify(&self) -> Result<(), String> {
let mut state = self.lock();
state.verified = true;
let pending = std::mem::take(&mut state.pending);
for region in &pending {
self.check(&mut state, region)?;
}
state.damage.clone().map_or(Ok(()), Err)
}
pub fn defer(&self, region: Region) -> Result<(), String> {
let mut state = self.lock();
if state.verified {
self.check(&mut state, ®ion)
} else {
state.pending.push(region);
Ok(())
}
}
fn check(&self, state: &mut Checks, region: &Region) -> Result<(), String> {
if let Some(damage) = &state.damage {
return Err(damage.clone());
}
let bytes = self.data.as_slice().get(region.range.clone());
if bytes.is_some_and(|bytes| crc(bytes) == region.crc) {
return Ok(());
}
let damage = format!("the checksum of its {} does not match", region.what);
state.damage = Some(damage.clone());
if let Some(f) = state.on_damage.take() {
f();
}
Err(damage)
}
pub fn is_damaged(&self) -> bool {
self.lock().damage.is_some()
}
pub fn is_verified(&self) -> bool {
let state = self.lock();
state.verified && state.pending.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
#[test]
fn a_parallel_crc_is_the_serial_one() {
let bytes: Vec<u8> = (0..(3 * PIECE + 12345))
.map(|i| (i * 31 % 251) as u8)
.collect();
assert_eq!(crc(&bytes), crc32fast::hash(&bytes));
assert_eq!(crc(&bytes[..10]), crc32fast::hash(&bytes[..10]));
assert_eq!(crc(&[]), crc32fast::hash(&[]));
}
#[test]
fn a_whole_read_is_the_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("x");
let bytes: Vec<u8> = (0..(2 * PIECE + 77)).map(|i| (i % 253) as u8).collect();
std::fs::write(&path, &bytes).unwrap();
let file = File::open(&path).unwrap();
let read = read_whole(&file, bytes.len() as u64).unwrap();
assert_eq!(read.as_slice(), &bytes[..]);
assert_eq!(read.as_ptr() as usize % 8, 0);
assert!(read_whole(&file, bytes.len() as u64 + 1).is_err());
if MAPS {
let mapped = map(&file, bytes.len() as u64).unwrap();
assert_eq!(mapped.as_slice(), &bytes[..]);
}
}
#[test]
fn a_deferred_checksum_is_checked_once_verified() {
let data = Buffer::from_vec(vec![1u8, 2, 3, 4, 5, 6, 7, 8]);
let good = Region {
what: "targets",
range: 0..4,
crc: crc32fast::hash(&[1, 2, 3, 4]),
};
let bad = Region {
what: "in-adjacency",
range: 4..8,
crc: 0,
};
let checks = Unverified::new(data, vec![good.clone()]);
let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false));
let flag = Arc::clone(&dropped);
checks.on_damage(Box::new(move || {
flag.store(true, std::sync::atomic::Ordering::SeqCst)
}));
checks.defer(bad.clone()).unwrap();
assert!(!checks.is_damaged());
let err = checks.verify().unwrap_err();
assert!(err.contains("in-adjacency"), "{err}");
assert!(checks.is_damaged() && dropped.load(std::sync::atomic::Ordering::SeqCst));
assert!(checks.verify().is_err());
let checks = Unverified::new(Buffer::from_vec(vec![1u8, 2, 3, 4, 5, 6, 7, 8]), vec![good]);
checks.verify().unwrap();
assert!(checks.is_verified());
assert!(checks.defer(bad).is_err());
}
}