use std::ops::Deref;
use std::path::Path;
use crate::error::Result;
pub(crate) enum Segment {
#[cfg(feature = "mmap")]
Mapped(memmap2::Mmap),
Owned(Vec<u8>),
}
impl Deref for Segment {
type Target = [u8];
fn deref(&self) -> &[u8] {
match self {
#[cfg(feature = "mmap")]
Segment::Mapped(map) => map,
Segment::Owned(bytes) => bytes,
}
}
}
impl std::fmt::Debug for Segment {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Segment").field("len", &self.len()).finish()
}
}
pub(crate) fn open(path: &Path) -> Result<Segment> {
#[cfg(feature = "mmap")]
{
let file = std::fs::File::open(path)?;
Ok(Segment::Mapped(unsafe {
memmap2::MmapOptions::new().map(&file)?
}))
}
#[cfg(not(feature = "mmap"))]
{
Ok(Segment::Owned(std::fs::read(path)?))
}
}
pub(crate) fn owned(bytes: Vec<u8>) -> Segment {
Segment::Owned(bytes)
}
pub(crate) fn advise_sequential(segment: &Segment) {
#[cfg(all(feature = "mmap", unix))]
if let Segment::Mapped(map) = segment {
let _ = map.advise(memmap2::Advice::Sequential);
}
#[cfg(not(all(feature = "mmap", unix)))]
let _ = segment;
}
#[cfg(all(feature = "mmap", unix))]
pub(crate) fn advise_normal(segment: &Segment) {
if let Segment::Mapped(map) = segment {
let _ = map.advise(memmap2::Advice::Normal);
}
}
#[cfg(feature = "mmap")]
pub(crate) fn mapped(map: memmap2::Mmap) -> Segment {
Segment::Mapped(map)
}