rw_builder/
file.rs

1use std::{fs::OpenOptions, path::PathBuf};
2
3use anyhow::Result;
4
5use crate::RwBuilder;
6
7/// Type for building readers and writers on top of a file handle.
8/// It is itself an `RwBuilder`, but can't be created through one.
9/// This is why we call it a source.
10#[derive(Debug)]
11pub struct Builder {
12    /// The path of the file for which readers and writers can be created.
13    path: PathBuf,
14}
15
16impl Builder {
17    /// Factory function to create a builder holding on to a file path
18    #[must_use]
19    pub const fn new(path: PathBuf) -> Self {
20        Self { path }
21    }
22}
23
24impl RwBuilder for Builder {
25    type Reader = std::fs::File;
26    type Writer = std::fs::File;
27
28    fn reader(&self) -> Result<Self::Reader> {
29        let options = OpenOptions::new().read(true).open(&self.path)?;
30        Ok(options)
31    }
32
33    fn writer(&self) -> Result<Self::Writer> {
34        let options = OpenOptions::new().create(true).write(true).open(&self.path)?;
35        Ok(options)
36    }
37}