maybe_fut/api/fs/open_options.rs
1#[derive(Clone, Debug, Unwrap)]
2#[unwrap_types(
3 std(std::fs::OpenOptions),
4 tokio(tokio::fs::OpenOptions),
5 tokio_gated("tokio-fs")
6)]
7/// Options and flags which can be used to configure how a file is opened.
8/// This builder exposes the ability to configure how a File is opened and what operations are permitted on the open file. The File::open and File::create methods are aliases for commonly used options using this builder.
9///
10/// Generally speaking, when using OpenOptions, you’ll first call new, then chain calls to methods to set each option, then call open, passing the path of the file you’re trying to open. This will give you a io::Result with a File inside that you can further operate on.
11pub struct OpenOptions(OpenOptionsInner);
12
13impl Default for OpenOptions {
14 fn default() -> Self {
15 Self::new()
16 }
17}
18
19/// Inner pointer to sync or async file.
20#[derive(Debug, Clone)]
21enum OpenOptionsInner {
22 /// Std variant of file <https://docs.rs/rustc-std-workspace-std/latest/std/fs/struct.OpenOptions.html>
23 Std(std::fs::OpenOptions),
24 #[cfg(tokio_fs)]
25 #[cfg_attr(docsrs, doc(cfg(feature = "tokio-fs")))]
26 /// Tokio variant of file <https://docs.rs/tokio/latest/tokio/fs/struct.OpenOptions.html>
27 Tokio(tokio::fs::OpenOptions),
28}
29
30impl From<std::fs::OpenOptions> for OpenOptions {
31 fn from(options: std::fs::OpenOptions) -> Self {
32 Self(OpenOptionsInner::Std(options))
33 }
34}
35
36#[cfg(tokio_fs)]
37#[cfg_attr(docsrs, doc(cfg(feature = "tokio-fs")))]
38impl From<tokio::fs::OpenOptions> for OpenOptions {
39 fn from(options: tokio::fs::OpenOptions) -> Self {
40 Self(OpenOptionsInner::Tokio(options))
41 }
42}
43
44impl OpenOptions {
45 /// Creates a blank new set of options ready for configuration.
46 /// All options are initially set to false.
47 pub fn new() -> Self {
48 #[cfg(tokio_fs)]
49 {
50 if crate::context::is_async_context() {
51 tokio::fs::OpenOptions::new().into()
52 } else {
53 std::fs::OpenOptions::new().into()
54 }
55 }
56 #[cfg(not(tokio_fs))]
57 {
58 std::fs::OpenOptions::new().into()
59 }
60 }
61
62 /// Sets the option for read access.
63 ///
64 /// This option, when true, will indicate that the file should be
65 /// `read`-able if opened.
66 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
67 match &mut self.0 {
68 OpenOptionsInner::Std(inner) => {
69 inner.read(read);
70 }
71 #[cfg(tokio_fs)]
72 OpenOptionsInner::Tokio(inner) => {
73 inner.read(read);
74 }
75 }
76 self
77 }
78
79 /// Sets the option for write access.
80 ///
81 /// This option, when true, will indicate that the file should be `write`-able if opened.
82 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
83 match &mut self.0 {
84 OpenOptionsInner::Std(inner) => {
85 inner.write(write);
86 }
87 #[cfg(tokio_fs)]
88 OpenOptionsInner::Tokio(inner) => {
89 inner.write(write);
90 }
91 }
92 self
93 }
94
95 /// Sets the option for append mode.
96 ///
97 /// This option, when true, means that writes will append to a file instead of overwriting previous contents.
98 /// Note that setting `.write(true).append(true)` has the same effect as setting only `.append(true)`.
99 ///
100 /// For most filesystems, the operating system guarantees that all writes are atomic: no writes get mangled because another process writes at the same time.
101 ///
102 /// One maybe obvious note when using append-mode: make sure that all data that belongs together is written to
103 /// the file in one operation. This can be done by concatenating strings before passing them to [`Self::write`], or using a
104 /// buffered writer (with a buffer of adequate size), and calling flush() when the message is complete.
105 ///
106 /// If a file is opened with both read and append access, beware that after opening, and after every write,
107 /// the position for reading may be set at the end of the file.
108 /// So, before writing, save the current position (using `seek(SeekFrom::Current(0))`), and restore it before the next read.
109 ///
110 /// ### Note
111 ///
112 /// This function doesn’t create the file if it doesn’t exist. Use the [`Self::create`] method to do so.
113 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
114 match &mut self.0 {
115 OpenOptionsInner::Std(inner) => {
116 inner.append(append);
117 }
118 #[cfg(tokio_fs)]
119 OpenOptionsInner::Tokio(inner) => {
120 inner.append(append);
121 }
122 }
123 self
124 }
125
126 /// Sets the option for truncating a previous file.
127 ///
128 /// If a file is successfully opened with this option set it will truncate the file to 0 length if it already exists.
129 ///
130 /// The file must be opened with write access for truncate to work.
131 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
132 match &mut self.0 {
133 OpenOptionsInner::Std(inner) => {
134 inner.truncate(truncate);
135 }
136 #[cfg(tokio_fs)]
137 OpenOptionsInner::Tokio(inner) => {
138 inner.truncate(truncate);
139 }
140 }
141 self
142 }
143
144 /// Sets the option for creating a new file.
145 ///
146 /// This option indicates whether a new file will be created if the file does not yet already exist.
147 ///
148 /// In order for the file to be created, [`Self::write`] or [`Self::append`] access must be used.
149 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
150 match &mut self.0 {
151 OpenOptionsInner::Std(inner) => {
152 inner.create(create);
153 }
154 #[cfg(tokio_fs)]
155 OpenOptionsInner::Tokio(inner) => {
156 inner.create(create);
157 }
158 }
159 self
160 }
161
162 /// Sets the option to always create a new file.
163 ///
164 /// This option indicates whether a new file will be created. No file is allowed to exist at the target location, also no (dangling) symlink.
165 ///
166 ///
167 /// This option is useful because it is atomic. Otherwise between checking whether a file exists and creating a new one, the file may have been created by another process (a TOCTOU race condition / attack).
168 ///
169 /// If `.create_new(true)` is set, `.create()` and `.truncate()` are ignored.
170 ///
171 /// The file must be opened with [`Self::write`] or [`Self::append`] access in order to create a new file.
172 pub fn create_new(&mut self, create_new: bool) -> &mut OpenOptions {
173 match &mut self.0 {
174 OpenOptionsInner::Std(inner) => {
175 inner.create_new(create_new);
176 }
177 #[cfg(tokio_fs)]
178 OpenOptionsInner::Tokio(inner) => {
179 inner.create_new(create_new);
180 }
181 }
182 self
183 }
184
185 /// Opens a file at `path` with the options specified by `self`.
186 ///
187 /// # Errors
188 ///
189 /// This function will return an error under a number of different
190 /// circumstances. Some of these error conditions are listed here, together
191 /// with their [`ErrorKind`]. The mapping to [`ErrorKind`]s is not part of
192 /// the compatibility contract of the function, especially the `Other` kind
193 /// might change to more specific kinds in the future.
194 ///
195 /// - [`NotFound`]: The specified file does not exist and neither `create`
196 /// or `create_new` is set.
197 /// - [`NotFound`]: One of the directory components of the file path does
198 /// not exist.
199 /// - [`PermissionDenied`]: The user lacks permission to get the specified
200 /// access rights for the file.
201 /// - [`PermissionDenied`]: The user lacks permission to open one of the
202 /// directory components of the specified path.
203 /// - [`AlreadyExists`]: `create_new` was specified and the file already
204 /// exists.
205 /// - [`InvalidInput`]: Invalid combinations of open options (truncate
206 /// without write access, no access mode set, etc.).
207 /// - [`Other`]: One of the directory components of the specified file path
208 /// was not, in fact, a directory.
209 /// - [`Other`]: Filesystem-level errors: full disk, write permission
210 /// requested on a read-only file system, exceeded disk quota, too many
211 /// open files, too long filename, too many symbolic links in the
212 /// specified path (Unix-like systems only), etc.
213 pub async fn open(
214 &self,
215 path: impl AsRef<std::path::Path>,
216 ) -> std::io::Result<crate::fs::File> {
217 match &self.0 {
218 OpenOptionsInner::Std(inner) => inner.open(path).map(crate::fs::File::from),
219 #[cfg(tokio_fs)]
220 OpenOptionsInner::Tokio(inner) => inner.open(path).await.map(crate::fs::File::from),
221 }
222 }
223
224 /// Sets the mode bits that a new file will be created with.
225 ///
226 /// If a new file is created as part of an [`Self::open`] call then this specified mode will be used as the permission bits
227 /// for the new file. If no mode is set, the default of `0o666` will be used.
228 /// The operating system masks out bits with the system’s umask, to produce the final permissions.
229 #[cfg(unix)]
230 #[cfg_attr(docsrs, doc(cfg(unix)))]
231 pub fn mode(&mut self, mode: u32) -> &mut OpenOptions {
232 use std::os::unix::fs::OpenOptionsExt as _;
233
234 match &mut self.0 {
235 OpenOptionsInner::Std(inner) => {
236 inner.mode(mode);
237 }
238 #[cfg(tokio_fs)]
239 OpenOptionsInner::Tokio(inner) => {
240 inner.mode(mode);
241 }
242 }
243 self
244 }
245
246 #[cfg(unix)]
247 #[cfg_attr(docsrs, doc(cfg(unix)))]
248 /// Passes custom flags to the flags argument of `open`.
249 ///
250 /// The bits that define the access mode are masked out with `O_ACCMODE`, to ensure they do not interfere with the access mode set by Rusts options.
251 ///
252 /// Custom flags can only set flags, not remove flags set by Rusts options. This options overwrites any previously set custom flags.
253 pub fn custom_flags(&mut self, flags: i32) -> &mut OpenOptions {
254 use std::os::unix::fs::OpenOptionsExt as _;
255
256 match &mut self.0 {
257 OpenOptionsInner::Std(inner) => {
258 inner.custom_flags(flags);
259 }
260 #[cfg(tokio_fs)]
261 OpenOptionsInner::Tokio(inner) => {
262 inner.custom_flags(flags);
263 }
264 }
265 self
266 }
267
268 #[cfg(windows)]
269 #[cfg_attr(docsrs, doc(cfg(windows)))]
270 /// Overrides the dwDesiredAccess argument to the call to `CreateFile` with the specified value.
271 ///
272 /// This will override the read, write, and append flags on the `OpenOptions` structure. This method provides fine-grained control over the permissions to read, write and append data, attributes (like hidden and system), and extended attributes.
273 pub fn access_mode(&mut self, access_mode: u32) -> &mut OpenOptions {
274 use std::os::windows::fs::OpenOptionsExt as _;
275
276 match &mut self.0 {
277 OpenOptionsInner::Std(inner) => {
278 inner.access_mode(access_mode);
279 }
280 #[cfg(tokio_fs)]
281 OpenOptionsInner::Tokio(inner) => {
282 inner.access_mode(access_mode);
283 }
284 }
285 self
286 }
287
288 #[cfg(windows)]
289 #[cfg_attr(docsrs, doc(cfg(windows)))]
290 ///Overrides the dwShareMode argument to the call to CreateFile with the specified value.
291 /// By default share_mode is set to `FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE`.
292 /// This allows other processes to read, write, and delete/rename the same file while it is open. Removing any of the flags will prevent other processes from performing the corresponding operation until the file handle is closed.
293 pub fn share_mode(&mut self, share_mode: u32) -> &mut OpenOptions {
294 use std::os::windows::fs::OpenOptionsExt as _;
295
296 match &mut self.0 {
297 OpenOptionsInner::Std(inner) => {
298 inner.share_mode(share_mode);
299 }
300 #[cfg(tokio_fs)]
301 OpenOptionsInner::Tokio(inner) => {
302 inner.share_mode(share_mode);
303 }
304 }
305 self
306 }
307
308 #[cfg(windows)]
309 #[cfg_attr(docsrs, doc(cfg(windows)))]
310 /// Sets extra flags for the dwFileFlags argument to the call to CreateFile2 to the specified value (or combines it with attributes and security_qos_flags to set the dwFlagsAndAttributes for CreateFile).
311 /// Custom flags can only set flags, not remove flags set by Rust’s options. This option overwrites any previously set custom flags.
312 pub fn custom_flags(&mut self, flags: u32) -> &mut OpenOptions {
313 use std::os::windows::fs::OpenOptionsExt as _;
314
315 match &mut self.0 {
316 OpenOptionsInner::Std(inner) => {
317 inner.custom_flags(flags);
318 }
319 #[cfg(tokio_fs)]
320 OpenOptionsInner::Tokio(inner) => {
321 inner.custom_flags(flags);
322 }
323 }
324 self
325 }
326
327 #[cfg(windows)]
328 #[cfg_attr(docsrs, doc(cfg(windows)))]
329 /// Sets the dwFileAttributes argument to the call to CreateFile2 to the specified value (or combines it with custom_flags and security_qos_flags to set the dwFlagsAndAttributes for CreateFile).
330 ///
331 /// If a new file is created because it does not yet exist and .create(true) or .create_new(true) are specified, the new file is given the attributes declared with .attributes().
332 ///
333 /// If an existing file is opened with .create(true).truncate(true), its existing attributes are preserved and combined with the ones declared with .attributes().
334 ///
335 /// In all other cases the attributes get ignored.
336 pub fn attributes(&mut self, attributes: u32) -> &mut OpenOptions {
337 use std::os::windows::fs::OpenOptionsExt as _;
338
339 match &mut self.0 {
340 OpenOptionsInner::Std(inner) => {
341 inner.attributes(attributes);
342 }
343 #[cfg(tokio_fs)]
344 OpenOptionsInner::Tokio(inner) => {
345 inner.attributes(attributes);
346 }
347 }
348 self
349 }
350
351 #[cfg(windows)]
352 #[cfg_attr(docsrs, doc(cfg(windows)))]
353 /// Sets the dwSecurityQosFlags argument to the call to CreateFile2 to the specified value (or combines it with custom_flags and attributes to set the dwFlagsAndAttributes for CreateFile).
354 ///
355 /// By default security_qos_flags is not set. It should be specified when opening a named pipe, to control to which degree a server process can act on behalf of a client process (security impersonation level).
356 ///
357 /// When security_qos_flags is not set, a malicious program can gain the elevated privileges of a privileged Rust process when it allows opening user-specified paths, by tricking it into opening a named pipe. So arguably security_qos_flags should also be set when opening arbitrary paths. However the bits can then conflict with other flags, specifically FILE_FLAG_OPEN_NO_RECALL.
358 ///
359 /// For information about possible values, see Impersonation Levels on the Windows Dev Center site. The SECURITY_SQOS_PRESENT flag is set automatically when using this method.
360 pub fn security_qos_flags(&mut self, flags: u32) -> &mut OpenOptions {
361 use std::os::windows::fs::OpenOptionsExt as _;
362
363 match &mut self.0 {
364 OpenOptionsInner::Std(inner) => {
365 inner.security_qos_flags(flags);
366 }
367 #[cfg(tokio_fs)]
368 OpenOptionsInner::Tokio(inner) => {
369 inner.security_qos_flags(flags);
370 }
371 }
372 self
373 }
374}
375
376#[cfg(test)]
377mod test {
378
379 use super::*;
380 use crate::{SyncRuntime, Unwrap};
381
382 #[test]
383 fn test_open_options() {
384 let options = OpenOptions::new();
385 assert!(matches!(options.0, OpenOptionsInner::Std(_)));
386 }
387
388 #[tokio::test]
389 async fn test_open_options_async() {
390 let options = OpenOptions::new();
391 assert!(matches!(options.0, OpenOptionsInner::Tokio(_)));
392 }
393
394 #[test]
395 fn test_open_file_sync() {
396 let temp = tempfile::NamedTempFile::new().expect("Failed to create temp file");
397 std::fs::write(temp.path(), b"Hello world").expect("Failed to write file");
398
399 SyncRuntime::block_on(OpenOptions::new().read(true).write(true).open(temp.path()))
400 .expect("Failed to open file");
401 }
402
403 #[tokio::test]
404 async fn test_open_file_async() {
405 let temp = tempfile::NamedTempFile::new().expect("Failed to create temp file");
406 std::fs::write(temp.path(), b"Hello world").expect("Failed to write file");
407
408 OpenOptions::new()
409 .read(true)
410 .write(true)
411 .open(temp.path())
412 .await
413 .expect("Failed to open file");
414 }
415
416 #[test]
417 fn test_should_get_underlying_type() {
418 let options = OpenOptions::new();
419 options.unwrap_std();
420 }
421
422 #[tokio::test]
423 async fn test_should_get_underlying_type_async() {
424 let options = OpenOptions::new();
425 options.unwrap_tokio();
426 }
427}