file_lock/
file_options.rs

1use std::fs::{File, OpenOptions};
2use std::path::Path;
3
4/// A wrapper around the open options type
5/// that can be queried for the write permissions
6///
7/// This type has the exact same API as [`std::fs::OpenOptions`]
8/// with the exception that the confluent interface passes `self`
9/// rather than `&mut self`.
10pub struct FileOptions {
11    open_options: OpenOptions,
12    pub(crate) writeable: bool,
13}
14
15impl FileOptions {
16    pub fn new() -> Self {
17        Self {
18            open_options: OpenOptions::new(),
19            writeable: false,
20        }
21    }
22
23    pub fn append(mut self, append: bool) -> Self {
24        self.open_options.append(append);
25        self.writeable = true;
26        self
27    }
28
29    pub fn create(mut self, create: bool) -> Self {
30        self.open_options.create(create);
31        self
32    }
33
34    pub fn create_new(mut self, create_new: bool) -> Self {
35        self.open_options.create_new(create_new);
36        self
37    }
38
39    pub fn open<P: AsRef<Path>>(&self, path: P) -> std::io::Result<File> {
40        self.open_options.open(path)
41    }
42
43    pub fn read(mut self, read: bool) -> Self {
44        self.open_options.read(read);
45        self
46    }
47
48    pub fn truncate(mut self, truncate: bool) -> Self {
49        self.open_options.truncate(truncate);
50        self
51    }
52
53    pub fn write(mut self, write: bool) -> Self {
54        self.open_options.write(write);
55        self.writeable = write;
56        self
57    }
58}
59
60impl Default for FileOptions {
61    fn default() -> Self {
62        Self::new()
63    }
64}