]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/windows/ext/fs.rs
34f3a0196cedfa16d05ae8df0d876d0e4c917866
[rust.git] / src / libstd / sys / windows / ext / fs.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Windows-specific extensions for the primitives in the `std::fs` module.
12
13 #![stable(feature = "rust1", since = "1.0.0")]
14
15 use fs::{self, OpenOptions, Metadata};
16 use io;
17 use path::Path;
18 use sys;
19 use sys_common::{AsInnerMut, AsInner};
20
21 /// Windows-specific extensions to [`File`].
22 ///
23 /// [`File`]: ../../../fs/struct.File.html
24 #[stable(feature = "file_offset", since = "1.15.0")]
25 pub trait FileExt {
26     /// Seeks to a given position and reads a number of bytes.
27     ///
28     /// Returns the number of bytes read.
29     ///
30     /// The offset is relative to the start of the file and thus independent
31     /// from the current cursor. The current cursor **is** affected by this
32     /// function, it is set to the end of the read.
33     ///
34     /// Reading beyond the end of the file will always return with a length of
35     /// 0.
36     ///
37     /// Note that similar to `File::read`, it is not an error to return with a
38     /// short read. When returning from such a short read, the file pointer is
39     /// still updated.
40     ///
41     /// # Examples
42     ///
43     /// ```no_run
44     /// use std::io;
45     /// use std::fs::File;
46     /// use std::os::windows::prelude::*;
47     ///
48     /// # fn foo() -> 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 writes a number of bytes.
62     ///
63     /// Returns the number of bytes written.
64     ///
65     /// The offset is relative to the start of the file and thus independent
66     /// from the current cursor. The current cursor **is** affected by this
67     /// function, it is set to the end of the write.
68     ///
69     /// When writing beyond the end of the file, the file is appropiately
70     /// extended and the intermediate bytes are left uninitialized.
71     ///
72     /// Note that similar to `File::write`, it is not an error to return a
73     /// short write. When returning from such a short write, the file pointer
74     /// is still updated.
75     ///
76     /// # Examples
77     ///
78     /// ```no_run
79     /// use std::fs::File;
80     /// use std::os::windows::prelude::*;
81     ///
82     /// # fn foo() -> std::io::Result<()> {
83     /// let mut buffer = File::create("foo.txt")?;
84     ///
85     /// // Write a byte string starting 72 bytes from
86     /// // the start of the file.
87     /// buffer.seek_write(b"some bytes", 72)?;
88     /// # Ok(())
89     /// # }
90     /// ```
91     #[stable(feature = "file_offset", since = "1.15.0")]
92     fn seek_write(&self, buf: &[u8], offset: u64) -> io::Result<usize>;
93 }
94
95 #[stable(feature = "file_offset", since = "1.15.0")]
96 impl FileExt for fs::File {
97     fn seek_read(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
98         self.as_inner().read_at(buf, offset)
99     }
100
101     fn seek_write(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
102         self.as_inner().write_at(buf, offset)
103     }
104 }
105
106 /// Windows-specific extensions to [`OpenOptions`].
107 ///
108 /// [`OpenOptions`]: ../../../fs/struct.OpenOptions.html
109 #[stable(feature = "open_options_ext", since = "1.10.0")]
110 pub trait OpenOptionsExt {
111     /// Overrides the `dwDesiredAccess` argument to the call to [`CreateFile`]
112     /// with the specified value.
113     ///
114     /// This will override the `read`, `write`, and `append` flags on the
115     /// `OpenOptions` structure. This method provides fine-grained control over
116     /// the permissions to read, write and append data, attributes (like hidden
117     /// and system), and extended attributes.
118     ///
119     /// # Examples
120     ///
121     /// ```no_run
122     /// use std::fs::OpenOptions;
123     /// use std::os::windows::prelude::*;
124     ///
125     /// // Open without read and write permission, for example if you only need
126     /// // to call `stat` on the file
127     /// let file = OpenOptions::new().access_mode(0).open("foo.txt");
128     /// ```
129     ///
130     /// [`CreateFile`]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858.aspx
131     #[stable(feature = "open_options_ext", since = "1.10.0")]
132     fn access_mode(&mut self, access: u32) -> &mut Self;
133
134     /// Overrides the `dwShareMode` argument to the call to [`CreateFile`] with
135     /// the specified value.
136     ///
137     /// By default `share_mode` is set to
138     /// `FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE`. This allows
139     /// other processes to to read, write, and delete/rename the same file
140     /// while it is open. Removing any of the flags will prevent other
141     /// processes from performing the corresponding operation until the file
142     /// handle is closed.
143     ///
144     /// # Examples
145     ///
146     /// ```no_run
147     /// use std::fs::OpenOptions;
148     /// use std::os::windows::prelude::*;
149     ///
150     /// // Do not allow others to read or modify this file while we have it open
151     /// // for writing.
152     /// let file = OpenOptions::new()
153     ///     .write(true)
154     ///     .share_mode(0)
155     ///     .open("foo.txt");
156     /// ```
157     ///
158     /// [`CreateFile`]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858.aspx
159     #[stable(feature = "open_options_ext", since = "1.10.0")]
160     fn share_mode(&mut self, val: u32) -> &mut Self;
161
162     /// Sets extra flags for the `dwFileFlags` argument to the call to
163     /// [`CreateFile2`] to the specified value (or combines it with
164     /// `attributes` and `security_qos_flags` to set the `dwFlagsAndAttributes`
165     /// for [`CreateFile`]).
166     ///
167     /// Custom flags can only set flags, not remove flags set by Rust's options.
168     /// This option overwrites any previously set custom flags.
169     ///
170     /// # Examples
171     ///
172     /// ```ignore
173     /// extern crate winapi;
174     ///
175     /// use std::fs::OpenOptions;
176     /// use std::os::windows::prelude::*;
177     ///
178     /// let file = OpenOptions::new()
179     ///     .create(true)
180     ///     .write(true)
181     ///     .custom_flags(winapi::FILE_FLAG_DELETE_ON_CLOSE)
182     ///     .open("foo.txt");
183     /// ```
184     ///
185     /// [`CreateFile`]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858.aspx
186     /// [`CreateFile2`]: https://msdn.microsoft.com/en-us/library/windows/desktop/hh449422.aspx
187     #[stable(feature = "open_options_ext", since = "1.10.0")]
188     fn custom_flags(&mut self, flags: u32) -> &mut Self;
189
190     /// Sets the `dwFileAttributes` argument to the call to [`CreateFile2`] to
191     /// the specified value (or combines it with `custom_flags` and
192     /// `security_qos_flags` to set the `dwFlagsAndAttributes` for
193     /// [`CreateFile`]).
194     ///
195     /// If a _new_ file is created because it does not yet exist and
196     /// `.create(true)` or `.create_new(true)` are specified, the new file is
197     /// given the attributes declared with `.attributes()`.
198     ///
199     /// If an _existing_ file is opened with `.create(true).truncate(true)`, its
200     /// existing attributes are preserved and combined with the ones declared
201     /// with `.attributes()`.
202     ///
203     /// In all other cases the attributes get ignored.
204     ///
205     /// # Examples
206     ///
207     /// ```ignore
208     /// extern crate winapi;
209     ///
210     /// use std::fs::OpenOptions;
211     /// use std::os::windows::prelude::*;
212     ///
213     /// let file = OpenOptions::new()
214     ///     .write(true)
215     ///     .create(true)
216     ///     .attributes(winapi::FILE_ATTRIBUTE_HIDDEN)
217     ///     .open("foo.txt");
218     /// ```
219     ///
220     /// [`CreateFile`]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858.aspx
221     /// [`CreateFile2`]: https://msdn.microsoft.com/en-us/library/windows/desktop/hh449422.aspx
222     #[stable(feature = "open_options_ext", since = "1.10.0")]
223     fn attributes(&mut self, val: u32) -> &mut Self;
224
225     /// Sets the `dwSecurityQosFlags` argument to the call to [`CreateFile2`] to
226     /// the specified value (or combines it with `custom_flags` and `attributes`
227     /// to set the `dwFlagsAndAttributes` for [`CreateFile`]).
228     ///
229     /// By default, `security_qos_flags` is set to `SECURITY_ANONYMOUS`. For
230     /// information about possible values, see [Impersonation Levels] on the
231     /// Windows Dev Center site.
232     ///
233     /// # Examples
234     ///
235     /// ```no_run
236     /// use std::fs::OpenOptions;
237     /// use std::os::windows::prelude::*;
238     ///
239     /// let file = OpenOptions::new()
240     ///     .write(true)
241     ///     .create(true)
242     ///
243     ///     // Sets the flag value to `SecurityIdentification`.
244     ///     options.security_qos_flags(1)
245     ///
246     ///     .open("foo.txt");
247     /// ```
248     ///
249     /// [`CreateFile`]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858.aspx
250     /// [`CreateFile2`]: https://msdn.microsoft.com/en-us/library/windows/desktop/hh449422.aspx
251     /// [Impersonation Levels]:
252     ///     https://msdn.microsoft.com/en-us/library/windows/desktop/aa379572.aspx
253     #[stable(feature = "open_options_ext", since = "1.10.0")]
254     fn security_qos_flags(&mut self, flags: u32) -> &mut OpenOptions;
255 }
256
257 #[stable(feature = "open_options_ext", since = "1.10.0")]
258 impl OpenOptionsExt for OpenOptions {
259     fn access_mode(&mut self, access: u32) -> &mut OpenOptions {
260         self.as_inner_mut().access_mode(access); self
261     }
262
263     fn share_mode(&mut self, share: u32) -> &mut OpenOptions {
264         self.as_inner_mut().share_mode(share); self
265     }
266
267     fn custom_flags(&mut self, flags: u32) -> &mut OpenOptions {
268         self.as_inner_mut().custom_flags(flags); self
269     }
270
271     fn attributes(&mut self, attributes: u32) -> &mut OpenOptions {
272         self.as_inner_mut().attributes(attributes); self
273     }
274
275     fn security_qos_flags(&mut self, flags: u32) -> &mut OpenOptions {
276         self.as_inner_mut().security_qos_flags(flags); self
277     }
278 }
279
280 /// Extension methods for [`fs::Metadata`] to access the raw fields contained
281 /// within.
282 ///
283 /// The data members that this trait exposes correspond to the members
284 /// of the [`BY_HANDLE_FILE_INFORMATION`] structure.
285 ///
286 /// [`fs::Metadata`]: ../../../fs/struct.Metadata.html
287 /// [`BY_HANDLE_FILE_INFORMATION`]:
288 ///     https://msdn.microsoft.com/en-us/library/windows/desktop/aa363788.aspx
289 #[stable(feature = "metadata_ext", since = "1.1.0")]
290 pub trait MetadataExt {
291     /// Returns the value of the `dwFileAttributes` field of this metadata.
292     ///
293     /// This field contains the file system attribute information for a file
294     /// or directory. For possible values and their descriptions, see
295     /// [File Attribute Constants] in the Windows Dev Center.
296     ///
297     /// # Examples
298     ///
299     /// ```no_run
300     /// use std::io;
301     /// use std::fs;
302     /// use std::os::windows::prelude::*;
303     ///
304     /// # fn foo() -> io::Result<()> {
305     /// let metadata = fs::metadata("foo.txt")?;
306     /// let attributes = metadata.file_attributes();
307     /// # Ok(())
308     /// # }
309     /// ```
310     ///
311     /// [File Attribute Constants]:
312     ///     https://msdn.microsoft.com/en-us/library/windows/desktop/gg258117.aspx
313     #[stable(feature = "metadata_ext", since = "1.1.0")]
314     fn file_attributes(&self) -> u32;
315
316     /// Returns the value of the `ftCreationTime` field of this metadata.
317     ///
318     /// The returned 64-bit value is equivalent to a [`FILETIME`] struct,
319     /// which represents the number of 100-nanosecond intervals since
320     /// January 1, 1601 (UTC). The struct is automatically
321     /// converted to a `u64` value, as that is the recommended way
322     /// to use it.
323     ///
324     /// If the underlying filesystem does not support creation time, the
325     /// returned value is 0.
326     ///
327     /// # Examples
328     ///
329     /// ```no_run
330     /// use std::io;
331     /// use std::fs;
332     /// use std::os::windows::prelude::*;
333     ///
334     /// # fn foo() -> io::Result<()> {
335     /// let metadata = fs::metadata("foo.txt")?;
336     /// let creation_time = metadata.creation_time();
337     /// # Ok(())
338     /// # }
339     /// ```
340     ///
341     /// [`FILETIME`]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724284.aspx
342     #[stable(feature = "metadata_ext", since = "1.1.0")]
343     fn creation_time(&self) -> u64;
344
345     /// Returns the value of the `ftLastAccessTime` field of this metadata.
346     ///
347     /// The returned 64-bit value is equivalent to a [`FILETIME`] struct,
348     /// which represents the number of 100-nanosecond intervals since
349     /// January 1, 1601 (UTC). The struct is automatically
350     /// converted to a `u64` value, as that is the recommended way
351     /// to use it.
352     ///
353     /// For a file, the value specifies the last time that a file was read
354     /// from or written to. For a directory, the value specifies when
355     /// the directory was created. For both files and directories, the
356     /// specified date is correct, but the time of day is always set to
357     /// midnight.
358     ///
359     /// If the underlying filesystem does not support last access time, the
360     /// returned value is 0.
361     ///
362     /// # Examples
363     ///
364     /// ```no_run
365     /// use std::io;
366     /// use std::fs;
367     /// use std::os::windows::prelude::*;
368     ///
369     /// # fn foo() -> io::Result<()> {
370     /// let metadata = fs::metadata("foo.txt")?;
371     /// let last_access_time = metadata.last_access_time();
372     /// # Ok(())
373     /// # }
374     /// ```
375     ///
376     /// [`FILETIME`]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724284.aspx
377     #[stable(feature = "metadata_ext", since = "1.1.0")]
378     fn last_access_time(&self) -> u64;
379
380     /// Returns the value of the `ftLastWriteTime` field of this metadata.
381     ///
382     /// The returned 64-bit value is equivalent to a [`FILETIME`] struct,
383     /// which represents the number of 100-nanosecond intervals since
384     /// January 1, 1601 (UTC). The struct is automatically
385     /// converted to a `u64` value, as that is the recommended way
386     /// to use it.
387     ///
388     /// For a file, the value specifies the last time that a file was written
389     /// to. For a directory, the structure specifies when the directory was
390     /// created.
391     ///
392     /// If the underlying filesystem does not support the last write time
393     /// time, the returned value is 0.
394     ///
395     /// # Examples
396     ///
397     /// ```no_run
398     /// use std::io;
399     /// use std::fs;
400     /// use std::os::windows::prelude::*;
401     ///
402     /// # fn foo() -> io::Result<()> {
403     /// let metadata = fs::metadata("foo.txt")?;
404     /// let last_write_time = metadata.last_write_time();
405     /// # Ok(())
406     /// # }
407     /// ```
408     ///
409     /// [`FILETIME`]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724284.aspx
410     #[stable(feature = "metadata_ext", since = "1.1.0")]
411     fn last_write_time(&self) -> u64;
412
413     /// Returns the value of the `nFileSize{High,Low}` fields of this
414     /// metadata.
415     ///
416     /// The returned value does not have meaning for directories.
417     ///
418     /// # Examples
419     ///
420     /// ```no_run
421     /// use std::io;
422     /// use std::fs;
423     /// use std::os::windows::prelude::*;
424     ///
425     /// # fn foo() -> io::Result<()> {
426     /// let metadata = fs::metadata("foo.txt")?;
427     /// let file_size = metadata.file_size();
428     /// # Ok(())
429     /// # }
430     /// ```
431     #[stable(feature = "metadata_ext", since = "1.1.0")]
432     fn file_size(&self) -> u64;
433 }
434
435 #[stable(feature = "metadata_ext", since = "1.1.0")]
436 impl MetadataExt for Metadata {
437     fn file_attributes(&self) -> u32 { self.as_inner().attrs() }
438     fn creation_time(&self) -> u64 { self.as_inner().created_u64() }
439     fn last_access_time(&self) -> u64 { self.as_inner().accessed_u64() }
440     fn last_write_time(&self) -> u64 { self.as_inner().modified_u64() }
441     fn file_size(&self) -> u64 { self.as_inner().size() }
442 }
443
444 /// Creates a new file symbolic link on the filesystem.
445 ///
446 /// The `dst` path will be a file symbolic link pointing to the `src`
447 /// path.
448 ///
449 /// # Examples
450 ///
451 /// ```no_run
452 /// use std::os::windows::fs;
453 ///
454 /// # fn foo() -> std::io::Result<()> {
455 /// fs::symlink_file("a.txt", "b.txt")?;
456 /// # Ok(())
457 /// # }
458 /// ```
459 #[stable(feature = "symlink", since = "1.1.0")]
460 pub fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q)
461                                                     -> io::Result<()> {
462     sys::fs::symlink_inner(src.as_ref(), dst.as_ref(), false)
463 }
464
465 /// Creates a new directory symlink on the filesystem.
466 ///
467 /// The `dst` path will be a directory symbolic link pointing to the `src`
468 /// path.
469 ///
470 /// # Examples
471 ///
472 /// ```no_run
473 /// use std::os::windows::fs;
474 ///
475 /// # fn foo() -> std::io::Result<()> {
476 /// fs::symlink_file("a", "b")?;
477 /// # Ok(())
478 /// # }
479 /// ```
480 #[stable(feature = "symlink", since = "1.1.0")]
481 pub fn symlink_dir<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q)
482                                                    -> io::Result<()> {
483     sys::fs::symlink_inner(src.as_ref(), dst.as_ref(), true)
484 }