mod vec_writer;
pub use vec_writer::VecWriter;
use crate::Result;
pub trait MdfWrite {
fn write_all(&mut self, bytes: &[u8]) -> Result<()>;
fn seek(&mut self, pos: u64) -> Result<u64>;
fn position(&self) -> u64;
fn flush(&mut self) -> Result<()>;
}
#[cfg(feature = "std")]
mod std_impl {
use super::MdfWrite;
use crate::Result;
use std::fs::File;
use std::io::{BufWriter, Seek, SeekFrom, Write};
pub struct FileWriter {
inner: BufWriter<File>,
position: u64,
}
impl FileWriter {
pub fn new(path: &str) -> Result<Self> {
Self::with_capacity(path, 1_048_576) }
pub fn with_capacity(path: &str, capacity: usize) -> Result<Self> {
let file = File::create(path)?;
let inner = BufWriter::with_capacity(capacity, file);
Ok(Self { inner, position: 0 })
}
}
impl MdfWrite for FileWriter {
fn write_all(&mut self, bytes: &[u8]) -> Result<()> {
self.inner.write_all(bytes)?;
self.position += bytes.len() as u64;
Ok(())
}
fn seek(&mut self, pos: u64) -> Result<u64> {
self.inner.seek(SeekFrom::Start(pos))?;
self.position = pos;
Ok(self.position)
}
fn position(&self) -> u64 {
self.position
}
fn flush(&mut self) -> Result<()> {
self.inner.flush()?;
Ok(())
}
}
}
#[cfg(feature = "std")]
pub use std_impl::FileWriter;