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)
}
}
pub fn are_strings(values: &[u8], offsets: &[i32]) -> bool {
fn piece(values: &[u8], offsets: &[i32]) -> bool {
const RUN: usize = 1 << 12;
let mut at = 0;
while at + 1 < offsets.len() {
let run = &offsets[at..(at + RUN + 1).min(offsets.len())];
let (first, last) = (run[0] as usize, run[run.len() - 1] as usize);
let bytes = &values[first..last];
if !bytes.is_ascii() {
let Ok(text) = std::str::from_utf8(bytes) else {
return false;
};
if !run
.iter()
.all(|&o| text.is_char_boundary(o as usize - first))
{
return false;
}
}
at += RUN;
}
true
}
let Some(strings) = offsets.len().checked_sub(1) else {
return false;
};
let threads = threads_for(values.len()).min(strings.max(1));
if threads <= 1 {
return piece(values, offsets);
}
#[cfg(not(target_arch = "wasm32"))]
{
let each = strings.div_ceil(threads);
std::thread::scope(|scope| {
let pieces: Vec<_> = (0..threads)
.map(|t| {
let from = (t * each).min(strings);
let to = ((t + 1) * each).min(strings);
scope.spawn(move || piece(values, &offsets[from..=to]))
})
.collect();
pieces
.into_iter()
.all(|p| p.join().expect("a string check does not panic"))
})
}
#[cfg(target_arch = "wasm32")]
{
piece(values, offsets)
}
}
#[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)
}
#[cfg(test)]
pub fn holds(&self, ptr: *const u8) -> bool {
self.data.as_slice().as_ptr_range().contains(&ptr)
}
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 strings_are_checked_as_arrow_checks_them() {
use datafusion::arrow::array::StringArray;
use datafusion::arrow::buffer::{Buffer, OffsetBuffer, ScalarBuffer};
let agree = |values: &[u8], offsets: &[i32]| {
let arrow = StringArray::try_new(
OffsetBuffer::new(ScalarBuffer::from(offsets.to_vec())),
Buffer::from(values.to_vec()),
None,
)
.is_ok();
assert_eq!(
are_strings(values, offsets),
arrow,
"{values:?} {offsets:?}"
);
arrow
};
assert!(agree(b"", &[0]));
assert!(agree(b"abc", &[0, 1, 1, 3]));
assert!(agree("h\u{e9}llo".as_bytes(), &[0, 3, 6]));
assert!(!agree("h\u{e9}llo".as_bytes(), &[0, 2, 6]));
assert!(!agree(&[b'a', 0xff, b'b'], &[0, 1, 3]));
assert!(!agree(&[0xe2, 0x82], &[0, 2]));
assert!(are_strings(&[b'a', 0xff], &[0, 1]));
let n = 300_000usize;
let mut values = Vec::new();
let mut offsets = vec![0i32];
for i in 0..n {
let id = match i % 5 {
0 => format!("n\u{e9}-{i:0200}"),
_ => format!("did:plc:{i:0300}"),
};
values.extend_from_slice(id.as_bytes());
offsets.push(values.len() as i32);
}
assert!(threads_for(values.len()) > 1 || cfg!(target_arch = "wasm32"));
assert!(are_strings(&values, &offsets));
for at in [
0,
1,
values.len() / 3,
values.len() / 2 + 7,
values.len() - 1,
] {
let mut damaged = values.clone();
damaged[at] = 0xff;
assert!(!are_strings(&damaged, &offsets), "byte {at}");
}
for i in [0, n / 4, n / 2, n - 5] {
let i = i - i % 5;
let mut cut = offsets.clone();
cut[i] += 2;
assert!(!are_strings(&values, &cut), "offset {i}");
}
}
#[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());
}
}