Skip to main content

rw_builder/
file.rs

1use std::{fs::OpenOptions, path::PathBuf};
2
3use crate::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)]
11#[must_use]
12pub struct Builder {
13    /// The path of the file for which readers and writers can be created.
14    path: PathBuf,
15}
16
17impl Builder {
18    /// Factory function to create a builder holding on to a file path
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 =
35            OpenOptions::new().create(true).truncate(true).write(true).open(&self.path)?;
36        Ok(options)
37    }
38}