use std::fs::File;
use std::path::Path;
use memmap2::{Mmap, MmapOptions};
use crate::demo::{Demo, DemoIndex};
use crate::error::Result;
use crate::limits::DecodeLimits;
use crate::playback::DemoParser;
#[derive(Debug)]
pub struct MappedDemo {
mapping: Mmap,
limits: DecodeLimits,
}
impl MappedDemo {
pub unsafe fn open(path: impl AsRef<Path>) -> Result<Self> {
unsafe { Self::open_with_limits(path, DecodeLimits::default()) }
}
pub unsafe fn open_with_limits(path: impl AsRef<Path>, limits: DecodeLimits) -> Result<Self> {
let file = File::open(path)?;
let mapping = unsafe { MmapOptions::new().map(&file)? };
Self::from_mmap_with_limits(mapping, limits)
}
pub fn from_mmap(mapping: Mmap) -> Result<Self> {
Self::from_mmap_with_limits(mapping, DecodeLimits::default())
}
pub fn from_mmap_with_limits(mapping: Mmap, limits: DecodeLimits) -> Result<Self> {
Demo::with_limits(&mapping, limits)?;
Ok(Self { mapping, limits })
}
pub fn as_bytes(&self) -> &[u8] {
&self.mapping
}
pub fn len(&self) -> usize {
self.mapping.len()
}
pub fn is_empty(&self) -> bool {
self.mapping.is_empty()
}
pub const fn limits(&self) -> DecodeLimits {
self.limits
}
pub fn demo(&self) -> Result<Demo<'_>> {
Demo::with_limits(&self.mapping, self.limits)
}
pub fn parser(&self) -> Result<DemoParser<'_>> {
DemoParser::with_limits(&self.mapping, self.limits)
}
pub fn index(&self) -> Result<DemoIndex> {
self.demo()?.index()
}
}
impl AsRef<[u8]> for MappedDemo {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
#[cfg(test)]
mod tests {
use std::io::Write;
use tempfile::NamedTempFile;
use super::*;
use crate::demo::{HEADER_SIZE, MAGIC, command};
fn fixture() -> Vec<u8> {
let mut bytes = Vec::from(MAGIC);
bytes.resize(HEADER_SIZE, 0);
bytes.extend_from_slice(&[command::SYNC_TICK as u8, 0, 0]);
bytes.extend_from_slice(&[command::PACKET as u8, 1, 0]);
bytes
}
#[test]
fn opens_and_indexes_a_file_without_copying_it() {
let bytes = fixture();
let mut file = NamedTempFile::new().expect("temporary file");
file.write_all(&bytes).expect("write fixture");
file.flush().expect("flush fixture");
let mapped = unsafe { MappedDemo::open(file.path()) }.expect("valid mapping");
assert_eq!(mapped.as_bytes(), bytes);
assert_eq!(mapped.len(), bytes.len());
assert_eq!(mapped.demo().expect("borrowed demo").data(), bytes);
assert_eq!(
mapped.parser().expect("borrowed parser").demo().data(),
bytes
);
assert_eq!(mapped.index().expect("valid index").distinct_ticks(), [1]);
}
#[test]
fn rejects_a_mapped_non_demo_file() {
let mut file = NamedTempFile::new().expect("temporary file");
file.write_all(b"not a source 2 demo")
.expect("write fixture");
file.flush().expect("flush fixture");
let result = unsafe { MappedDemo::open(file.path()) };
assert!(result.is_err());
}
}