Skip to content

Commit

Permalink
Add Buffered File
Browse files Browse the repository at this point in the history
  • Loading branch information
tmontaigu committed Oct 12, 2023
1 parent ad311b6 commit 7cf1ec9
Showing 1 changed file with 42 additions and 5 deletions.
47 changes: 42 additions & 5 deletions src/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,46 @@ use crate::{
};
use byteorder::ReadBytesExt;
use std::fmt::{Debug, Formatter};
use std::io::{Cursor, Read, Seek, SeekFrom, Write};
use std::io::{BufReader, BufWriter, Cursor, Read, Seek, SeekFrom, Write};
use std::path::Path;

pub struct BufReadWriteFile {
input: BufReader<std::fs::File>,
output: BufWriter<std::fs::File>,
}

impl BufReadWriteFile {
fn new(file: std::fs::File) -> std::io::Result<Self> {
let input = BufReader::new(file.try_clone()?);
let output = BufWriter::new(file);

Ok(Self { input, output })
}
}

impl Read for BufReadWriteFile {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.input.read(buf)
}
}

impl Write for BufReadWriteFile {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.output.write(buf)
}

fn flush(&mut self) -> std::io::Result<()> {
self.output.flush()
}
}

impl Seek for BufReadWriteFile {
fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
self.output.seek(pos)?;
self.input.seek(pos)
}
}

/// Index to a field in a record
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
pub struct FieldIndex(pub usize);
Expand Down Expand Up @@ -543,22 +580,22 @@ impl<T: Write + Seek> File<T> {
}
}

impl File<std::fs::File> {
impl File<BufReadWriteFile> {
pub fn open_with_options<P: AsRef<Path>>(
path: P,
options: std::fs::OpenOptions,
) -> Result<Self, Error> {
let file = options
.open(path)
.map_err(|error| Error::io_error(error, 0))?;
File::open(file)
File::open(BufReadWriteFile::new(file).unwrap())
}

/// Opens an existing dBase file in read only mode
pub fn open_read_only<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
let file = std::fs::File::open(path).map_err(|error| Error::io_error(error, 0))?;

File::open(file)
File::open(BufReadWriteFile::new(file).unwrap())
}

/// Opens an existing dBase file in write only mode
Expand All @@ -585,6 +622,6 @@ impl File<std::fs::File> {
pub fn create<P: AsRef<Path>>(path: P, table_info: TableInfo) -> Result<Self, Error> {
let file = std::fs::File::create(path).map_err(|error| Error::io_error(error, 0))?;

File::create_new(file, table_info)
File::create_new(BufReadWriteFile::new(file).unwrap(), table_info)
}
}

0 comments on commit 7cf1ec9

Please sign in to comment.