use std::fs::File;
use std::io::{BufReader, Read};
use std::path::Path;
use std::sync::mpsc::{self, Receiver, SyncSender};
use std::thread::{self, JoinHandle};
pub struct ReadAheadReader {
receiver: Receiver<Option<Vec<u8>>>,
current_buf: Vec<u8>,
pos: usize,
_handle: JoinHandle<()>,
}
impl ReadAheadReader {
pub fn open<P: AsRef<Path>>(path: P) -> std::io::Result<Self> {
Self::with_config(path, 4 * 1024 * 1024, 2)
}
pub fn with_config<P: AsRef<Path>>(
path: P,
chunk_size: usize,
queue_depth: usize,
) -> std::io::Result<Self> {
let file = File::open(path.as_ref())?;
Ok(Self::from_file(file, chunk_size, queue_depth))
}
pub fn from_file(mut file: File, chunk_size: usize, queue_depth: usize) -> Self {
let (sender, receiver): (SyncSender<Option<Vec<u8>>>, _) =
mpsc::sync_channel(queue_depth);
let handle = thread::spawn(move || {
loop {
let mut buf = vec![0u8; chunk_size];
match file.read(&mut buf) {
Ok(0) => {
let _ = sender.send(None);
break;
}
Ok(n) => {
buf.truncate(n);
if sender.send(Some(buf)).is_err() {
break;
}
}
Err(_) => {
let _ = sender.send(None);
break;
}
}
}
});
ReadAheadReader {
receiver,
current_buf: Vec::new(),
pos: 0,
_handle: handle,
}
}
fn fill_buffer(&mut self) -> bool {
if self.pos < self.current_buf.len() {
return true;
}
match self.receiver.recv() {
Ok(Some(buf)) => {
self.current_buf = buf;
self.pos = 0;
true
}
_ => false,
}
}
}
impl Read for ReadAheadReader {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if !self.fill_buffer() {
return Ok(0);
}
let available = self.current_buf.len() - self.pos;
let to_copy = buf.len().min(available);
buf[..to_copy].copy_from_slice(&self.current_buf[self.pos..self.pos + to_copy]);
self.pos += to_copy;
Ok(to_copy)
}
}
pub fn open_mrt_file<P: AsRef<Path>>(path: P) -> std::io::Result<BufReader<ReadAheadReader>> {
let reader = ReadAheadReader::open(path)?;
Ok(BufReader::with_capacity(64 * 1024, reader))
}