From 7cf1ec9c0b4549a8ecc55ab9ba9f7d56073a6cf7 Mon Sep 17 00:00:00 2001 From: tmontaigu Date: Thu, 12 Oct 2023 21:04:11 +0200 Subject: [PATCH] Add Buffered File --- src/file.rs | 47 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 42 insertions(+), 5 deletions(-) diff --git a/src/file.rs b/src/file.rs index 6be6194..30444c1 100644 --- a/src/file.rs +++ b/src/file.rs @@ -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, + output: BufWriter, +} + +impl BufReadWriteFile { + fn new(file: std::fs::File) -> std::io::Result { + 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 { + self.input.read(buf) + } +} + +impl Write for BufReadWriteFile { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + 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 { + 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); @@ -543,7 +580,7 @@ impl File { } } -impl File { +impl File { pub fn open_with_options>( path: P, options: std::fs::OpenOptions, @@ -551,14 +588,14 @@ impl File { 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>(path: P) -> Result { 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 @@ -585,6 +622,6 @@ impl File { pub fn create>(path: P, table_info: TableInfo) -> Result { 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) } }