1#![allow(unsafe_code)]
2
3use std::path::Path;
4
5use crate::Result;
6
7#[cfg(feature = "mmap")]
9pub struct MmapHandle {
10 mmap: memmap2::Mmap,
11}
12
13#[cfg(feature = "mmap")]
14impl MmapHandle {
15 fn new(file: std::fs::File, prefault: bool) -> Result<Self> {
16 let mmap = unsafe { memmap2::Mmap::map(&file)? };
17 #[cfg(unix)]
18 {
19 if prefault {
20 let _ = mmap.advise(memmap2::Advice::WillNeed);
22 } else {
23 let _ = mmap.advise(memmap2::Advice::Sequential);
25 }
26 }
27 Ok(MmapHandle { mmap })
28 }
29
30 fn as_slice(&self) -> &[u8] {
31 &self.mmap[..]
32 }
33}
34
35pub enum InputBuffer {
37 #[cfg(feature = "mmap")]
38 Mmap(MmapHandle),
39 Owned(Vec<u8>),
40}
41
42impl InputBuffer {
43 pub fn open(path: &Path, use_mmap: bool, prefault: bool) -> Result<Self> {
48 #[cfg(feature = "mmap")]
49 {
50 if use_mmap {
51 let file = std::fs::File::open(path)?;
52 return Ok(InputBuffer::Mmap(MmapHandle::new(file, prefault)?));
53 }
54 }
55 let _ = use_mmap;
56 let _ = prefault;
57 let bytes = std::fs::read(path)?;
58 Ok(InputBuffer::Owned(bytes))
59 }
60
61 pub fn as_slice(&self) -> &[u8] {
62 match self {
63 #[cfg(feature = "mmap")]
64 InputBuffer::Mmap(handle) => handle.as_slice(),
65 InputBuffer::Owned(bytes) => bytes,
66 }
67 }
68
69 pub fn len(&self) -> usize {
70 self.as_slice().len()
71 }
72
73 pub fn is_empty(&self) -> bool {
74 self.len() == 0
75 }
76}