-
Notifications
You must be signed in to change notification settings - Fork 36
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
shadow3aaa
committed
Jun 29, 2024
1 parent
76eee9b
commit eae7d69
Showing
3 changed files
with
82 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
use std::{ | ||
collections::{hash_map::Entry, HashMap}, | ||
fs::File, | ||
io::prelude::*, | ||
path::{Path, PathBuf}, | ||
}; | ||
|
||
use anyhow::Result; | ||
|
||
#[derive(Debug)] | ||
pub struct FileHandler { | ||
files: HashMap<PathBuf, File>, | ||
} | ||
|
||
impl FileHandler { | ||
pub fn new() -> Self { | ||
Self { | ||
files: HashMap::new(), | ||
} | ||
} | ||
|
||
pub fn read_to_string(&mut self, path: impl AsRef<Path>) -> Result<String> { | ||
let mut string = String::new(); | ||
match self.files.entry(path.as_ref().to_path_buf()) { | ||
Entry::Occupied(entry) => { | ||
let mut string = String::new(); | ||
entry.get().read_to_string(&mut string)?; | ||
} | ||
Entry::Vacant(entry) => { | ||
let mut file = File::open(path.as_ref())?; | ||
file.read_to_string(&mut string)?; | ||
entry.insert(file); | ||
} | ||
} | ||
|
||
Ok(string) | ||
} | ||
|
||
pub fn write(&mut self, path: impl AsRef<Path>, content: impl AsRef<[u8]>) -> Result<()> { | ||
match self.files.entry(path.as_ref().to_path_buf()) { | ||
Entry::Occupied(mut entry) => { | ||
entry.get_mut().write_all(content.as_ref())?; | ||
} | ||
Entry::Vacant(entry) => { | ||
let mut file = File::create(path)?; | ||
file.write_all(content.as_ref())?; | ||
entry.insert(file); | ||
} | ||
} | ||
|
||
Ok(()) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters