Skip to main content

std/os/windows/
fs.rs

1//! Windows-specific extensions to primitives in the [`std::fs`] module.
2//!
3//! [`std::fs`]: crate::fs
4
5#![stable(feature = "rust1", since = "1.0.0")]
6
7use crate::fs::{self, Metadata, OpenOptions, Permissions};
8use crate::io::BorrowedCursor;
9use crate::macros::rustdoc_skip_body;
10use crate::path::Path;
11use crate::sys::{AsInner, AsInnerMut, FromInner, IntoInner};
12use crate::time::SystemTime;
13use crate::{io, sys};
14
15mod dirs;
16
17#[unstable(feature = "fs_home_dirs", issue = "162082")]
18pub use dirs::HomeDirsExt;
19#[unstable(feature = "fs_media_dirs", issue = "162083")]
20pub use dirs::MediaDirsExt;
21
22/// Windows-specific extensions to [`fs::File`].
23#[stable(feature = "file_offset", since = "1.15.0")]
24pub trait FileExt {
25    /// Seeks to a given position and reads a number of bytes.
26    ///
27    /// Returns the number of bytes read.
28    ///
29    /// The offset is relative to the start of the file and thus independent
30    /// from the current cursor. The current cursor **is** affected by this
31    /// function, it is set to the end of the read.
32    ///
33    /// Reading beyond the end of the file will always return with a length of
34    /// 0\.
35    ///
36    /// Note that similar to `File::read`, it is not an error to return with a
37    /// short read. When returning from such a short read, the file pointer is
38    /// still updated.
39    ///
40    /// # Examples
41    ///
42    #[cfg_attr(windows, doc = "```no_run")]
43    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
44    /// use std::io;
45    /// use std::fs::File;
46    /// use std::os::windows::prelude::*;
47    ///
48    /// fn main() -> io::Result<()> {
49    ///     let mut file = File::open("foo.txt")?;
50    ///     let mut buffer = [0; 10];
51    ///
52    ///     // Read 10 bytes, starting 72 bytes from the
53    ///     // start of the file.
54    ///     file.seek_read(&mut buffer[..], 72)?;
55    ///     Ok(())
56    /// }
57    /// ```
58    #[stable(feature = "file_offset", since = "1.15.0")]
59    fn seek_read(&self, buf: &mut [u8], offset: u64) -> io::Result<usize>;
60
61    /// Seeks to a given position and reads the exact number of bytes required to fill `buf`.
62    ///
63    /// The offset is relative to the start of the file and thus independent
64    /// from the current cursor. The current cursor **is** affected by this
65    /// function, it is set to the end of the read.
66    ///
67    /// Similar to [`io::Read::read_exact`] but uses [`seek_read`] instead of `read`.
68    ///
69    /// [`seek_read`]: FileExt::seek_read
70    ///
71    /// # Errors
72    ///
73    ///
74    /// If this function encounters an "end of file" before completely filling
75    /// the buffer, it returns an error of the kind [`io::ErrorKind::UnexpectedEof`].
76    /// The contents of `buf` are unspecified in this case.
77    ///
78    /// If any other read error is encountered then this function immediately
79    /// returns. The contents of `buf` are unspecified in this case.
80    ///
81    /// If this function returns an error, it is unspecified how many bytes it
82    /// has read, but it will never read more than would be necessary to
83    /// completely fill the buffer.
84    ///
85    /// # Examples
86    ///
87    #[cfg_attr(windows, doc = "```no_run")]
88    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
89    /// #![feature(seek_read_exact_seek_write_all)]
90    ///
91    /// use std::io;
92    /// use std::fs::File;
93    /// use std::os::windows::prelude::*;
94    ///
95    /// fn main() -> io::Result<()> {
96    ///     let mut file = File::open("foo.txt")?;
97    ///     let mut buffer = [0; 10];
98    ///
99    ///     // Read 10 bytes, starting 72 bytes from the
100    ///     // start of the file.
101    ///     file.seek_read_exact(&mut buffer[..], 72)?;
102    ///     Ok(())
103    /// }
104    /// ```
105    #[unstable(feature = "seek_read_exact_seek_write_all", issue = "162868")]
106    fn seek_read_exact(&self, mut buf: &mut [u8], mut offset: u64) -> io::Result<()> {
107        while !buf.is_empty() {
108            match self.seek_read(buf, offset) {
109                Ok(0) => break,
110                Ok(n) => {
111                    buf = &mut buf[n..];
112                    offset += n as u64;
113                }
114                Err(e) => return Err(e),
115            }
116        }
117        if !buf.is_empty() { Err(io::Error::READ_EXACT_EOF) } else { Ok(()) }
118    }
119
120    /// Seeks to a given position and reads some bytes into the buffer.
121    ///
122    /// This is equivalent to the [`seek_read`](FileExt::seek_read) method, except that it is passed
123    /// a [`BorrowedCursor`] rather than `&mut [u8]` to allow use with uninitialized buffers. The
124    /// new data will be appended to any existing contents of `buf`.
125    ///
126    /// Reading beyond the end of the file will always succeed without reading any bytes.
127    ///
128    /// # Examples
129    ///
130    #[cfg_attr(windows, doc = "```no_run")]
131    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
132    /// #![feature(core_io_borrowed_buf)]
133    /// #![feature(read_buf_at)]
134    ///
135    /// use std::io;
136    /// use std::io::BorrowedBuf;
137    /// use std::fs::File;
138    /// use std::mem::MaybeUninit;
139    /// use std::os::windows::prelude::*;
140    ///
141    /// fn main() -> io::Result<()> {
142    ///     let mut file = File::open("pi.txt")?;
143    ///
144    ///     // Read some bytes starting from offset 2
145    ///     let mut buf: [MaybeUninit<u8>; 10] = [MaybeUninit::uninit(); 10];
146    ///     let mut buf = BorrowedBuf::from(buf.as_mut_slice());
147    ///     file.seek_read_buf(buf.unfilled(), 2)?;
148    ///
149    ///     assert!(buf.filled().starts_with(b"1"));
150    ///
151    ///     Ok(())
152    /// }
153    /// ```
154    #[unstable(feature = "read_buf_at", issue = "140771")]
155    fn seek_read_buf(&self, buf: BorrowedCursor<'_, u8>, offset: u64) -> io::Result<()> {
156        io::default_read_buf(|b| self.seek_read(b, offset), buf)
157    }
158
159    /// Seeks to a given position and reads the exact number of bytes required to fill `buf`.
160    ///
161    /// This is equivalent to the [`seek_read_exact`](FileExt::seek_read_exact) method, except
162    /// that it is passed a [`BorrowedCursor`] rather than `&mut [u8]` to allow use with
163    /// uninitialized buffers. The new data will be appended to any existing contents of `buf`.
164    ///
165    /// Reading beyond the end of the file will always succeed without reading any bytes.
166    ///
167    /// # Examples
168    ///
169    #[cfg_attr(windows, doc = "```no_run")]
170    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
171    /// #![feature(core_io_borrowed_buf)]
172    /// #![feature(seek_read_exact_seek_write_all)]
173    ///
174    /// use std::io;
175    /// use std::io::BorrowedBuf;
176    /// use std::fs::File;
177    /// use std::mem::MaybeUninit;
178    /// use std::os::windows::prelude::*;
179    ///
180    /// fn main() -> io::Result<()> {
181    ///     let mut file = File::open("pi.txt")?;
182    ///
183    ///     // Read some bytes starting from offset 2
184    ///     let mut buf: [MaybeUninit<u8>; 10] = [MaybeUninit::uninit(); 10];
185    ///     let mut buf = BorrowedBuf::from(buf.as_mut_slice());
186    ///     file.seek_read_buf_exact(buf.unfilled(), 2)?;
187    ///
188    ///     assert!(buf.filled().starts_with(b"1"));
189    ///
190    ///     Ok(())
191    /// }
192    /// ```
193    #[unstable(feature = "seek_read_exact_seek_write_all", issue = "162868")]
194    fn seek_read_buf_exact(
195        &self,
196        mut buf: BorrowedCursor<'_, u8>,
197        mut offset: u64,
198    ) -> io::Result<()> {
199        while buf.capacity() > 0 {
200            let prev_written = buf.written();
201            match self.seek_read_buf(buf.reborrow(), offset) {
202                Ok(()) => {}
203                Err(e) => return Err(e),
204            }
205            let n = buf.written() - prev_written;
206            offset += n as u64;
207            if n == 0 {
208                return Err(io::Error::READ_EXACT_EOF);
209            }
210        }
211        Ok(())
212    }
213
214    /// Seeks to a given position and writes a number of bytes.
215    ///
216    /// Returns the number of bytes written.
217    ///
218    /// The offset is relative to the start of the file and thus independent
219    /// from the current cursor. The current cursor **is** affected by this
220    /// function, it is set to the end of the write.
221    ///
222    /// When writing beyond the end of the file, the file is appropriately
223    /// extended and the intermediate bytes are set to zero.
224    ///
225    /// Note that similar to `File::write`, it is not an error to return a
226    /// short write. When returning from such a short write, the file pointer
227    /// is still updated.
228    ///
229    /// # Examples
230    ///
231    #[cfg_attr(windows, doc = "```no_run")]
232    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
233    /// use std::fs::File;
234    /// use std::os::windows::prelude::*;
235    ///
236    /// fn main() -> std::io::Result<()> {
237    ///     let mut buffer = File::create("foo.txt")?;
238    ///
239    ///     // Write a byte string starting 72 bytes from
240    ///     // the start of the file.
241    ///     buffer.seek_write(b"some bytes", 72)?;
242    ///     Ok(())
243    /// }
244    /// ```
245    #[stable(feature = "file_offset", since = "1.15.0")]
246    fn seek_write(&self, buf: &[u8], offset: u64) -> io::Result<usize>;
247
248    /// Seeks to a given position and attempts to write an entire buffer.
249    ///
250    /// The offset is relative to the start of the file and thus independent
251    /// from the current cursor. The current cursor **is** affected by this
252    /// function, it is set to the end of the write.
253    ///
254    /// This method will continuously call [`seek_write`] until there is no more data
255    /// to be written or an error of non-[`io::ErrorKind::Interrupted`] kind is
256    /// returned. This method will not return until the entire buffer has been
257    /// successfully written or such an error occurs. The first error that is
258    /// not of [`io::ErrorKind::Interrupted`] kind generated from this method will be
259    /// returned.
260    ///
261    /// # Errors
262    ///
263    /// This function will return the first error that [`seek_write`] returns.
264    ///
265    /// [`seek_write`]: FileExt::seek_write
266    ///
267    /// # Examples
268    ///
269    #[cfg_attr(windows, doc = "```no_run")]
270    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
271    /// #![feature(seek_read_exact_seek_write_all)]
272    ///
273    /// use std::fs::File;
274    /// use std::os::windows::prelude::*;
275    ///
276    /// fn main() -> std::io::Result<()> {
277    ///     let mut buffer = File::create("foo.txt")?;
278    ///
279    ///     // Write a byte string starting 72 bytes from
280    ///     // the start of the file.
281    ///     buffer.seek_write_all(b"some bytes", 72)?;
282    ///     Ok(())
283    /// }
284    /// ```
285    #[unstable(feature = "seek_read_exact_seek_write_all", issue = "162868")]
286    fn seek_write_all(&self, mut buf: &[u8], mut offset: u64) -> io::Result<()> {
287        while !buf.is_empty() {
288            match self.seek_write(buf, offset) {
289                Ok(0) => {
290                    return Err(io::Error::WRITE_ALL_EOF);
291                }
292                Ok(n) => {
293                    buf = &buf[n..];
294                    offset += n as u64
295                }
296                Err(e) => return Err(e),
297            }
298        }
299        Ok(())
300    }
301}
302
303#[stable(feature = "file_offset", since = "1.15.0")]
304impl FileExt for fs::File {
305    fn seek_read(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
306        self.as_inner().read_at(buf, offset)
307    }
308
309    fn seek_read_buf(&self, buf: BorrowedCursor<'_, u8>, offset: u64) -> io::Result<()> {
310        self.as_inner().read_buf_at(buf, offset)
311    }
312
313    fn seek_write(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
314        self.as_inner().write_at(buf, offset)
315    }
316}
317
318/// Windows-specific extensions to [`fs::OpenOptions`].
319// WARNING: This trait is not sealed. DON'T add any new methods!
320// Add them to OpenOptionsExt2 instead.
321#[stable(feature = "open_options_ext", since = "1.10.0")]
322pub trait OpenOptionsExt {
323    /// Overrides the `dwDesiredAccess` argument to the call to [`CreateFile`]
324    /// with the specified value.
325    ///
326    /// This will override the `read`, `write`, and `append` flags on the
327    /// `OpenOptions` structure. This method provides fine-grained control over
328    /// the permissions to read, write and append data, attributes (like hidden
329    /// and system), and extended attributes.
330    ///
331    /// # Examples
332    ///
333    #[cfg_attr(windows, doc = "```no_run")]
334    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
335    /// use std::fs::OpenOptions;
336    /// use std::os::windows::prelude::*;
337    ///
338    /// // Open without read and write permission, for example if you only need
339    /// // to call `stat` on the file
340    /// let file = OpenOptions::new().access_mode(0).open("foo.txt");
341    /// ```
342    ///
343    /// [`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea
344    #[stable(feature = "open_options_ext", since = "1.10.0")]
345    fn access_mode(&mut self, access: u32) -> &mut Self;
346
347    /// Overrides the `dwShareMode` argument to the call to [`CreateFile`] with
348    /// the specified value.
349    ///
350    /// By default `share_mode` is set to
351    /// `FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE`. This allows
352    /// other processes to read, write, and delete/rename the same file
353    /// while it is open. Removing any of the flags will prevent other
354    /// processes from performing the corresponding operation until the file
355    /// handle is closed.
356    ///
357    /// # Examples
358    ///
359    #[cfg_attr(windows, doc = "```no_run")]
360    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
361    /// use std::fs::OpenOptions;
362    /// use std::os::windows::prelude::*;
363    ///
364    /// // Do not allow others to read or modify this file while we have it open
365    /// // for writing.
366    /// let file = OpenOptions::new()
367    ///     .write(true)
368    ///     .share_mode(0)
369    ///     .open("foo.txt");
370    /// ```
371    ///
372    /// [`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea
373    #[stable(feature = "open_options_ext", since = "1.10.0")]
374    fn share_mode(&mut self, val: u32) -> &mut Self;
375
376    /// Sets extra flags for the `dwFileFlags` argument to the call to
377    /// [`CreateFile2`] to the specified value (or combines it with
378    /// `attributes` and `security_qos_flags` to set the `dwFlagsAndAttributes`
379    /// for [`CreateFile`]).
380    ///
381    /// Custom flags can only set flags, not remove flags set by Rust's options.
382    /// This option overwrites any previously set custom flags.
383    ///
384    /// # Examples
385    ///
386    #[cfg_attr(windows, doc = "```no_run")]
387    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
388    /// # #![allow(unexpected_cfgs)]
389    /// use std::fs::OpenOptions;
390    /// use std::os::windows::prelude::*;
391    ///
392    /// # pub const FILE_FLAG_DELETE_ON_CLOSE: u32 = 0x04000000;
393    ///
394    /// let file = OpenOptions::new()
395    ///     .create(true)
396    ///     .write(true)
397    ///     .custom_flags(FILE_FLAG_DELETE_ON_CLOSE)
398    ///     .open("foo.txt");
399    /// ```
400    ///
401    /// [`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea
402    /// [`CreateFile2`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfile2
403    #[stable(feature = "open_options_ext", since = "1.10.0")]
404    fn custom_flags(&mut self, flags: u32) -> &mut Self;
405
406    /// Sets the `dwFileAttributes` argument to the call to [`CreateFile2`] to
407    /// the specified value (or combines it with `custom_flags` and
408    /// `security_qos_flags` to set the `dwFlagsAndAttributes` for
409    /// [`CreateFile`]).
410    ///
411    /// If a _new_ file is created because it does not yet exist and
412    /// `.create(true)` or `.create_new(true)` are specified, the new file is
413    /// given the attributes declared with `.attributes()`.
414    ///
415    /// If an _existing_ file is opened with `.create(true).truncate(true)`, its
416    /// existing attributes are preserved and combined with the ones declared
417    /// with `.attributes()`.
418    ///
419    /// In all other cases the attributes get ignored.
420    ///
421    /// # Examples
422    ///
423    #[cfg_attr(windows, doc = "```no_run")]
424    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
425    /// # #![allow(unexpected_cfgs)]
426    /// use std::fs::OpenOptions;
427    /// use std::os::windows::prelude::*;
428    ///
429    /// # pub const FILE_ATTRIBUTE_HIDDEN: u32 = 2;
430    ///
431    /// let file = OpenOptions::new()
432    ///     .write(true)
433    ///     .create(true)
434    ///     .attributes(FILE_ATTRIBUTE_HIDDEN)
435    ///     .open("foo.txt");
436    /// ```
437    ///
438    /// [`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea
439    /// [`CreateFile2`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfile2
440    #[stable(feature = "open_options_ext", since = "1.10.0")]
441    fn attributes(&mut self, val: u32) -> &mut Self;
442
443    /// Sets the `dwSecurityQosFlags` argument to the call to [`CreateFile2`] to
444    /// the specified value (or combines it with `custom_flags` and `attributes`
445    /// to set the `dwFlagsAndAttributes` for [`CreateFile`]).
446    ///
447    /// By default `security_qos_flags` is not set. It should be specified when
448    /// opening a named pipe, to control to which degree a server process can
449    /// act on behalf of a client process (security impersonation level).
450    ///
451    /// When `security_qos_flags` is not set, a malicious program can gain the
452    /// elevated privileges of a privileged Rust process when it allows opening
453    /// user-specified paths, by tricking it into opening a named pipe. So
454    /// arguably `security_qos_flags` should also be set when opening arbitrary
455    /// paths. However the bits can then conflict with other flags, specifically
456    /// `FILE_FLAG_OPEN_NO_RECALL`.
457    ///
458    /// For information about possible values, see [Impersonation Levels] on the
459    /// Windows Dev Center site. The `SECURITY_SQOS_PRESENT` flag is set
460    /// automatically when using this method.
461    ///
462    /// # Examples
463    ///
464    #[cfg_attr(windows, doc = "```no_run")]
465    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
466    /// # #![allow(unexpected_cfgs)]
467    /// use std::fs::OpenOptions;
468    /// use std::os::windows::prelude::*;
469    ///
470    /// # pub const SECURITY_IDENTIFICATION: u32 = 0;
471    ///
472    /// let file = OpenOptions::new()
473    ///     .write(true)
474    ///     .create(true)
475    ///     .security_qos_flags(SECURITY_IDENTIFICATION)
476    ///     .open(r"\\.\pipe\MyPipe");
477    /// ```
478    ///
479    /// [`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea
480    /// [`CreateFile2`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfile2
481    /// [Impersonation Levels]:
482    ///     https://docs.microsoft.com/en-us/windows/win32/api/winnt/ne-winnt-security_impersonation_level
483    #[stable(feature = "open_options_ext", since = "1.10.0")]
484    fn security_qos_flags(&mut self, flags: u32) -> &mut Self;
485}
486
487#[stable(feature = "open_options_ext", since = "1.10.0")]
488impl OpenOptionsExt for OpenOptions {
489    #[rustdoc_skip_body]
490    fn access_mode(&mut self, access: u32) -> &mut OpenOptions {
491        self.as_inner_mut().access_mode(access);
492        self
493    }
494
495    #[rustdoc_skip_body]
496    fn share_mode(&mut self, share: u32) -> &mut OpenOptions {
497        self.as_inner_mut().share_mode(share);
498        self
499    }
500
501    #[rustdoc_skip_body]
502    fn custom_flags(&mut self, flags: u32) -> &mut OpenOptions {
503        self.as_inner_mut().custom_flags(flags);
504        self
505    }
506
507    #[rustdoc_skip_body]
508    fn attributes(&mut self, attributes: u32) -> &mut OpenOptions {
509        self.as_inner_mut().attributes(attributes);
510        self
511    }
512
513    #[rustdoc_skip_body]
514    fn security_qos_flags(&mut self, flags: u32) -> &mut OpenOptions {
515        self.as_inner_mut().security_qos_flags(flags);
516        self
517    }
518}
519
520#[unstable(feature = "windows_freeze_file_times", issue = "149715")]
521pub impl(self) trait OpenOptionsExt2 {
522    /// If set to `true`, prevent the "last access time" of the file from being changed.
523    ///
524    /// Default to `false`.
525    #[unstable(feature = "windows_freeze_file_times", issue = "149715")]
526    fn freeze_last_access_time(&mut self, freeze: bool) -> &mut Self;
527
528    /// If set to `true`, prevent the "last write time" of the file from being changed.
529    ///
530    /// Default to `false`.
531    #[unstable(feature = "windows_freeze_file_times", issue = "149715")]
532    fn freeze_last_write_time(&mut self, freeze: bool) -> &mut Self;
533}
534
535#[unstable(feature = "windows_freeze_file_times", issue = "149715")]
536impl OpenOptionsExt2 for OpenOptions {
537    #[rustdoc_skip_body]
538    fn freeze_last_access_time(&mut self, freeze: bool) -> &mut Self {
539        self.as_inner_mut().freeze_last_access_time(freeze);
540        self
541    }
542
543    #[rustdoc_skip_body]
544    fn freeze_last_write_time(&mut self, freeze: bool) -> &mut Self {
545        self.as_inner_mut().freeze_last_write_time(freeze);
546        self
547    }
548}
549
550/// Windows-specific extensions to [`fs::Permissions`]. This extension trait
551/// provides extra utilities to shows what Windows file attributes are enabled
552/// in [`Permissions`] and to manually set file attributes on [`Permissions`].
553///
554/// See Microsoft's [`File Attribute Constants`] page to know what file
555/// attribute metadata are defined and stored on Windows files.
556///
557/// [`Permissions`]: fs::Permissions
558/// [`File Attribute Constants`]:
559///     https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants
560///
561/// # Example
562///
563#[cfg_attr(windows, doc = "```no_run")]
564#[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
565/// #![feature(windows_permissions_ext)]
566/// use std::fs::Permissions;
567/// use std::os::windows::fs::PermissionsExt;
568///
569/// const FILE_ATTRIBUTE_SYSTEM: u32 = 0x4;
570/// const FILE_ATTRIBUTE_ARCHIVE: u32 = 0x20;
571/// let my_file_attr = FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_ARCHIVE;
572/// let mut permissions = Permissions::from_file_attributes(my_file_attr);
573/// assert_eq!(permissions.file_attributes(), my_file_attr);
574///
575/// const FILE_ATTRIBUTE_HIDDEN: u32 = 0x2;
576/// let new_file_attr = permissions.file_attributes() | FILE_ATTRIBUTE_HIDDEN;
577/// permissions.set_file_attributes(new_file_attr);
578/// assert_eq!(permissions.file_attributes(), new_file_attr);
579/// ```
580#[unstable(feature = "windows_permissions_ext", issue = "152956")]
581pub impl(self) trait PermissionsExt {
582    /// Returns the file attribute bits.
583    #[unstable(feature = "windows_permissions_ext", issue = "152956")]
584    fn file_attributes(&self) -> u32;
585
586    /// Sets the file attribute bits.
587    #[unstable(feature = "windows_permissions_ext", issue = "152956")]
588    fn set_file_attributes(&mut self, mask: u32);
589
590    /// Creates a new instance from the given file attribute bits.
591    #[unstable(feature = "windows_permissions_ext", issue = "152956")]
592    fn from_file_attributes(mask: u32) -> Self;
593}
594
595#[unstable(feature = "windows_permissions_ext", issue = "152956")]
596impl PermissionsExt for fs::Permissions {
597    #[rustdoc_skip_body]
598    fn file_attributes(&self) -> u32 {
599        self.as_inner().file_attributes()
600    }
601
602    fn set_file_attributes(&mut self, mask: u32) {
603        *self = Permissions::from_inner(FromInner::from_inner(mask));
604    }
605
606    fn from_file_attributes(mask: u32) -> Self {
607        Permissions::from_inner(FromInner::from_inner(mask))
608    }
609}
610
611/// Windows-specific extensions to [`fs::Metadata`].
612///
613/// The data members that this trait exposes correspond to the members
614/// of the [`BY_HANDLE_FILE_INFORMATION`] structure.
615///
616/// [`BY_HANDLE_FILE_INFORMATION`]:
617///     https://docs.microsoft.com/windows/win32/api/fileapi/ns-fileapi-by_handle_file_information
618#[stable(feature = "metadata_ext", since = "1.1.0")]
619pub trait MetadataExt {
620    /// Returns the value of the `dwFileAttributes` field of this metadata.
621    ///
622    /// This field contains the file system attribute information for a file
623    /// or directory. For possible values and their descriptions, see
624    /// [File Attribute Constants] in the Windows Dev Center.
625    ///
626    /// # Examples
627    ///
628    #[cfg_attr(windows, doc = "```no_run")]
629    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
630    /// use std::io;
631    /// use std::fs;
632    /// use std::os::windows::prelude::*;
633    ///
634    /// fn main() -> io::Result<()> {
635    ///     let metadata = fs::metadata("foo.txt")?;
636    ///     let attributes = metadata.file_attributes();
637    ///     Ok(())
638    /// }
639    /// ```
640    ///
641    /// [File Attribute Constants]:
642    ///     https://docs.microsoft.com/windows/win32/fileio/file-attribute-constants
643    #[stable(feature = "metadata_ext", since = "1.1.0")]
644    fn file_attributes(&self) -> u32;
645
646    /// Returns the value of the `ftCreationTime` field of this metadata.
647    ///
648    /// The returned 64-bit value is equivalent to a [`FILETIME`] struct,
649    /// which represents the number of 100-nanosecond intervals since
650    /// January 1, 1601 (UTC). The struct is automatically
651    /// converted to a `u64` value, as that is the recommended way
652    /// to use it.
653    ///
654    /// If the underlying filesystem does not support creation time, the
655    /// returned value is 0.
656    ///
657    /// # Examples
658    ///
659    #[cfg_attr(windows, doc = "```no_run")]
660    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
661    /// use std::io;
662    /// use std::fs;
663    /// use std::os::windows::prelude::*;
664    ///
665    /// fn main() -> io::Result<()> {
666    ///     let metadata = fs::metadata("foo.txt")?;
667    ///     let creation_time = metadata.creation_time();
668    ///     Ok(())
669    /// }
670    /// ```
671    ///
672    /// [`FILETIME`]: https://docs.microsoft.com/windows/win32/api/minwinbase/ns-minwinbase-filetime
673    #[stable(feature = "metadata_ext", since = "1.1.0")]
674    fn creation_time(&self) -> u64;
675
676    /// Returns the value of the `ftLastAccessTime` field of this metadata.
677    ///
678    /// The returned 64-bit value is equivalent to a [`FILETIME`] struct,
679    /// which represents the number of 100-nanosecond intervals since
680    /// January 1, 1601 (UTC). The struct is automatically
681    /// converted to a `u64` value, as that is the recommended way
682    /// to use it.
683    ///
684    /// For a file, the value specifies the last time that a file was read
685    /// from or written to. For a directory, the value specifies when
686    /// the directory was created. For both files and directories, the
687    /// specified date is correct, but the time of day is always set to
688    /// midnight.
689    ///
690    /// If the underlying filesystem does not support last access time, the
691    /// returned value is 0.
692    ///
693    /// # Examples
694    ///
695    #[cfg_attr(windows, doc = "```no_run")]
696    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
697    /// use std::io;
698    /// use std::fs;
699    /// use std::os::windows::prelude::*;
700    ///
701    /// fn main() -> io::Result<()> {
702    ///     let metadata = fs::metadata("foo.txt")?;
703    ///     let last_access_time = metadata.last_access_time();
704    ///     Ok(())
705    /// }
706    /// ```
707    ///
708    /// [`FILETIME`]: https://docs.microsoft.com/windows/win32/api/minwinbase/ns-minwinbase-filetime
709    #[stable(feature = "metadata_ext", since = "1.1.0")]
710    fn last_access_time(&self) -> u64;
711
712    /// Returns the value of the `ftLastWriteTime` field of this metadata.
713    ///
714    /// The returned 64-bit value is equivalent to a [`FILETIME`] struct,
715    /// which represents the number of 100-nanosecond intervals since
716    /// January 1, 1601 (UTC). The struct is automatically
717    /// converted to a `u64` value, as that is the recommended way
718    /// to use it.
719    ///
720    /// For a file, the value specifies the last time that a file was written
721    /// to. For a directory, the structure specifies when the directory was
722    /// created.
723    ///
724    /// If the underlying filesystem does not support the last write time,
725    /// the returned value is 0.
726    ///
727    /// # Examples
728    ///
729    #[cfg_attr(windows, doc = "```no_run")]
730    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
731    /// use std::io;
732    /// use std::fs;
733    /// use std::os::windows::prelude::*;
734    ///
735    /// fn main() -> io::Result<()> {
736    ///     let metadata = fs::metadata("foo.txt")?;
737    ///     let last_write_time = metadata.last_write_time();
738    ///     Ok(())
739    /// }
740    /// ```
741    ///
742    /// [`FILETIME`]: https://docs.microsoft.com/windows/win32/api/minwinbase/ns-minwinbase-filetime
743    #[stable(feature = "metadata_ext", since = "1.1.0")]
744    fn last_write_time(&self) -> u64;
745
746    /// Returns the value of the `nFileSize` fields of this
747    /// metadata.
748    ///
749    /// The returned value does not have meaning for directories.
750    ///
751    /// # Examples
752    ///
753    #[cfg_attr(windows, doc = "```no_run")]
754    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
755    /// use std::io;
756    /// use std::fs;
757    /// use std::os::windows::prelude::*;
758    ///
759    /// fn main() -> io::Result<()> {
760    ///     let metadata = fs::metadata("foo.txt")?;
761    ///     let file_size = metadata.file_size();
762    ///     Ok(())
763    /// }
764    /// ```
765    #[stable(feature = "metadata_ext", since = "1.1.0")]
766    fn file_size(&self) -> u64;
767
768    /// Returns the value of the `dwVolumeSerialNumber` field of this
769    /// metadata.
770    ///
771    /// This will return `None` if the `Metadata` instance was created from a
772    /// call to `DirEntry::metadata`. If this `Metadata` was created by using
773    /// `fs::metadata` or `File::metadata`, then this will return `Some`.
774    #[unstable(feature = "windows_by_handle", issue = "63010")]
775    fn volume_serial_number(&self) -> Option<u32>;
776
777    /// Returns the value of the `nNumberOfLinks` field of this
778    /// metadata.
779    ///
780    /// This will return `None` if the `Metadata` instance was created from a
781    /// call to `DirEntry::metadata`. If this `Metadata` was created by using
782    /// `fs::metadata` or `File::metadata`, then this will return `Some`.
783    #[unstable(feature = "windows_by_handle", issue = "63010")]
784    fn number_of_links(&self) -> Option<u32>;
785
786    /// Returns the value of the `nFileIndex` fields of this
787    /// metadata.
788    ///
789    /// This will return `None` if the `Metadata` instance was created from a
790    /// call to `DirEntry::metadata`. If this `Metadata` was created by using
791    /// `fs::metadata` or `File::metadata`, then this will return `Some`.
792    #[unstable(feature = "windows_by_handle", issue = "63010")]
793    fn file_index(&self) -> Option<u64>;
794
795    /// Returns the value of the `ChangeTime` fields of this metadata.
796    ///
797    /// `ChangeTime` is the last time file metadata was changed, such as
798    /// renames, attributes, etc.
799    ///
800    /// This will return `None` if `Metadata` instance was created from a call to
801    /// `DirEntry::metadata` or if the `target_vendor` is outside the current platform
802    /// support for this api.
803    #[unstable(feature = "windows_change_time", issue = "121478")]
804    fn change_time(&self) -> Option<u64>;
805}
806
807#[stable(feature = "metadata_ext", since = "1.1.0")]
808impl MetadataExt for Metadata {
809    #[rustdoc_skip_body]
810    fn file_attributes(&self) -> u32 {
811        self.as_inner().attrs()
812    }
813    #[rustdoc_skip_body]
814    fn creation_time(&self) -> u64 {
815        self.as_inner().created_u64()
816    }
817    #[rustdoc_skip_body]
818    fn last_access_time(&self) -> u64 {
819        self.as_inner().accessed_u64()
820    }
821    #[rustdoc_skip_body]
822    fn last_write_time(&self) -> u64 {
823        self.as_inner().modified_u64()
824    }
825    #[rustdoc_skip_body]
826    fn file_size(&self) -> u64 {
827        self.as_inner().size()
828    }
829    #[rustdoc_skip_body]
830    fn volume_serial_number(&self) -> Option<u32> {
831        self.as_inner().volume_serial_number()
832    }
833    #[rustdoc_skip_body]
834    fn number_of_links(&self) -> Option<u32> {
835        self.as_inner().number_of_links()
836    }
837    #[rustdoc_skip_body]
838    fn file_index(&self) -> Option<u64> {
839        self.as_inner().file_index()
840    }
841    #[rustdoc_skip_body]
842    fn change_time(&self) -> Option<u64> {
843        self.as_inner().changed_u64()
844    }
845}
846
847/// Windows-specific extensions to [`fs::FileType`].
848///
849/// On Windows, a symbolic link knows whether it is a file or directory.
850#[stable(feature = "windows_file_type_ext", since = "1.64.0")]
851pub impl(self) trait FileTypeExt {
852    /// Returns `true` if this file type is a symbolic link that is also a directory.
853    #[stable(feature = "windows_file_type_ext", since = "1.64.0")]
854    fn is_symlink_dir(&self) -> bool;
855    /// Returns `true` if this file type is a symbolic link that is also a file.
856    #[stable(feature = "windows_file_type_ext", since = "1.64.0")]
857    fn is_symlink_file(&self) -> bool;
858}
859
860#[stable(feature = "windows_file_type_ext", since = "1.64.0")]
861impl FileTypeExt for fs::FileType {
862    #[rustdoc_skip_body]
863    fn is_symlink_dir(&self) -> bool {
864        self.as_inner().is_symlink_dir()
865    }
866    #[rustdoc_skip_body]
867    fn is_symlink_file(&self) -> bool {
868        self.as_inner().is_symlink_file()
869    }
870}
871
872/// Windows-specific extensions to [`fs::FileTimes`].
873#[stable(feature = "file_set_times", since = "1.75.0")]
874pub impl(self) trait FileTimesExt {
875    /// Set the creation time of a file.
876    #[stable(feature = "file_set_times", since = "1.75.0")]
877    fn set_created(self, t: SystemTime) -> Self;
878}
879
880#[stable(feature = "file_set_times", since = "1.75.0")]
881impl FileTimesExt for fs::FileTimes {
882    #[rustdoc_skip_body]
883    fn set_created(mut self, t: SystemTime) -> Self {
884        self.as_inner_mut().set_created(t.into_inner());
885        self
886    }
887}
888
889/// Creates a new symlink to a non-directory file on the filesystem.
890///
891/// The `link` path will be a file symbolic link pointing to the `original`
892/// path.
893///
894/// The `original` path should not be a directory or a symlink to a directory,
895/// otherwise the symlink will be broken. Use [`symlink_dir`] for directories.
896///
897/// This function currently corresponds to [`CreateSymbolicLinkW`][CreateSymbolicLinkW].
898/// Note that this [may change in the future][changes].
899///
900/// [CreateSymbolicLinkW]: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createsymboliclinkw
901/// [changes]: io#platform-specific-behavior
902///
903/// # Examples
904///
905#[cfg_attr(windows, doc = "```no_run")]
906#[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
907/// use std::os::windows::fs;
908///
909/// fn main() -> std::io::Result<()> {
910///     fs::symlink_file("a.txt", "b.txt")?;
911///     Ok(())
912/// }
913/// ```
914///
915/// # Limitations
916///
917/// Windows treats symlink creation as a [privileged action][symlink-security],
918/// therefore this function is likely to fail unless the user makes changes to
919/// their system to permit symlink creation. Users can try enabling Developer
920/// Mode, granting the `SeCreateSymbolicLinkPrivilege` privilege, or running
921/// the process as an administrator.
922///
923/// [symlink-security]: https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/create-symbolic-links
924#[doc(alias = "CreateSymbolicLink", alias = "CreateSymbolicLinkW")]
925#[stable(feature = "symlink", since = "1.1.0")]
926#[cfg_attr(not(test), rustc_diagnostic_item = "fs_symlink_file")]
927#[rustdoc_skip_body]
928pub fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
929    sys::fs::symlink_inner(original.as_ref(), link.as_ref(), false)
930}
931
932/// Creates a new symlink to a directory on the filesystem.
933///
934/// The `link` path will be a directory symbolic link pointing to the `original`
935/// path.
936///
937/// The `original` path must be a directory or a symlink to a directory,
938/// otherwise the symlink will be broken. Use [`symlink_file`] for other files.
939///
940/// This function currently corresponds to [`CreateSymbolicLinkW`][CreateSymbolicLinkW].
941/// Note that this [may change in the future][changes].
942///
943/// [CreateSymbolicLinkW]: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createsymboliclinkw
944/// [changes]: io#platform-specific-behavior
945///
946/// # Examples
947///
948#[cfg_attr(windows, doc = "```no_run")]
949#[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
950/// use std::os::windows::fs;
951///
952/// fn main() -> std::io::Result<()> {
953///     fs::symlink_dir("a", "b")?;
954///     Ok(())
955/// }
956/// ```
957///
958/// # Limitations
959///
960/// Windows treats symlink creation as a [privileged action][symlink-security],
961/// therefore this function is likely to fail unless the user makes changes to
962/// their system to permit symlink creation. Users can try enabling Developer
963/// Mode, granting the `SeCreateSymbolicLinkPrivilege` privilege, or running
964/// the process as an administrator.
965///
966/// [symlink-security]: https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/create-symbolic-links
967#[doc(alias = "CreateSymbolicLink", alias = "CreateSymbolicLinkW")]
968#[stable(feature = "symlink", since = "1.1.0")]
969#[cfg_attr(not(test), rustc_diagnostic_item = "fs_symlink_dir")]
970#[rustdoc_skip_body]
971pub fn symlink_dir<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
972    sys::fs::symlink_inner(original.as_ref(), link.as_ref(), true)
973}
974
975/// Creates a junction point.
976///
977/// The `link` path will be a directory junction pointing to the original path.
978/// If `link` is a relative path then it will be made absolute prior to creating the junction point.
979/// The `original` path must be a directory or a link to a directory, otherwise the junction point will be broken.
980///
981/// If either path is not a local file path then this will fail.
982#[unstable(feature = "junction_point", issue = "121709")]
983#[rustdoc_skip_body]
984pub fn junction_point<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
985    sys::fs::junction_point(original.as_ref(), link.as_ref())
986}