1use std::fs::File;
79use std::ops::Range;
80use std::sync::Mutex;
81
82use datafusion::arrow::buffer::Buffer;
83
84pub const MAPS: bool = cfg!(all(
87 unix,
88 target_endian = "little",
89 not(target_arch = "wasm32")
90));
91
92#[cfg(all(unix, target_endian = "little", not(target_arch = "wasm32")))]
95pub fn map(file: &File, len: u64) -> Result<Buffer, String> {
96 use std::ptr::NonNull;
97 use std::sync::Arc;
98
99 use rustix::mm::{mmap, munmap, MapFlags, ProtFlags};
100
101 struct Mapping {
103 ptr: NonNull<u8>,
104 len: usize,
105 }
106 unsafe impl Send for Mapping {}
109 unsafe impl Sync for Mapping {}
110 impl std::panic::RefUnwindSafe for Mapping {}
111 impl Drop for Mapping {
112 fn drop(&mut self) {
113 let _ = unsafe { munmap(self.ptr.as_ptr().cast(), self.len) };
116 }
117 }
118
119 let len = usize::try_from(len).map_err(|e| e.to_string())?;
120 if len == 0 {
121 return Ok(Buffer::from_vec(Vec::<u8>::new()));
122 }
123 let ptr = unsafe {
126 mmap(
127 std::ptr::null_mut(),
128 len,
129 ProtFlags::READ,
130 MapFlags::SHARED,
131 file,
132 0,
133 )
134 }
135 .map_err(|e| format!("cannot map the file: {e}"))?;
136 let ptr = NonNull::new(ptr.cast::<u8>()).ok_or("cannot map the file")?;
137 let owner = Arc::new(Mapping { ptr, len });
138 Ok(unsafe { Buffer::from_custom_allocation(ptr, len, owner) })
141}
142
143#[cfg(not(all(unix, target_endian = "little", not(target_arch = "wasm32"))))]
145pub fn map(_file: &File, _len: u64) -> Result<Buffer, String> {
146 Err("index files are not mapped on this platform".into())
147}
148
149const PIECE: usize = 32 << 20;
151
152fn threads_for(len: usize) -> usize {
154 let pieces = len.div_ceil(PIECE).max(1);
155 #[cfg(not(target_arch = "wasm32"))]
156 {
157 let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
158 cores.min(pieces)
159 }
160 #[cfg(target_arch = "wasm32")]
162 {
163 pieces.min(1)
164 }
165}
166
167pub fn read_whole(file: &File, len: u64) -> Result<Buffer, String> {
170 let len = usize::try_from(len).map_err(|e| e.to_string())?;
171 let mut words = vec![0u64; len.div_ceil(8)];
172 {
173 let bytes: &mut [u8] =
176 unsafe { std::slice::from_raw_parts_mut(words.as_mut_ptr().cast::<u8>(), len) };
177 read_parallel(file, bytes)?;
178 }
179 Ok(Buffer::from_vec(words).slice_with_length(0, len))
180}
181
182fn read_parallel(file: &File, bytes: &mut [u8]) -> Result<(), String> {
184 let threads = threads_for(bytes.len());
185 if threads <= 1 {
186 return read_exact_at(file, bytes, 0);
187 }
188 #[cfg(not(target_arch = "wasm32"))]
189 {
190 let piece = bytes.len().div_ceil(threads);
191 std::thread::scope(|scope| {
192 let reads: Vec<_> = bytes
193 .chunks_mut(piece)
194 .enumerate()
195 .map(|(i, part)| scope.spawn(move || read_exact_at(file, part, (i * piece) as u64)))
196 .collect();
197 reads
198 .into_iter()
199 .try_for_each(|r| r.join().unwrap_or_else(|_| Err("a read failed".into())))
200 })
201 }
202 #[cfg(target_arch = "wasm32")]
203 {
204 read_exact_at(file, bytes, 0)
205 }
206}
207
208fn read_exact_at(file: &File, buf: &mut [u8], offset: u64) -> Result<(), String> {
210 let short = |e: std::io::Error| match e.kind() {
211 std::io::ErrorKind::UnexpectedEof => "the file is truncated".to_string(),
212 _ => e.to_string(),
213 };
214 #[cfg(unix)]
215 {
216 std::os::unix::fs::FileExt::read_exact_at(file, buf, offset).map_err(short)
217 }
218 #[cfg(windows)]
219 {
220 let (mut buf, mut offset) = (buf, offset);
221 while !buf.is_empty() {
222 match std::os::windows::fs::FileExt::seek_read(file, buf, offset) {
223 Ok(0) => return Err("the file is truncated".into()),
224 Ok(n) => {
225 buf = &mut buf[n..];
226 offset += n as u64;
227 }
228 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
229 Err(e) => return Err(e.to_string()),
230 }
231 }
232 Ok(())
233 }
234 #[cfg(not(any(unix, windows)))]
235 {
236 use std::io::{Read, Seek, SeekFrom};
237 let mut file = file;
238 file.seek(SeekFrom::Start(offset)).map_err(short)?;
239 file.read_exact(buf).map_err(short)
240 }
241}
242
243pub fn crc(bytes: &[u8]) -> u32 {
246 let threads = threads_for(bytes.len());
247 if threads <= 1 {
248 return crc32fast::hash(bytes);
249 }
250 #[cfg(not(target_arch = "wasm32"))]
251 {
252 let piece = bytes.len().div_ceil(threads);
253 let parts: Vec<crc32fast::Hasher> = std::thread::scope(|scope| {
254 let parts: Vec<_> = bytes
255 .chunks(piece)
256 .map(|part| {
257 scope.spawn(move || {
258 let mut hasher = crc32fast::Hasher::new();
259 hasher.update(part);
260 hasher
261 })
262 })
263 .collect();
264 parts
265 .into_iter()
266 .map(|p| p.join().expect("a CRC thread does not panic"))
267 .collect()
268 });
269 let mut parts = parts.into_iter();
270 let mut all = parts.next().unwrap_or_default();
271 for part in parts {
272 all.combine(&part);
273 }
274 all.finalize()
275 }
276 #[cfg(target_arch = "wasm32")]
277 {
278 crc32fast::hash(bytes)
279 }
280}
281
282pub fn are_strings(values: &[u8], offsets: &[i32]) -> bool {
291 fn piece(values: &[u8], offsets: &[i32]) -> bool {
293 const RUN: usize = 1 << 12;
294 let mut at = 0;
297 while at + 1 < offsets.len() {
298 let run = &offsets[at..(at + RUN + 1).min(offsets.len())];
299 let (first, last) = (run[0] as usize, run[run.len() - 1] as usize);
300 let bytes = &values[first..last];
301 if !bytes.is_ascii() {
304 let Ok(text) = std::str::from_utf8(bytes) else {
305 return false;
306 };
307 if !run
308 .iter()
309 .all(|&o| text.is_char_boundary(o as usize - first))
310 {
311 return false;
312 }
313 }
314 at += RUN;
315 }
316 true
317 }
318 let Some(strings) = offsets.len().checked_sub(1) else {
319 return false;
320 };
321 let threads = threads_for(values.len()).min(strings.max(1));
322 if threads <= 1 {
323 return piece(values, offsets);
324 }
325 #[cfg(not(target_arch = "wasm32"))]
326 {
327 let each = strings.div_ceil(threads);
328 std::thread::scope(|scope| {
329 let pieces: Vec<_> = (0..threads)
330 .map(|t| {
331 let from = (t * each).min(strings);
332 let to = ((t + 1) * each).min(strings);
333 scope.spawn(move || piece(values, &offsets[from..=to]))
334 })
335 .collect();
336 pieces
338 .into_iter()
339 .all(|p| p.join().expect("a string check does not panic"))
340 })
341 }
342 #[cfg(target_arch = "wasm32")]
343 {
344 piece(values, offsets)
345 }
346}
347
348#[derive(Debug, Clone)]
350pub struct Region {
351 pub what: &'static str,
353 pub range: Range<usize>,
354 pub crc: u32,
355}
356
357pub struct Unverified {
360 data: Buffer,
361 state: Mutex<Checks>,
362}
363
364#[derive(Default)]
365struct Checks {
366 pending: Vec<Region>,
367 verified: bool,
370 damage: Option<String>,
372 on_damage: Option<Box<dyn FnOnce() + Send>>,
374}
375
376impl std::fmt::Debug for Unverified {
377 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
378 let state = self.lock();
379 write!(
380 f,
381 "Unverified({} pending, verified: {}, damage: {:?})",
382 state.pending.len(),
383 state.verified,
384 state.damage
385 )
386 }
387}
388
389impl Unverified {
390 pub fn new(data: Buffer, regions: Vec<Region>) -> Self {
392 Self {
393 data,
394 state: Mutex::new(Checks {
395 pending: regions,
396 ..Checks::default()
397 }),
398 }
399 }
400
401 fn lock(&self) -> std::sync::MutexGuard<'_, Checks> {
402 self.state.lock().unwrap_or_else(|e| e.into_inner())
403 }
404
405 pub fn on_damage(&self, f: Box<dyn FnOnce() + Send>) {
407 self.lock().on_damage = Some(f);
408 }
409
410 pub fn verify(&self) -> Result<(), String> {
413 let mut state = self.lock();
414 state.verified = true;
415 let pending = std::mem::take(&mut state.pending);
416 for region in &pending {
417 self.check(&mut state, region)?;
418 }
419 state.damage.clone().map_or(Ok(()), Err)
420 }
421
422 pub fn defer(&self, region: Region) -> Result<(), String> {
425 let mut state = self.lock();
426 if state.verified {
427 self.check(&mut state, ®ion)
428 } else {
429 state.pending.push(region);
430 Ok(())
431 }
432 }
433
434 fn check(&self, state: &mut Checks, region: &Region) -> Result<(), String> {
435 if let Some(damage) = &state.damage {
436 return Err(damage.clone());
437 }
438 let bytes = self.data.as_slice().get(region.range.clone());
439 if bytes.is_some_and(|bytes| crc(bytes) == region.crc) {
440 return Ok(());
441 }
442 let damage = format!("the checksum of its {} does not match", region.what);
443 state.damage = Some(damage.clone());
444 if let Some(f) = state.on_damage.take() {
445 f();
446 }
447 Err(damage)
448 }
449
450 #[cfg(test)]
453 pub fn holds(&self, ptr: *const u8) -> bool {
454 self.data.as_slice().as_ptr_range().contains(&ptr)
455 }
456
457 pub fn is_damaged(&self) -> bool {
459 self.lock().damage.is_some()
460 }
461
462 pub fn is_verified(&self) -> bool {
464 let state = self.lock();
465 state.verified && state.pending.is_empty()
466 }
467}
468
469#[cfg(test)]
470mod tests {
471 use super::*;
472 use std::sync::Arc;
473
474 #[test]
475 fn strings_are_checked_as_arrow_checks_them() {
476 use datafusion::arrow::array::StringArray;
477 use datafusion::arrow::buffer::{Buffer, OffsetBuffer, ScalarBuffer};
478 let agree = |values: &[u8], offsets: &[i32]| {
480 let arrow = StringArray::try_new(
481 OffsetBuffer::new(ScalarBuffer::from(offsets.to_vec())),
482 Buffer::from(values.to_vec()),
483 None,
484 )
485 .is_ok();
486 assert_eq!(
487 are_strings(values, offsets),
488 arrow,
489 "{values:?} {offsets:?}"
490 );
491 arrow
492 };
493 assert!(agree(b"", &[0]));
494 assert!(agree(b"abc", &[0, 1, 1, 3]));
495 assert!(agree("h\u{e9}llo".as_bytes(), &[0, 3, 6]));
496 assert!(!agree("h\u{e9}llo".as_bytes(), &[0, 2, 6]));
498 assert!(!agree(&[b'a', 0xff, b'b'], &[0, 1, 3]));
499 assert!(!agree(&[0xe2, 0x82], &[0, 2]));
500 assert!(are_strings(&[b'a', 0xff], &[0, 1]));
502
503 let n = 300_000usize;
506 let mut values = Vec::new();
507 let mut offsets = vec![0i32];
508 for i in 0..n {
509 let id = match i % 5 {
510 0 => format!("n\u{e9}-{i:0200}"),
511 _ => format!("did:plc:{i:0300}"),
512 };
513 values.extend_from_slice(id.as_bytes());
514 offsets.push(values.len() as i32);
515 }
516 assert!(threads_for(values.len()) > 1 || cfg!(target_arch = "wasm32"));
517 assert!(are_strings(&values, &offsets));
518 for at in [
519 0,
520 1,
521 values.len() / 3,
522 values.len() / 2 + 7,
523 values.len() - 1,
524 ] {
525 let mut damaged = values.clone();
526 damaged[at] = 0xff;
527 assert!(!are_strings(&damaged, &offsets), "byte {at}");
528 }
529 for i in [0, n / 4, n / 2, n - 5] {
530 let i = i - i % 5;
533 let mut cut = offsets.clone();
534 cut[i] += 2;
535 assert!(!are_strings(&values, &cut), "offset {i}");
536 }
537 }
538
539 #[test]
540 fn a_parallel_crc_is_the_serial_one() {
541 let bytes: Vec<u8> = (0..(3 * PIECE + 12345))
542 .map(|i| (i * 31 % 251) as u8)
543 .collect();
544 assert_eq!(crc(&bytes), crc32fast::hash(&bytes));
545 assert_eq!(crc(&bytes[..10]), crc32fast::hash(&bytes[..10]));
546 assert_eq!(crc(&[]), crc32fast::hash(&[]));
547 }
548
549 #[test]
550 fn a_whole_read_is_the_file() {
551 let dir = tempfile::tempdir().unwrap();
552 let path = dir.path().join("x");
553 let bytes: Vec<u8> = (0..(2 * PIECE + 77)).map(|i| (i % 253) as u8).collect();
554 std::fs::write(&path, &bytes).unwrap();
555 let file = File::open(&path).unwrap();
556 let read = read_whole(&file, bytes.len() as u64).unwrap();
557 assert_eq!(read.as_slice(), &bytes[..]);
558 assert_eq!(read.as_ptr() as usize % 8, 0);
559 assert!(read_whole(&file, bytes.len() as u64 + 1).is_err());
560 if MAPS {
561 let mapped = map(&file, bytes.len() as u64).unwrap();
562 assert_eq!(mapped.as_slice(), &bytes[..]);
563 }
564 }
565
566 #[test]
567 fn a_deferred_checksum_is_checked_once_verified() {
568 let data = Buffer::from_vec(vec![1u8, 2, 3, 4, 5, 6, 7, 8]);
569 let good = Region {
570 what: "targets",
571 range: 0..4,
572 crc: crc32fast::hash(&[1, 2, 3, 4]),
573 };
574 let bad = Region {
575 what: "in-adjacency",
576 range: 4..8,
577 crc: 0,
578 };
579 let checks = Unverified::new(data, vec![good.clone()]);
580 let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false));
581 let flag = Arc::clone(&dropped);
582 checks.on_damage(Box::new(move || {
583 flag.store(true, std::sync::atomic::Ordering::SeqCst)
584 }));
585 checks.defer(bad.clone()).unwrap();
587 assert!(!checks.is_damaged());
588 let err = checks.verify().unwrap_err();
589 assert!(err.contains("in-adjacency"), "{err}");
590 assert!(checks.is_damaged() && dropped.load(std::sync::atomic::Ordering::SeqCst));
591 assert!(checks.verify().is_err());
592
593 let checks = Unverified::new(Buffer::from_vec(vec![1u8, 2, 3, 4, 5, 6, 7, 8]), vec![good]);
594 checks.verify().unwrap();
595 assert!(checks.is_verified());
596 assert!(checks.defer(bad).is_err());
598 }
599}