1use std::fs::File;
74use std::ops::Range;
75use std::sync::Mutex;
76
77use datafusion::arrow::buffer::Buffer;
78
79pub const MAPS: bool = cfg!(all(
82 unix,
83 target_endian = "little",
84 not(target_arch = "wasm32")
85));
86
87#[cfg(all(unix, target_endian = "little", not(target_arch = "wasm32")))]
90pub fn map(file: &File, len: u64) -> Result<Buffer, String> {
91 use std::ptr::NonNull;
92 use std::sync::Arc;
93
94 use rustix::mm::{mmap, munmap, MapFlags, ProtFlags};
95
96 struct Mapping {
98 ptr: NonNull<u8>,
99 len: usize,
100 }
101 unsafe impl Send for Mapping {}
104 unsafe impl Sync for Mapping {}
105 impl std::panic::RefUnwindSafe for Mapping {}
106 impl Drop for Mapping {
107 fn drop(&mut self) {
108 let _ = unsafe { munmap(self.ptr.as_ptr().cast(), self.len) };
111 }
112 }
113
114 let len = usize::try_from(len).map_err(|e| e.to_string())?;
115 if len == 0 {
116 return Ok(Buffer::from_vec(Vec::<u8>::new()));
117 }
118 let ptr = unsafe {
121 mmap(
122 std::ptr::null_mut(),
123 len,
124 ProtFlags::READ,
125 MapFlags::SHARED,
126 file,
127 0,
128 )
129 }
130 .map_err(|e| format!("cannot map the file: {e}"))?;
131 let ptr = NonNull::new(ptr.cast::<u8>()).ok_or("cannot map the file")?;
132 let owner = Arc::new(Mapping { ptr, len });
133 Ok(unsafe { Buffer::from_custom_allocation(ptr, len, owner) })
136}
137
138#[cfg(not(all(unix, target_endian = "little", not(target_arch = "wasm32"))))]
140pub fn map(_file: &File, _len: u64) -> Result<Buffer, String> {
141 Err("index files are not mapped on this platform".into())
142}
143
144const PIECE: usize = 32 << 20;
146
147fn threads_for(len: usize) -> usize {
149 let pieces = len.div_ceil(PIECE).max(1);
150 #[cfg(not(target_arch = "wasm32"))]
151 {
152 let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
153 cores.min(pieces)
154 }
155 #[cfg(target_arch = "wasm32")]
157 {
158 pieces.min(1)
159 }
160}
161
162pub fn read_whole(file: &File, len: u64) -> Result<Buffer, String> {
165 let len = usize::try_from(len).map_err(|e| e.to_string())?;
166 let mut words = vec![0u64; len.div_ceil(8)];
167 {
168 let bytes: &mut [u8] =
171 unsafe { std::slice::from_raw_parts_mut(words.as_mut_ptr().cast::<u8>(), len) };
172 read_parallel(file, bytes)?;
173 }
174 Ok(Buffer::from_vec(words).slice_with_length(0, len))
175}
176
177fn read_parallel(file: &File, bytes: &mut [u8]) -> Result<(), String> {
179 let threads = threads_for(bytes.len());
180 if threads <= 1 {
181 return read_exact_at(file, bytes, 0);
182 }
183 #[cfg(not(target_arch = "wasm32"))]
184 {
185 let piece = bytes.len().div_ceil(threads);
186 std::thread::scope(|scope| {
187 let reads: Vec<_> = bytes
188 .chunks_mut(piece)
189 .enumerate()
190 .map(|(i, part)| scope.spawn(move || read_exact_at(file, part, (i * piece) as u64)))
191 .collect();
192 reads
193 .into_iter()
194 .try_for_each(|r| r.join().unwrap_or_else(|_| Err("a read failed".into())))
195 })
196 }
197 #[cfg(target_arch = "wasm32")]
198 {
199 read_exact_at(file, bytes, 0)
200 }
201}
202
203fn read_exact_at(file: &File, buf: &mut [u8], offset: u64) -> Result<(), String> {
205 let short = |e: std::io::Error| match e.kind() {
206 std::io::ErrorKind::UnexpectedEof => "the file is truncated".to_string(),
207 _ => e.to_string(),
208 };
209 #[cfg(unix)]
210 {
211 std::os::unix::fs::FileExt::read_exact_at(file, buf, offset).map_err(short)
212 }
213 #[cfg(windows)]
214 {
215 let (mut buf, mut offset) = (buf, offset);
216 while !buf.is_empty() {
217 match std::os::windows::fs::FileExt::seek_read(file, buf, offset) {
218 Ok(0) => return Err("the file is truncated".into()),
219 Ok(n) => {
220 buf = &mut buf[n..];
221 offset += n as u64;
222 }
223 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
224 Err(e) => return Err(e.to_string()),
225 }
226 }
227 Ok(())
228 }
229 #[cfg(not(any(unix, windows)))]
230 {
231 use std::io::{Read, Seek, SeekFrom};
232 let mut file = file;
233 file.seek(SeekFrom::Start(offset)).map_err(short)?;
234 file.read_exact(buf).map_err(short)
235 }
236}
237
238pub fn crc(bytes: &[u8]) -> u32 {
241 let threads = threads_for(bytes.len());
242 if threads <= 1 {
243 return crc32fast::hash(bytes);
244 }
245 #[cfg(not(target_arch = "wasm32"))]
246 {
247 let piece = bytes.len().div_ceil(threads);
248 let parts: Vec<crc32fast::Hasher> = std::thread::scope(|scope| {
249 let parts: Vec<_> = bytes
250 .chunks(piece)
251 .map(|part| {
252 scope.spawn(move || {
253 let mut hasher = crc32fast::Hasher::new();
254 hasher.update(part);
255 hasher
256 })
257 })
258 .collect();
259 parts
260 .into_iter()
261 .map(|p| p.join().expect("a CRC thread does not panic"))
262 .collect()
263 });
264 let mut parts = parts.into_iter();
265 let mut all = parts.next().unwrap_or_default();
266 for part in parts {
267 all.combine(&part);
268 }
269 all.finalize()
270 }
271 #[cfg(target_arch = "wasm32")]
272 {
273 crc32fast::hash(bytes)
274 }
275}
276
277#[derive(Debug, Clone)]
279pub struct Region {
280 pub what: &'static str,
282 pub range: Range<usize>,
283 pub crc: u32,
284}
285
286pub struct Unverified {
289 data: Buffer,
290 state: Mutex<Checks>,
291}
292
293#[derive(Default)]
294struct Checks {
295 pending: Vec<Region>,
296 verified: bool,
299 damage: Option<String>,
301 on_damage: Option<Box<dyn FnOnce() + Send>>,
303}
304
305impl std::fmt::Debug for Unverified {
306 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
307 let state = self.lock();
308 write!(
309 f,
310 "Unverified({} pending, verified: {}, damage: {:?})",
311 state.pending.len(),
312 state.verified,
313 state.damage
314 )
315 }
316}
317
318impl Unverified {
319 pub fn new(data: Buffer, regions: Vec<Region>) -> Self {
321 Self {
322 data,
323 state: Mutex::new(Checks {
324 pending: regions,
325 ..Checks::default()
326 }),
327 }
328 }
329
330 fn lock(&self) -> std::sync::MutexGuard<'_, Checks> {
331 self.state.lock().unwrap_or_else(|e| e.into_inner())
332 }
333
334 pub fn on_damage(&self, f: Box<dyn FnOnce() + Send>) {
336 self.lock().on_damage = Some(f);
337 }
338
339 pub fn verify(&self) -> Result<(), String> {
342 let mut state = self.lock();
343 state.verified = true;
344 let pending = std::mem::take(&mut state.pending);
345 for region in &pending {
346 self.check(&mut state, region)?;
347 }
348 state.damage.clone().map_or(Ok(()), Err)
349 }
350
351 pub fn defer(&self, region: Region) -> Result<(), String> {
354 let mut state = self.lock();
355 if state.verified {
356 self.check(&mut state, ®ion)
357 } else {
358 state.pending.push(region);
359 Ok(())
360 }
361 }
362
363 fn check(&self, state: &mut Checks, region: &Region) -> Result<(), String> {
364 if let Some(damage) = &state.damage {
365 return Err(damage.clone());
366 }
367 let bytes = self.data.as_slice().get(region.range.clone());
368 if bytes.is_some_and(|bytes| crc(bytes) == region.crc) {
369 return Ok(());
370 }
371 let damage = format!("the checksum of its {} does not match", region.what);
372 state.damage = Some(damage.clone());
373 if let Some(f) = state.on_damage.take() {
374 f();
375 }
376 Err(damage)
377 }
378
379 pub fn is_damaged(&self) -> bool {
381 self.lock().damage.is_some()
382 }
383
384 pub fn is_verified(&self) -> bool {
386 let state = self.lock();
387 state.verified && state.pending.is_empty()
388 }
389}
390
391#[cfg(test)]
392mod tests {
393 use super::*;
394 use std::sync::Arc;
395
396 #[test]
397 fn a_parallel_crc_is_the_serial_one() {
398 let bytes: Vec<u8> = (0..(3 * PIECE + 12345))
399 .map(|i| (i * 31 % 251) as u8)
400 .collect();
401 assert_eq!(crc(&bytes), crc32fast::hash(&bytes));
402 assert_eq!(crc(&bytes[..10]), crc32fast::hash(&bytes[..10]));
403 assert_eq!(crc(&[]), crc32fast::hash(&[]));
404 }
405
406 #[test]
407 fn a_whole_read_is_the_file() {
408 let dir = tempfile::tempdir().unwrap();
409 let path = dir.path().join("x");
410 let bytes: Vec<u8> = (0..(2 * PIECE + 77)).map(|i| (i % 253) as u8).collect();
411 std::fs::write(&path, &bytes).unwrap();
412 let file = File::open(&path).unwrap();
413 let read = read_whole(&file, bytes.len() as u64).unwrap();
414 assert_eq!(read.as_slice(), &bytes[..]);
415 assert_eq!(read.as_ptr() as usize % 8, 0);
416 assert!(read_whole(&file, bytes.len() as u64 + 1).is_err());
417 if MAPS {
418 let mapped = map(&file, bytes.len() as u64).unwrap();
419 assert_eq!(mapped.as_slice(), &bytes[..]);
420 }
421 }
422
423 #[test]
424 fn a_deferred_checksum_is_checked_once_verified() {
425 let data = Buffer::from_vec(vec![1u8, 2, 3, 4, 5, 6, 7, 8]);
426 let good = Region {
427 what: "targets",
428 range: 0..4,
429 crc: crc32fast::hash(&[1, 2, 3, 4]),
430 };
431 let bad = Region {
432 what: "in-adjacency",
433 range: 4..8,
434 crc: 0,
435 };
436 let checks = Unverified::new(data, vec![good.clone()]);
437 let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false));
438 let flag = Arc::clone(&dropped);
439 checks.on_damage(Box::new(move || {
440 flag.store(true, std::sync::atomic::Ordering::SeqCst)
441 }));
442 checks.defer(bad.clone()).unwrap();
444 assert!(!checks.is_damaged());
445 let err = checks.verify().unwrap_err();
446 assert!(err.contains("in-adjacency"), "{err}");
447 assert!(checks.is_damaged() && dropped.load(std::sync::atomic::Ordering::SeqCst));
448 assert!(checks.verify().is_err());
449
450 let checks = Unverified::new(Buffer::from_vec(vec![1u8, 2, 3, 4, 5, 6, 7, 8]), vec![good]);
451 checks.verify().unwrap();
452 assert!(checks.is_verified());
453 assert!(checks.defer(bad).is_err());
455 }
456}