Skip to main content

rypipe_core/
input.rs

1#![allow(unsafe_code)]
2
3use std::path::Path;
4
5use crate::Result;
6
7/// Owned handle for a memory-mapped file.
8#[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                // Pre-fault the entire file into RSS.
21                let _ = mmap.advise(memmap2::Advice::WillNeed);
22            } else {
23                // Let the kernel drop pages behind the sequential reader.
24                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
35/// Input abstraction: either a memory-mapped file or an owned in-memory buffer.
36pub enum InputBuffer {
37    #[cfg(feature = "mmap")]
38    Mmap(MmapHandle),
39    Owned(Vec<u8>),
40}
41
42impl InputBuffer {
43    /// Open a path as an input buffer.
44    ///
45    /// When `use_mmap` is true and the `"mmap"` feature is enabled, the file
46    /// is mapped.  Otherwise it is read into an owned `Vec<u8>`.
47    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}