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