]> git.lizzy.rs Git - rust.git/blob - src/libstd/fs.rs
Rollup merge of #72761 - poliorcetics:use-keyword-doc, r=Dylan-DPC
[rust.git] / src / libstd / fs.rs
1 // ignore-tidy-filelength
2
3 //! Filesystem manipulation operations.
4 //!
5 //! This module contains basic methods to manipulate the contents of the local
6 //! filesystem. All methods in this module represent cross-platform filesystem
7 //! operations. Extra platform-specific functionality can be found in the
8 //! extension traits of `std::os::$platform`.
9
10 #![stable(feature = "rust1", since = "1.0.0")]
11
12 use crate::ffi::OsString;
13 use crate::fmt;
14 use crate::io::{self, Initializer, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write};
15 use crate::path::{Path, PathBuf};
16 use crate::sys::fs as fs_imp;
17 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
18 use crate::time::SystemTime;
19
20 /// A reference to an open file on the filesystem.
21 ///
22 /// An instance of a `File` can be read and/or written depending on what options
23 /// it was opened with. Files also implement [`Seek`] to alter the logical cursor
24 /// that the file contains internally.
25 ///
26 /// Files are automatically closed when they go out of scope.  Errors detected
27 /// on closing are ignored by the implementation of `Drop`.  Use the method
28 /// [`sync_all`] if these errors must be manually handled.
29 ///
30 /// # Examples
31 ///
32 /// Creates a new file and write bytes to it (you can also use [`write`]):
33 ///
34 /// ```no_run
35 /// use std::fs::File;
36 /// use std::io::prelude::*;
37 ///
38 /// fn main() -> std::io::Result<()> {
39 ///     let mut file = File::create("foo.txt")?;
40 ///     file.write_all(b"Hello, world!")?;
41 ///     Ok(())
42 /// }
43 /// ```
44 ///
45 /// Read the contents of a file into a [`String`] (you can also use [`read`]):
46 ///
47 /// ```no_run
48 /// use std::fs::File;
49 /// use std::io::prelude::*;
50 ///
51 /// fn main() -> std::io::Result<()> {
52 ///     let mut file = File::open("foo.txt")?;
53 ///     let mut contents = String::new();
54 ///     file.read_to_string(&mut contents)?;
55 ///     assert_eq!(contents, "Hello, world!");
56 ///     Ok(())
57 /// }
58 /// ```
59 ///
60 /// It can be more efficient to read the contents of a file with a buffered
61 /// [`Read`]er. This can be accomplished with [`BufReader<R>`]:
62 ///
63 /// ```no_run
64 /// use std::fs::File;
65 /// use std::io::BufReader;
66 /// use std::io::prelude::*;
67 ///
68 /// fn main() -> std::io::Result<()> {
69 ///     let file = File::open("foo.txt")?;
70 ///     let mut buf_reader = BufReader::new(file);
71 ///     let mut contents = String::new();
72 ///     buf_reader.read_to_string(&mut contents)?;
73 ///     assert_eq!(contents, "Hello, world!");
74 ///     Ok(())
75 /// }
76 /// ```
77 ///
78 /// Note that, although read and write methods require a `&mut File`, because
79 /// of the interfaces for [`Read`] and [`Write`], the holder of a `&File` can
80 /// still modify the file, either through methods that take `&File` or by
81 /// retrieving the underlying OS object and modifying the file that way.
82 /// Additionally, many operating systems allow concurrent modification of files
83 /// by different processes. Avoid assuming that holding a `&File` means that the
84 /// file will not change.
85 ///
86 /// [`Seek`]: ../io/trait.Seek.html
87 /// [`String`]: ../string/struct.String.html
88 /// [`Read`]: ../io/trait.Read.html
89 /// [`Write`]: ../io/trait.Write.html
90 /// [`BufReader<R>`]: ../io/struct.BufReader.html
91 /// [`sync_all`]: struct.File.html#method.sync_all
92 /// [`read`]: fn.read.html
93 /// [`write`]: fn.write.html
94 #[stable(feature = "rust1", since = "1.0.0")]
95 pub struct File {
96     inner: fs_imp::File,
97 }
98
99 /// Metadata information about a file.
100 ///
101 /// This structure is returned from the [`metadata`] or
102 /// [`symlink_metadata`] function or method and represents known
103 /// metadata about a file such as its permissions, size, modification
104 /// times, etc.
105 ///
106 /// [`metadata`]: fn.metadata.html
107 /// [`symlink_metadata`]: fn.symlink_metadata.html
108 #[stable(feature = "rust1", since = "1.0.0")]
109 #[derive(Clone)]
110 pub struct Metadata(fs_imp::FileAttr);
111
112 /// Iterator over the entries in a directory.
113 ///
114 /// This iterator is returned from the [`read_dir`] function of this module and
115 /// will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. Through a [`DirEntry`]
116 /// information like the entry's path and possibly other metadata can be
117 /// learned.
118 ///
119 /// The order in which this iterator returns entries is platform and filesystem
120 /// dependent.
121 ///
122 /// # Errors
123 ///
124 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
125 /// IO error during iteration.
126 ///
127 /// [`read_dir`]: fn.read_dir.html
128 /// [`DirEntry`]: struct.DirEntry.html
129 /// [`io::Result`]: ../io/type.Result.html
130 /// [`Err`]: ../result/enum.Result.html#variant.Err
131 #[stable(feature = "rust1", since = "1.0.0")]
132 #[derive(Debug)]
133 pub struct ReadDir(fs_imp::ReadDir);
134
135 /// Entries returned by the [`ReadDir`] iterator.
136 ///
137 /// [`ReadDir`]: struct.ReadDir.html
138 ///
139 /// An instance of `DirEntry` represents an entry inside of a directory on the
140 /// filesystem. Each entry can be inspected via methods to learn about the full
141 /// path or possibly other metadata through per-platform extension traits.
142 #[stable(feature = "rust1", since = "1.0.0")]
143 pub struct DirEntry(fs_imp::DirEntry);
144
145 /// Options and flags which can be used to configure how a file is opened.
146 ///
147 /// This builder exposes the ability to configure how a [`File`] is opened and
148 /// what operations are permitted on the open file. The [`File::open`] and
149 /// [`File::create`] methods are aliases for commonly used options using this
150 /// builder.
151 ///
152 /// [`File`]: struct.File.html
153 /// [`File::open`]: struct.File.html#method.open
154 /// [`File::create`]: struct.File.html#method.create
155 ///
156 /// Generally speaking, when using `OpenOptions`, you'll first call [`new`],
157 /// then chain calls to methods to set each option, then call [`open`],
158 /// passing the path of the file you're trying to open. This will give you a
159 /// [`io::Result`][result] with a [`File`][file] inside that you can further
160 /// operate on.
161 ///
162 /// [`new`]: struct.OpenOptions.html#method.new
163 /// [`open`]: struct.OpenOptions.html#method.open
164 /// [result]: ../io/type.Result.html
165 /// [file]: struct.File.html
166 ///
167 /// # Examples
168 ///
169 /// Opening a file to read:
170 ///
171 /// ```no_run
172 /// use std::fs::OpenOptions;
173 ///
174 /// let file = OpenOptions::new().read(true).open("foo.txt");
175 /// ```
176 ///
177 /// Opening a file for both reading and writing, as well as creating it if it
178 /// doesn't exist:
179 ///
180 /// ```no_run
181 /// use std::fs::OpenOptions;
182 ///
183 /// let file = OpenOptions::new()
184 ///             .read(true)
185 ///             .write(true)
186 ///             .create(true)
187 ///             .open("foo.txt");
188 /// ```
189 #[derive(Clone, Debug)]
190 #[stable(feature = "rust1", since = "1.0.0")]
191 pub struct OpenOptions(fs_imp::OpenOptions);
192
193 /// Representation of the various permissions on a file.
194 ///
195 /// This module only currently provides one bit of information, [`readonly`],
196 /// which is exposed on all currently supported platforms. Unix-specific
197 /// functionality, such as mode bits, is available through the
198 /// [`PermissionsExt`] trait.
199 ///
200 /// [`readonly`]: struct.Permissions.html#method.readonly
201 /// [`PermissionsExt`]: ../os/unix/fs/trait.PermissionsExt.html
202 #[derive(Clone, PartialEq, Eq, Debug)]
203 #[stable(feature = "rust1", since = "1.0.0")]
204 pub struct Permissions(fs_imp::FilePermissions);
205
206 /// A structure representing a type of file with accessors for each file type.
207 /// It is returned by [`Metadata::file_type`] method.
208 ///
209 /// [`Metadata::file_type`]: struct.Metadata.html#method.file_type
210 #[stable(feature = "file_type", since = "1.1.0")]
211 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
212 pub struct FileType(fs_imp::FileType);
213
214 /// A builder used to create directories in various manners.
215 ///
216 /// This builder also supports platform-specific options.
217 #[stable(feature = "dir_builder", since = "1.6.0")]
218 #[derive(Debug)]
219 pub struct DirBuilder {
220     inner: fs_imp::DirBuilder,
221     recursive: bool,
222 }
223
224 /// Indicates how large a buffer to pre-allocate before reading the entire file.
225 fn initial_buffer_size(file: &File) -> usize {
226     // Allocate one extra byte so the buffer doesn't need to grow before the
227     // final `read` call at the end of the file.  Don't worry about `usize`
228     // overflow because reading will fail regardless in that case.
229     file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0)
230 }
231
232 /// Read the entire contents of a file into a bytes vector.
233 ///
234 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
235 /// with fewer imports and without an intermediate variable. It pre-allocates a
236 /// buffer based on the file size when available, so it is generally faster than
237 /// reading into a vector created with `Vec::new()`.
238 ///
239 /// [`File::open`]: struct.File.html#method.open
240 /// [`read_to_end`]: ../io/trait.Read.html#method.read_to_end
241 ///
242 /// # Errors
243 ///
244 /// This function will return an error if `path` does not already exist.
245 /// Other errors may also be returned according to [`OpenOptions::open`].
246 ///
247 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
248 ///
249 /// It will also return an error if it encounters while reading an error
250 /// of a kind other than [`ErrorKind::Interrupted`].
251 ///
252 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
253 ///
254 /// # Examples
255 ///
256 /// ```no_run
257 /// use std::fs;
258 /// use std::net::SocketAddr;
259 ///
260 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
261 ///     let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
262 ///     Ok(())
263 /// }
264 /// ```
265 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
266 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
267     fn inner(path: &Path) -> io::Result<Vec<u8>> {
268         let mut file = File::open(path)?;
269         let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
270         file.read_to_end(&mut bytes)?;
271         Ok(bytes)
272     }
273     inner(path.as_ref())
274 }
275
276 /// Read the entire contents of a file into a string.
277 ///
278 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
279 /// with fewer imports and without an intermediate variable. It pre-allocates a
280 /// buffer based on the file size when available, so it is generally faster than
281 /// reading into a string created with `String::new()`.
282 ///
283 /// [`File::open`]: struct.File.html#method.open
284 /// [`read_to_string`]: ../io/trait.Read.html#method.read_to_string
285 ///
286 /// # Errors
287 ///
288 /// This function will return an error if `path` does not already exist.
289 /// Other errors may also be returned according to [`OpenOptions::open`].
290 ///
291 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
292 ///
293 /// It will also return an error if it encounters while reading an error
294 /// of a kind other than [`ErrorKind::Interrupted`],
295 /// or if the contents of the file are not valid UTF-8.
296 ///
297 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
298 ///
299 /// # Examples
300 ///
301 /// ```no_run
302 /// use std::fs;
303 /// use std::net::SocketAddr;
304 ///
305 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
306 ///     let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
307 ///     Ok(())
308 /// }
309 /// ```
310 #[stable(feature = "fs_read_write", since = "1.26.0")]
311 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
312     fn inner(path: &Path) -> io::Result<String> {
313         let mut file = File::open(path)?;
314         let mut string = String::with_capacity(initial_buffer_size(&file));
315         file.read_to_string(&mut string)?;
316         Ok(string)
317     }
318     inner(path.as_ref())
319 }
320
321 /// Write a slice as the entire contents of a file.
322 ///
323 /// This function will create a file if it does not exist,
324 /// and will entirely replace its contents if it does.
325 ///
326 /// This is a convenience function for using [`File::create`] and [`write_all`]
327 /// with fewer imports.
328 ///
329 /// [`File::create`]: struct.File.html#method.create
330 /// [`write_all`]: ../io/trait.Write.html#method.write_all
331 ///
332 /// # Examples
333 ///
334 /// ```no_run
335 /// use std::fs;
336 ///
337 /// fn main() -> std::io::Result<()> {
338 ///     fs::write("foo.txt", b"Lorem ipsum")?;
339 ///     fs::write("bar.txt", "dolor sit")?;
340 ///     Ok(())
341 /// }
342 /// ```
343 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
344 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
345     fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
346         File::create(path)?.write_all(contents)
347     }
348     inner(path.as_ref(), contents.as_ref())
349 }
350
351 impl File {
352     /// Attempts to open a file in read-only mode.
353     ///
354     /// See the [`OpenOptions::open`] method for more details.
355     ///
356     /// # Errors
357     ///
358     /// This function will return an error if `path` does not already exist.
359     /// Other errors may also be returned according to [`OpenOptions::open`].
360     ///
361     /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
362     ///
363     /// # Examples
364     ///
365     /// ```no_run
366     /// use std::fs::File;
367     ///
368     /// fn main() -> std::io::Result<()> {
369     ///     let mut f = File::open("foo.txt")?;
370     ///     Ok(())
371     /// }
372     /// ```
373     #[stable(feature = "rust1", since = "1.0.0")]
374     pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
375         OpenOptions::new().read(true).open(path.as_ref())
376     }
377
378     /// Opens a file in write-only mode.
379     ///
380     /// This function will create a file if it does not exist,
381     /// and will truncate it if it does.
382     ///
383     /// See the [`OpenOptions::open`] function for more details.
384     ///
385     /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
386     ///
387     /// # Examples
388     ///
389     /// ```no_run
390     /// use std::fs::File;
391     ///
392     /// fn main() -> std::io::Result<()> {
393     ///     let mut f = File::create("foo.txt")?;
394     ///     Ok(())
395     /// }
396     /// ```
397     #[stable(feature = "rust1", since = "1.0.0")]
398     pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
399         OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
400     }
401
402     /// Returns a new OpenOptions object.
403     ///
404     /// This function returns a new OpenOptions object that you can use to
405     /// open or create a file with specific options if `open()` or `create()`
406     /// are not appropriate.
407     ///
408     /// It is equivalent to `OpenOptions::new()` but allows you to write more
409     /// readable code. Instead of `OpenOptions::new().read(true).open("foo.txt")`
410     /// you can write `File::with_options().read(true).open("foo.txt")`. This
411     /// also avoids the need to import `OpenOptions`.
412     ///
413     /// See the [`OpenOptions::new`] function for more details.
414     ///
415     /// [`OpenOptions::new`]: struct.OpenOptions.html#method.new
416     ///
417     /// # Examples
418     ///
419     /// ```no_run
420     /// #![feature(with_options)]
421     /// use std::fs::File;
422     ///
423     /// fn main() -> std::io::Result<()> {
424     ///     let mut f = File::with_options().read(true).open("foo.txt")?;
425     ///     Ok(())
426     /// }
427     /// ```
428     #[unstable(feature = "with_options", issue = "65439")]
429     pub fn with_options() -> OpenOptions {
430         OpenOptions::new()
431     }
432
433     /// Attempts to sync all OS-internal metadata to disk.
434     ///
435     /// This function will attempt to ensure that all in-memory data reaches the
436     /// filesystem before returning.
437     ///
438     /// This can be used to handle errors that would otherwise only be caught
439     /// when the `File` is closed.  Dropping a file will ignore errors in
440     /// synchronizing this in-memory data.
441     ///
442     /// # Examples
443     ///
444     /// ```no_run
445     /// use std::fs::File;
446     /// use std::io::prelude::*;
447     ///
448     /// fn main() -> std::io::Result<()> {
449     ///     let mut f = File::create("foo.txt")?;
450     ///     f.write_all(b"Hello, world!")?;
451     ///
452     ///     f.sync_all()?;
453     ///     Ok(())
454     /// }
455     /// ```
456     #[stable(feature = "rust1", since = "1.0.0")]
457     pub fn sync_all(&self) -> io::Result<()> {
458         self.inner.fsync()
459     }
460
461     /// This function is similar to [`sync_all`], except that it may not
462     /// synchronize file metadata to the filesystem.
463     ///
464     /// This is intended for use cases that must synchronize content, but don't
465     /// need the metadata on disk. The goal of this method is to reduce disk
466     /// operations.
467     ///
468     /// Note that some platforms may simply implement this in terms of
469     /// [`sync_all`].
470     ///
471     /// [`sync_all`]: struct.File.html#method.sync_all
472     ///
473     /// # Examples
474     ///
475     /// ```no_run
476     /// use std::fs::File;
477     /// use std::io::prelude::*;
478     ///
479     /// fn main() -> std::io::Result<()> {
480     ///     let mut f = File::create("foo.txt")?;
481     ///     f.write_all(b"Hello, world!")?;
482     ///
483     ///     f.sync_data()?;
484     ///     Ok(())
485     /// }
486     /// ```
487     #[stable(feature = "rust1", since = "1.0.0")]
488     pub fn sync_data(&self) -> io::Result<()> {
489         self.inner.datasync()
490     }
491
492     /// Truncates or extends the underlying file, updating the size of
493     /// this file to become `size`.
494     ///
495     /// If the `size` is less than the current file's size, then the file will
496     /// be shrunk. If it is greater than the current file's size, then the file
497     /// will be extended to `size` and have all of the intermediate data filled
498     /// in with 0s.
499     ///
500     /// The file's cursor isn't changed. In particular, if the cursor was at the
501     /// end and the file is shrunk using this operation, the cursor will now be
502     /// past the end.
503     ///
504     /// # Errors
505     ///
506     /// This function will return an error if the file is not opened for writing.
507     /// Also, std::io::ErrorKind::InvalidInput will be returned if the desired
508     /// length would cause an overflow due to the implementation specifics.
509     ///
510     /// # Examples
511     ///
512     /// ```no_run
513     /// use std::fs::File;
514     ///
515     /// fn main() -> std::io::Result<()> {
516     ///     let mut f = File::create("foo.txt")?;
517     ///     f.set_len(10)?;
518     ///     Ok(())
519     /// }
520     /// ```
521     ///
522     /// Note that this method alters the content of the underlying file, even
523     /// though it takes `&self` rather than `&mut self`.
524     #[stable(feature = "rust1", since = "1.0.0")]
525     pub fn set_len(&self, size: u64) -> io::Result<()> {
526         self.inner.truncate(size)
527     }
528
529     /// Queries metadata about the underlying file.
530     ///
531     /// # Examples
532     ///
533     /// ```no_run
534     /// use std::fs::File;
535     ///
536     /// fn main() -> std::io::Result<()> {
537     ///     let mut f = File::open("foo.txt")?;
538     ///     let metadata = f.metadata()?;
539     ///     Ok(())
540     /// }
541     /// ```
542     #[stable(feature = "rust1", since = "1.0.0")]
543     pub fn metadata(&self) -> io::Result<Metadata> {
544         self.inner.file_attr().map(Metadata)
545     }
546
547     /// Creates a new `File` instance that shares the same underlying file handle
548     /// as the existing `File` instance. Reads, writes, and seeks will affect
549     /// both `File` instances simultaneously.
550     ///
551     /// # Examples
552     ///
553     /// Creates two handles for a file named `foo.txt`:
554     ///
555     /// ```no_run
556     /// use std::fs::File;
557     ///
558     /// fn main() -> std::io::Result<()> {
559     ///     let mut file = File::open("foo.txt")?;
560     ///     let file_copy = file.try_clone()?;
561     ///     Ok(())
562     /// }
563     /// ```
564     ///
565     /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
566     /// two handles, seek one of them, and read the remaining bytes from the
567     /// other handle:
568     ///
569     /// ```no_run
570     /// use std::fs::File;
571     /// use std::io::SeekFrom;
572     /// use std::io::prelude::*;
573     ///
574     /// fn main() -> std::io::Result<()> {
575     ///     let mut file = File::open("foo.txt")?;
576     ///     let mut file_copy = file.try_clone()?;
577     ///
578     ///     file.seek(SeekFrom::Start(3))?;
579     ///
580     ///     let mut contents = vec![];
581     ///     file_copy.read_to_end(&mut contents)?;
582     ///     assert_eq!(contents, b"def\n");
583     ///     Ok(())
584     /// }
585     /// ```
586     #[stable(feature = "file_try_clone", since = "1.9.0")]
587     pub fn try_clone(&self) -> io::Result<File> {
588         Ok(File { inner: self.inner.duplicate()? })
589     }
590
591     /// Changes the permissions on the underlying file.
592     ///
593     /// # Platform-specific behavior
594     ///
595     /// This function currently corresponds to the `fchmod` function on Unix and
596     /// the `SetFileInformationByHandle` function on Windows. Note that, this
597     /// [may change in the future][changes].
598     ///
599     /// [changes]: ../io/index.html#platform-specific-behavior
600     ///
601     /// # Errors
602     ///
603     /// This function will return an error if the user lacks permission change
604     /// attributes on the underlying file. It may also return an error in other
605     /// os-specific unspecified cases.
606     ///
607     /// # Examples
608     ///
609     /// ```no_run
610     /// fn main() -> std::io::Result<()> {
611     ///     use std::fs::File;
612     ///
613     ///     let file = File::open("foo.txt")?;
614     ///     let mut perms = file.metadata()?.permissions();
615     ///     perms.set_readonly(true);
616     ///     file.set_permissions(perms)?;
617     ///     Ok(())
618     /// }
619     /// ```
620     ///
621     /// Note that this method alters the permissions of the underlying file,
622     /// even though it takes `&self` rather than `&mut self`.
623     #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
624     pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
625         self.inner.set_permissions(perm.0)
626     }
627 }
628
629 impl AsInner<fs_imp::File> for File {
630     fn as_inner(&self) -> &fs_imp::File {
631         &self.inner
632     }
633 }
634 impl FromInner<fs_imp::File> for File {
635     fn from_inner(f: fs_imp::File) -> File {
636         File { inner: f }
637     }
638 }
639 impl IntoInner<fs_imp::File> for File {
640     fn into_inner(self) -> fs_imp::File {
641         self.inner
642     }
643 }
644
645 #[stable(feature = "rust1", since = "1.0.0")]
646 impl fmt::Debug for File {
647     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
648         self.inner.fmt(f)
649     }
650 }
651
652 #[stable(feature = "rust1", since = "1.0.0")]
653 impl Read for File {
654     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
655         self.inner.read(buf)
656     }
657
658     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
659         self.inner.read_vectored(bufs)
660     }
661
662     #[inline]
663     fn is_read_vectored(&self) -> bool {
664         self.inner.is_read_vectored()
665     }
666
667     #[inline]
668     unsafe fn initializer(&self) -> Initializer {
669         Initializer::nop()
670     }
671 }
672 #[stable(feature = "rust1", since = "1.0.0")]
673 impl Write for File {
674     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
675         self.inner.write(buf)
676     }
677
678     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
679         self.inner.write_vectored(bufs)
680     }
681
682     #[inline]
683     fn is_write_vectored(&self) -> bool {
684         self.inner.is_write_vectored()
685     }
686
687     fn flush(&mut self) -> io::Result<()> {
688         self.inner.flush()
689     }
690 }
691 #[stable(feature = "rust1", since = "1.0.0")]
692 impl Seek for File {
693     fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
694         self.inner.seek(pos)
695     }
696 }
697 #[stable(feature = "rust1", since = "1.0.0")]
698 impl Read for &File {
699     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
700         self.inner.read(buf)
701     }
702
703     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
704         self.inner.read_vectored(bufs)
705     }
706
707     #[inline]
708     fn is_read_vectored(&self) -> bool {
709         self.inner.is_read_vectored()
710     }
711
712     #[inline]
713     unsafe fn initializer(&self) -> Initializer {
714         Initializer::nop()
715     }
716 }
717 #[stable(feature = "rust1", since = "1.0.0")]
718 impl Write for &File {
719     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
720         self.inner.write(buf)
721     }
722
723     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
724         self.inner.write_vectored(bufs)
725     }
726
727     #[inline]
728     fn is_write_vectored(&self) -> bool {
729         self.inner.is_write_vectored()
730     }
731
732     fn flush(&mut self) -> io::Result<()> {
733         self.inner.flush()
734     }
735 }
736 #[stable(feature = "rust1", since = "1.0.0")]
737 impl Seek for &File {
738     fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
739         self.inner.seek(pos)
740     }
741 }
742
743 impl OpenOptions {
744     /// Creates a blank new set of options ready for configuration.
745     ///
746     /// All options are initially set to `false`.
747     ///
748     /// # Examples
749     ///
750     /// ```no_run
751     /// use std::fs::OpenOptions;
752     ///
753     /// let mut options = OpenOptions::new();
754     /// let file = options.read(true).open("foo.txt");
755     /// ```
756     #[stable(feature = "rust1", since = "1.0.0")]
757     pub fn new() -> Self {
758         OpenOptions(fs_imp::OpenOptions::new())
759     }
760
761     /// Sets the option for read access.
762     ///
763     /// This option, when true, will indicate that the file should be
764     /// `read`-able if opened.
765     ///
766     /// # Examples
767     ///
768     /// ```no_run
769     /// use std::fs::OpenOptions;
770     ///
771     /// let file = OpenOptions::new().read(true).open("foo.txt");
772     /// ```
773     #[stable(feature = "rust1", since = "1.0.0")]
774     pub fn read(&mut self, read: bool) -> &mut Self {
775         self.0.read(read);
776         self
777     }
778
779     /// Sets the option for write access.
780     ///
781     /// This option, when true, will indicate that the file should be
782     /// `write`-able if opened.
783     ///
784     /// If the file already exists, any write calls on it will overwrite its
785     /// contents, without truncating it.
786     ///
787     /// # Examples
788     ///
789     /// ```no_run
790     /// use std::fs::OpenOptions;
791     ///
792     /// let file = OpenOptions::new().write(true).open("foo.txt");
793     /// ```
794     #[stable(feature = "rust1", since = "1.0.0")]
795     pub fn write(&mut self, write: bool) -> &mut Self {
796         self.0.write(write);
797         self
798     }
799
800     /// Sets the option for the append mode.
801     ///
802     /// This option, when true, means that writes will append to a file instead
803     /// of overwriting previous contents.
804     /// Note that setting `.write(true).append(true)` has the same effect as
805     /// setting only `.append(true)`.
806     ///
807     /// For most filesystems, the operating system guarantees that all writes are
808     /// atomic: no writes get mangled because another process writes at the same
809     /// time.
810     ///
811     /// One maybe obvious note when using append-mode: make sure that all data
812     /// that belongs together is written to the file in one operation. This
813     /// can be done by concatenating strings before passing them to [`write()`],
814     /// or using a buffered writer (with a buffer of adequate size),
815     /// and calling [`flush()`] when the message is complete.
816     ///
817     /// If a file is opened with both read and append access, beware that after
818     /// opening, and after every write, the position for reading may be set at the
819     /// end of the file. So, before writing, save the current position (using
820     /// [`seek`]`(`[`SeekFrom`]`::`[`Current`]`(0))`), and restore it before the next read.
821     ///
822     /// ## Note
823     ///
824     /// This function doesn't create the file if it doesn't exist. Use the [`create`]
825     /// method to do so.
826     ///
827     /// [`write()`]: ../../std/fs/struct.File.html#method.write
828     /// [`flush()`]: ../../std/fs/struct.File.html#method.flush
829     /// [`seek`]: ../../std/fs/struct.File.html#method.seek
830     /// [`SeekFrom`]: ../../std/io/enum.SeekFrom.html
831     /// [`Current`]: ../../std/io/enum.SeekFrom.html#variant.Current
832     /// [`create`]: #method.create
833     ///
834     /// # Examples
835     ///
836     /// ```no_run
837     /// use std::fs::OpenOptions;
838     ///
839     /// let file = OpenOptions::new().append(true).open("foo.txt");
840     /// ```
841     #[stable(feature = "rust1", since = "1.0.0")]
842     pub fn append(&mut self, append: bool) -> &mut Self {
843         self.0.append(append);
844         self
845     }
846
847     /// Sets the option for truncating a previous file.
848     ///
849     /// If a file is successfully opened with this option set it will truncate
850     /// the file to 0 length if it already exists.
851     ///
852     /// The file must be opened with write access for truncate to work.
853     ///
854     /// # Examples
855     ///
856     /// ```no_run
857     /// use std::fs::OpenOptions;
858     ///
859     /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
860     /// ```
861     #[stable(feature = "rust1", since = "1.0.0")]
862     pub fn truncate(&mut self, truncate: bool) -> &mut Self {
863         self.0.truncate(truncate);
864         self
865     }
866
867     /// Sets the option to create a new file, or open it if it already exists.
868     ///
869     /// In order for the file to be created, [`write`] or [`append`] access must
870     /// be used.
871     ///
872     /// [`write`]: #method.write
873     /// [`append`]: #method.append
874     ///
875     /// # Examples
876     ///
877     /// ```no_run
878     /// use std::fs::OpenOptions;
879     ///
880     /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
881     /// ```
882     #[stable(feature = "rust1", since = "1.0.0")]
883     pub fn create(&mut self, create: bool) -> &mut Self {
884         self.0.create(create);
885         self
886     }
887
888     /// Sets the option to create a new file, failing if it already exists.
889     ///
890     /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
891     /// way, if the call succeeds, the file returned is guaranteed to be new.
892     ///
893     /// This option is useful because it is atomic. Otherwise between checking
894     /// whether a file exists and creating a new one, the file may have been
895     /// created by another process (a TOCTOU race condition / attack).
896     ///
897     /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
898     /// ignored.
899     ///
900     /// The file must be opened with write or append access in order to create
901     /// a new file.
902     ///
903     /// [`.create()`]: #method.create
904     /// [`.truncate()`]: #method.truncate
905     ///
906     /// # Examples
907     ///
908     /// ```no_run
909     /// use std::fs::OpenOptions;
910     ///
911     /// let file = OpenOptions::new().write(true)
912     ///                              .create_new(true)
913     ///                              .open("foo.txt");
914     /// ```
915     #[stable(feature = "expand_open_options2", since = "1.9.0")]
916     pub fn create_new(&mut self, create_new: bool) -> &mut Self {
917         self.0.create_new(create_new);
918         self
919     }
920
921     /// Opens a file at `path` with the options specified by `self`.
922     ///
923     /// # Errors
924     ///
925     /// This function will return an error under a number of different
926     /// circumstances. Some of these error conditions are listed here, together
927     /// with their [`ErrorKind`]. The mapping to [`ErrorKind`]s is not part of
928     /// the compatibility contract of the function, especially the `Other` kind
929     /// might change to more specific kinds in the future.
930     ///
931     /// * [`NotFound`]: The specified file does not exist and neither `create`
932     ///   or `create_new` is set.
933     /// * [`NotFound`]: One of the directory components of the file path does
934     ///   not exist.
935     /// * [`PermissionDenied`]: The user lacks permission to get the specified
936     ///   access rights for the file.
937     /// * [`PermissionDenied`]: The user lacks permission to open one of the
938     ///   directory components of the specified path.
939     /// * [`AlreadyExists`]: `create_new` was specified and the file already
940     ///   exists.
941     /// * [`InvalidInput`]: Invalid combinations of open options (truncate
942     ///   without write access, no access mode set, etc.).
943     /// * [`Other`]: One of the directory components of the specified file path
944     ///   was not, in fact, a directory.
945     /// * [`Other`]: Filesystem-level errors: full disk, write permission
946     ///   requested on a read-only file system, exceeded disk quota, too many
947     ///   open files, too long filename, too many symbolic links in the
948     ///   specified path (Unix-like systems only), etc.
949     ///
950     /// # Examples
951     ///
952     /// ```no_run
953     /// use std::fs::OpenOptions;
954     ///
955     /// let file = OpenOptions::new().read(true).open("foo.txt");
956     /// ```
957     ///
958     /// [`ErrorKind`]: ../io/enum.ErrorKind.html
959     /// [`AlreadyExists`]: ../io/enum.ErrorKind.html#variant.AlreadyExists
960     /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
961     /// [`NotFound`]: ../io/enum.ErrorKind.html#variant.NotFound
962     /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
963     /// [`PermissionDenied`]: ../io/enum.ErrorKind.html#variant.PermissionDenied
964     #[stable(feature = "rust1", since = "1.0.0")]
965     pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
966         self._open(path.as_ref())
967     }
968
969     fn _open(&self, path: &Path) -> io::Result<File> {
970         fs_imp::File::open(path, &self.0).map(|inner| File { inner })
971     }
972 }
973
974 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
975     fn as_inner(&self) -> &fs_imp::OpenOptions {
976         &self.0
977     }
978 }
979
980 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
981     fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
982         &mut self.0
983     }
984 }
985
986 impl Metadata {
987     /// Returns the file type for this metadata.
988     ///
989     /// # Examples
990     ///
991     /// ```no_run
992     /// fn main() -> std::io::Result<()> {
993     ///     use std::fs;
994     ///
995     ///     let metadata = fs::metadata("foo.txt")?;
996     ///
997     ///     println!("{:?}", metadata.file_type());
998     ///     Ok(())
999     /// }
1000     /// ```
1001     #[stable(feature = "file_type", since = "1.1.0")]
1002     pub fn file_type(&self) -> FileType {
1003         FileType(self.0.file_type())
1004     }
1005
1006     /// Returns `true` if this metadata is for a directory. The
1007     /// result is mutually exclusive to the result of
1008     /// [`is_file`], and will be false for symlink metadata
1009     /// obtained from [`symlink_metadata`].
1010     ///
1011     /// [`is_file`]: struct.Metadata.html#method.is_file
1012     /// [`symlink_metadata`]: fn.symlink_metadata.html
1013     ///
1014     /// # Examples
1015     ///
1016     /// ```no_run
1017     /// fn main() -> std::io::Result<()> {
1018     ///     use std::fs;
1019     ///
1020     ///     let metadata = fs::metadata("foo.txt")?;
1021     ///
1022     ///     assert!(!metadata.is_dir());
1023     ///     Ok(())
1024     /// }
1025     /// ```
1026     #[stable(feature = "rust1", since = "1.0.0")]
1027     pub fn is_dir(&self) -> bool {
1028         self.file_type().is_dir()
1029     }
1030
1031     /// Returns `true` if this metadata is for a regular file. The
1032     /// result is mutually exclusive to the result of
1033     /// [`is_dir`], and will be false for symlink metadata
1034     /// obtained from [`symlink_metadata`].
1035     ///
1036     /// [`is_dir`]: struct.Metadata.html#method.is_dir
1037     /// [`symlink_metadata`]: fn.symlink_metadata.html
1038     ///
1039     /// # Examples
1040     ///
1041     /// ```no_run
1042     /// use std::fs;
1043     ///
1044     /// fn main() -> std::io::Result<()> {
1045     ///     let metadata = fs::metadata("foo.txt")?;
1046     ///
1047     ///     assert!(metadata.is_file());
1048     ///     Ok(())
1049     /// }
1050     /// ```
1051     #[stable(feature = "rust1", since = "1.0.0")]
1052     pub fn is_file(&self) -> bool {
1053         self.file_type().is_file()
1054     }
1055
1056     /// Returns the size of the file, in bytes, this metadata is for.
1057     ///
1058     /// # Examples
1059     ///
1060     /// ```no_run
1061     /// use std::fs;
1062     ///
1063     /// fn main() -> std::io::Result<()> {
1064     ///     let metadata = fs::metadata("foo.txt")?;
1065     ///
1066     ///     assert_eq!(0, metadata.len());
1067     ///     Ok(())
1068     /// }
1069     /// ```
1070     #[stable(feature = "rust1", since = "1.0.0")]
1071     pub fn len(&self) -> u64 {
1072         self.0.size()
1073     }
1074
1075     /// Returns the permissions of the file this metadata is for.
1076     ///
1077     /// # Examples
1078     ///
1079     /// ```no_run
1080     /// use std::fs;
1081     ///
1082     /// fn main() -> std::io::Result<()> {
1083     ///     let metadata = fs::metadata("foo.txt")?;
1084     ///
1085     ///     assert!(!metadata.permissions().readonly());
1086     ///     Ok(())
1087     /// }
1088     /// ```
1089     #[stable(feature = "rust1", since = "1.0.0")]
1090     pub fn permissions(&self) -> Permissions {
1091         Permissions(self.0.perm())
1092     }
1093
1094     /// Returns the last modification time listed in this metadata.
1095     ///
1096     /// The returned value corresponds to the `mtime` field of `stat` on Unix
1097     /// platforms and the `ftLastWriteTime` field on Windows platforms.
1098     ///
1099     /// # Errors
1100     ///
1101     /// This field may not be available on all platforms, and will return an
1102     /// `Err` on platforms where it is not available.
1103     ///
1104     /// # Examples
1105     ///
1106     /// ```no_run
1107     /// use std::fs;
1108     ///
1109     /// fn main() -> std::io::Result<()> {
1110     ///     let metadata = fs::metadata("foo.txt")?;
1111     ///
1112     ///     if let Ok(time) = metadata.modified() {
1113     ///         println!("{:?}", time);
1114     ///     } else {
1115     ///         println!("Not supported on this platform");
1116     ///     }
1117     ///     Ok(())
1118     /// }
1119     /// ```
1120     #[stable(feature = "fs_time", since = "1.10.0")]
1121     pub fn modified(&self) -> io::Result<SystemTime> {
1122         self.0.modified().map(FromInner::from_inner)
1123     }
1124
1125     /// Returns the last access time of this metadata.
1126     ///
1127     /// The returned value corresponds to the `atime` field of `stat` on Unix
1128     /// platforms and the `ftLastAccessTime` field on Windows platforms.
1129     ///
1130     /// Note that not all platforms will keep this field update in a file's
1131     /// metadata, for example Windows has an option to disable updating this
1132     /// time when files are accessed and Linux similarly has `noatime`.
1133     ///
1134     /// # Errors
1135     ///
1136     /// This field may not be available on all platforms, and will return an
1137     /// `Err` on platforms where it is not available.
1138     ///
1139     /// # Examples
1140     ///
1141     /// ```no_run
1142     /// use std::fs;
1143     ///
1144     /// fn main() -> std::io::Result<()> {
1145     ///     let metadata = fs::metadata("foo.txt")?;
1146     ///
1147     ///     if let Ok(time) = metadata.accessed() {
1148     ///         println!("{:?}", time);
1149     ///     } else {
1150     ///         println!("Not supported on this platform");
1151     ///     }
1152     ///     Ok(())
1153     /// }
1154     /// ```
1155     #[stable(feature = "fs_time", since = "1.10.0")]
1156     pub fn accessed(&self) -> io::Result<SystemTime> {
1157         self.0.accessed().map(FromInner::from_inner)
1158     }
1159
1160     /// Returns the creation time listed in this metadata.
1161     ///
1162     /// The returned value corresponds to the `btime` field of `statx` on
1163     /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1164     /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1165     ///
1166     /// # Errors
1167     ///
1168     /// This field may not be available on all platforms, and will return an
1169     /// `Err` on platforms or filesystems where it is not available.
1170     ///
1171     /// # Examples
1172     ///
1173     /// ```no_run
1174     /// use std::fs;
1175     ///
1176     /// fn main() -> std::io::Result<()> {
1177     ///     let metadata = fs::metadata("foo.txt")?;
1178     ///
1179     ///     if let Ok(time) = metadata.created() {
1180     ///         println!("{:?}", time);
1181     ///     } else {
1182     ///         println!("Not supported on this platform or filesystem");
1183     ///     }
1184     ///     Ok(())
1185     /// }
1186     /// ```
1187     #[stable(feature = "fs_time", since = "1.10.0")]
1188     pub fn created(&self) -> io::Result<SystemTime> {
1189         self.0.created().map(FromInner::from_inner)
1190     }
1191 }
1192
1193 #[stable(feature = "std_debug", since = "1.16.0")]
1194 impl fmt::Debug for Metadata {
1195     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1196         f.debug_struct("Metadata")
1197             .field("file_type", &self.file_type())
1198             .field("is_dir", &self.is_dir())
1199             .field("is_file", &self.is_file())
1200             .field("permissions", &self.permissions())
1201             .field("modified", &self.modified())
1202             .field("accessed", &self.accessed())
1203             .field("created", &self.created())
1204             .finish()
1205     }
1206 }
1207
1208 impl AsInner<fs_imp::FileAttr> for Metadata {
1209     fn as_inner(&self) -> &fs_imp::FileAttr {
1210         &self.0
1211     }
1212 }
1213
1214 impl FromInner<fs_imp::FileAttr> for Metadata {
1215     fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
1216         Metadata(attr)
1217     }
1218 }
1219
1220 impl Permissions {
1221     /// Returns `true` if these permissions describe a readonly (unwritable) file.
1222     ///
1223     /// # Examples
1224     ///
1225     /// ```no_run
1226     /// use std::fs::File;
1227     ///
1228     /// fn main() -> std::io::Result<()> {
1229     ///     let mut f = File::create("foo.txt")?;
1230     ///     let metadata = f.metadata()?;
1231     ///
1232     ///     assert_eq!(false, metadata.permissions().readonly());
1233     ///     Ok(())
1234     /// }
1235     /// ```
1236     #[stable(feature = "rust1", since = "1.0.0")]
1237     pub fn readonly(&self) -> bool {
1238         self.0.readonly()
1239     }
1240
1241     /// Modifies the readonly flag for this set of permissions. If the
1242     /// `readonly` argument is `true`, using the resulting `Permission` will
1243     /// update file permissions to forbid writing. Conversely, if it's `false`,
1244     /// using the resulting `Permission` will update file permissions to allow
1245     /// writing.
1246     ///
1247     /// This operation does **not** modify the filesystem. To modify the
1248     /// filesystem use the [`fs::set_permissions`] function.
1249     ///
1250     /// [`fs::set_permissions`]: fn.set_permissions.html
1251     ///
1252     /// # Examples
1253     ///
1254     /// ```no_run
1255     /// use std::fs::File;
1256     ///
1257     /// fn main() -> std::io::Result<()> {
1258     ///     let f = File::create("foo.txt")?;
1259     ///     let metadata = f.metadata()?;
1260     ///     let mut permissions = metadata.permissions();
1261     ///
1262     ///     permissions.set_readonly(true);
1263     ///
1264     ///     // filesystem doesn't change
1265     ///     assert_eq!(false, metadata.permissions().readonly());
1266     ///
1267     ///     // just this particular `permissions`.
1268     ///     assert_eq!(true, permissions.readonly());
1269     ///     Ok(())
1270     /// }
1271     /// ```
1272     #[stable(feature = "rust1", since = "1.0.0")]
1273     pub fn set_readonly(&mut self, readonly: bool) {
1274         self.0.set_readonly(readonly)
1275     }
1276 }
1277
1278 impl FileType {
1279     /// Tests whether this file type represents a directory. The
1280     /// result is mutually exclusive to the results of
1281     /// [`is_file`] and [`is_symlink`]; only zero or one of these
1282     /// tests may pass.
1283     ///
1284     /// [`is_file`]: struct.FileType.html#method.is_file
1285     /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1286     ///
1287     /// # Examples
1288     ///
1289     /// ```no_run
1290     /// fn main() -> std::io::Result<()> {
1291     ///     use std::fs;
1292     ///
1293     ///     let metadata = fs::metadata("foo.txt")?;
1294     ///     let file_type = metadata.file_type();
1295     ///
1296     ///     assert_eq!(file_type.is_dir(), false);
1297     ///     Ok(())
1298     /// }
1299     /// ```
1300     #[stable(feature = "file_type", since = "1.1.0")]
1301     pub fn is_dir(&self) -> bool {
1302         self.0.is_dir()
1303     }
1304
1305     /// Tests whether this file type represents a regular file.
1306     /// The result is  mutually exclusive to the results of
1307     /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1308     /// tests may pass.
1309     ///
1310     /// [`is_dir`]: struct.FileType.html#method.is_dir
1311     /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1312     ///
1313     /// # Examples
1314     ///
1315     /// ```no_run
1316     /// fn main() -> std::io::Result<()> {
1317     ///     use std::fs;
1318     ///
1319     ///     let metadata = fs::metadata("foo.txt")?;
1320     ///     let file_type = metadata.file_type();
1321     ///
1322     ///     assert_eq!(file_type.is_file(), true);
1323     ///     Ok(())
1324     /// }
1325     /// ```
1326     #[stable(feature = "file_type", since = "1.1.0")]
1327     pub fn is_file(&self) -> bool {
1328         self.0.is_file()
1329     }
1330
1331     /// Tests whether this file type represents a symbolic link.
1332     /// The result is mutually exclusive to the results of
1333     /// [`is_dir`] and [`is_file`]; only zero or one of these
1334     /// tests may pass.
1335     ///
1336     /// The underlying [`Metadata`] struct needs to be retrieved
1337     /// with the [`fs::symlink_metadata`] function and not the
1338     /// [`fs::metadata`] function. The [`fs::metadata`] function
1339     /// follows symbolic links, so [`is_symlink`] would always
1340     /// return `false` for the target file.
1341     ///
1342     /// [`Metadata`]: struct.Metadata.html
1343     /// [`fs::metadata`]: fn.metadata.html
1344     /// [`fs::symlink_metadata`]: fn.symlink_metadata.html
1345     /// [`is_dir`]: struct.FileType.html#method.is_dir
1346     /// [`is_file`]: struct.FileType.html#method.is_file
1347     /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1348     ///
1349     /// # Examples
1350     ///
1351     /// ```no_run
1352     /// use std::fs;
1353     ///
1354     /// fn main() -> std::io::Result<()> {
1355     ///     let metadata = fs::symlink_metadata("foo.txt")?;
1356     ///     let file_type = metadata.file_type();
1357     ///
1358     ///     assert_eq!(file_type.is_symlink(), false);
1359     ///     Ok(())
1360     /// }
1361     /// ```
1362     #[stable(feature = "file_type", since = "1.1.0")]
1363     pub fn is_symlink(&self) -> bool {
1364         self.0.is_symlink()
1365     }
1366 }
1367
1368 impl AsInner<fs_imp::FileType> for FileType {
1369     fn as_inner(&self) -> &fs_imp::FileType {
1370         &self.0
1371     }
1372 }
1373
1374 impl FromInner<fs_imp::FilePermissions> for Permissions {
1375     fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1376         Permissions(f)
1377     }
1378 }
1379
1380 impl AsInner<fs_imp::FilePermissions> for Permissions {
1381     fn as_inner(&self) -> &fs_imp::FilePermissions {
1382         &self.0
1383     }
1384 }
1385
1386 #[stable(feature = "rust1", since = "1.0.0")]
1387 impl Iterator for ReadDir {
1388     type Item = io::Result<DirEntry>;
1389
1390     fn next(&mut self) -> Option<io::Result<DirEntry>> {
1391         self.0.next().map(|entry| entry.map(DirEntry))
1392     }
1393 }
1394
1395 impl DirEntry {
1396     /// Returns the full path to the file that this entry represents.
1397     ///
1398     /// The full path is created by joining the original path to `read_dir`
1399     /// with the filename of this entry.
1400     ///
1401     /// # Examples
1402     ///
1403     /// ```no_run
1404     /// use std::fs;
1405     ///
1406     /// fn main() -> std::io::Result<()> {
1407     ///     for entry in fs::read_dir(".")? {
1408     ///         let dir = entry?;
1409     ///         println!("{:?}", dir.path());
1410     ///     }
1411     ///     Ok(())
1412     /// }
1413     /// ```
1414     ///
1415     /// This prints output like:
1416     ///
1417     /// ```text
1418     /// "./whatever.txt"
1419     /// "./foo.html"
1420     /// "./hello_world.rs"
1421     /// ```
1422     ///
1423     /// The exact text, of course, depends on what files you have in `.`.
1424     #[stable(feature = "rust1", since = "1.0.0")]
1425     pub fn path(&self) -> PathBuf {
1426         self.0.path()
1427     }
1428
1429     /// Returns the metadata for the file that this entry points at.
1430     ///
1431     /// This function will not traverse symlinks if this entry points at a
1432     /// symlink.
1433     ///
1434     /// # Platform-specific behavior
1435     ///
1436     /// On Windows this function is cheap to call (no extra system calls
1437     /// needed), but on Unix platforms this function is the equivalent of
1438     /// calling `symlink_metadata` on the path.
1439     ///
1440     /// # Examples
1441     ///
1442     /// ```
1443     /// use std::fs;
1444     ///
1445     /// if let Ok(entries) = fs::read_dir(".") {
1446     ///     for entry in entries {
1447     ///         if let Ok(entry) = entry {
1448     ///             // Here, `entry` is a `DirEntry`.
1449     ///             if let Ok(metadata) = entry.metadata() {
1450     ///                 // Now let's show our entry's permissions!
1451     ///                 println!("{:?}: {:?}", entry.path(), metadata.permissions());
1452     ///             } else {
1453     ///                 println!("Couldn't get metadata for {:?}", entry.path());
1454     ///             }
1455     ///         }
1456     ///     }
1457     /// }
1458     /// ```
1459     #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1460     pub fn metadata(&self) -> io::Result<Metadata> {
1461         self.0.metadata().map(Metadata)
1462     }
1463
1464     /// Returns the file type for the file that this entry points at.
1465     ///
1466     /// This function will not traverse symlinks if this entry points at a
1467     /// symlink.
1468     ///
1469     /// # Platform-specific behavior
1470     ///
1471     /// On Windows and most Unix platforms this function is free (no extra
1472     /// system calls needed), but some Unix platforms may require the equivalent
1473     /// call to `symlink_metadata` to learn about the target file type.
1474     ///
1475     /// # Examples
1476     ///
1477     /// ```
1478     /// use std::fs;
1479     ///
1480     /// if let Ok(entries) = fs::read_dir(".") {
1481     ///     for entry in entries {
1482     ///         if let Ok(entry) = entry {
1483     ///             // Here, `entry` is a `DirEntry`.
1484     ///             if let Ok(file_type) = entry.file_type() {
1485     ///                 // Now let's show our entry's file type!
1486     ///                 println!("{:?}: {:?}", entry.path(), file_type);
1487     ///             } else {
1488     ///                 println!("Couldn't get file type for {:?}", entry.path());
1489     ///             }
1490     ///         }
1491     ///     }
1492     /// }
1493     /// ```
1494     #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1495     pub fn file_type(&self) -> io::Result<FileType> {
1496         self.0.file_type().map(FileType)
1497     }
1498
1499     /// Returns the bare file name of this directory entry without any other
1500     /// leading path component.
1501     ///
1502     /// # Examples
1503     ///
1504     /// ```
1505     /// use std::fs;
1506     ///
1507     /// if let Ok(entries) = fs::read_dir(".") {
1508     ///     for entry in entries {
1509     ///         if let Ok(entry) = entry {
1510     ///             // Here, `entry` is a `DirEntry`.
1511     ///             println!("{:?}", entry.file_name());
1512     ///         }
1513     ///     }
1514     /// }
1515     /// ```
1516     #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1517     pub fn file_name(&self) -> OsString {
1518         self.0.file_name()
1519     }
1520 }
1521
1522 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1523 impl fmt::Debug for DirEntry {
1524     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1525         f.debug_tuple("DirEntry").field(&self.path()).finish()
1526     }
1527 }
1528
1529 impl AsInner<fs_imp::DirEntry> for DirEntry {
1530     fn as_inner(&self) -> &fs_imp::DirEntry {
1531         &self.0
1532     }
1533 }
1534
1535 /// Removes a file from the filesystem.
1536 ///
1537 /// Note that there is no
1538 /// guarantee that the file is immediately deleted (e.g., depending on
1539 /// platform, other open file descriptors may prevent immediate removal).
1540 ///
1541 /// # Platform-specific behavior
1542 ///
1543 /// This function currently corresponds to the `unlink` function on Unix
1544 /// and the `DeleteFile` function on Windows.
1545 /// Note that, this [may change in the future][changes].
1546 ///
1547 /// [changes]: ../io/index.html#platform-specific-behavior
1548 ///
1549 /// # Errors
1550 ///
1551 /// This function will return an error in the following situations, but is not
1552 /// limited to just these cases:
1553 ///
1554 /// * `path` points to a directory.
1555 /// * The user lacks permissions to remove the file.
1556 ///
1557 /// # Examples
1558 ///
1559 /// ```no_run
1560 /// use std::fs;
1561 ///
1562 /// fn main() -> std::io::Result<()> {
1563 ///     fs::remove_file("a.txt")?;
1564 ///     Ok(())
1565 /// }
1566 /// ```
1567 #[stable(feature = "rust1", since = "1.0.0")]
1568 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1569     fs_imp::unlink(path.as_ref())
1570 }
1571
1572 /// Given a path, query the file system to get information about a file,
1573 /// directory, etc.
1574 ///
1575 /// This function will traverse symbolic links to query information about the
1576 /// destination file.
1577 ///
1578 /// # Platform-specific behavior
1579 ///
1580 /// This function currently corresponds to the `stat` function on Unix
1581 /// and the `GetFileAttributesEx` function on Windows.
1582 /// Note that, this [may change in the future][changes].
1583 ///
1584 /// [changes]: ../io/index.html#platform-specific-behavior
1585 ///
1586 /// # Errors
1587 ///
1588 /// This function will return an error in the following situations, but is not
1589 /// limited to just these cases:
1590 ///
1591 /// * The user lacks permissions to perform `metadata` call on `path`.
1592 /// * `path` does not exist.
1593 ///
1594 /// # Examples
1595 ///
1596 /// ```rust,no_run
1597 /// use std::fs;
1598 ///
1599 /// fn main() -> std::io::Result<()> {
1600 ///     let attr = fs::metadata("/some/file/path.txt")?;
1601 ///     // inspect attr ...
1602 ///     Ok(())
1603 /// }
1604 /// ```
1605 #[stable(feature = "rust1", since = "1.0.0")]
1606 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1607     fs_imp::stat(path.as_ref()).map(Metadata)
1608 }
1609
1610 /// Query the metadata about a file without following symlinks.
1611 ///
1612 /// # Platform-specific behavior
1613 ///
1614 /// This function currently corresponds to the `lstat` function on Unix
1615 /// and the `GetFileAttributesEx` function on Windows.
1616 /// Note that, this [may change in the future][changes].
1617 ///
1618 /// [changes]: ../io/index.html#platform-specific-behavior
1619 ///
1620 /// # Errors
1621 ///
1622 /// This function will return an error in the following situations, but is not
1623 /// limited to just these cases:
1624 ///
1625 /// * The user lacks permissions to perform `metadata` call on `path`.
1626 /// * `path` does not exist.
1627 ///
1628 /// # Examples
1629 ///
1630 /// ```rust,no_run
1631 /// use std::fs;
1632 ///
1633 /// fn main() -> std::io::Result<()> {
1634 ///     let attr = fs::symlink_metadata("/some/file/path.txt")?;
1635 ///     // inspect attr ...
1636 ///     Ok(())
1637 /// }
1638 /// ```
1639 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1640 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1641     fs_imp::lstat(path.as_ref()).map(Metadata)
1642 }
1643
1644 /// Rename a file or directory to a new name, replacing the original file if
1645 /// `to` already exists.
1646 ///
1647 /// This will not work if the new name is on a different mount point.
1648 ///
1649 /// # Platform-specific behavior
1650 ///
1651 /// This function currently corresponds to the `rename` function on Unix
1652 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1653 ///
1654 /// Because of this, the behavior when both `from` and `to` exist differs. On
1655 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1656 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1657 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1658 ///
1659 /// Note that, this [may change in the future][changes].
1660 ///
1661 /// [changes]: ../io/index.html#platform-specific-behavior
1662 ///
1663 /// # Errors
1664 ///
1665 /// This function will return an error in the following situations, but is not
1666 /// limited to just these cases:
1667 ///
1668 /// * `from` does not exist.
1669 /// * The user lacks permissions to view contents.
1670 /// * `from` and `to` are on separate filesystems.
1671 ///
1672 /// # Examples
1673 ///
1674 /// ```no_run
1675 /// use std::fs;
1676 ///
1677 /// fn main() -> std::io::Result<()> {
1678 ///     fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1679 ///     Ok(())
1680 /// }
1681 /// ```
1682 #[stable(feature = "rust1", since = "1.0.0")]
1683 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1684     fs_imp::rename(from.as_ref(), to.as_ref())
1685 }
1686
1687 /// Copies the contents of one file to another. This function will also
1688 /// copy the permission bits of the original file to the destination file.
1689 ///
1690 /// This function will **overwrite** the contents of `to`.
1691 ///
1692 /// Note that if `from` and `to` both point to the same file, then the file
1693 /// will likely get truncated by this operation.
1694 ///
1695 /// On success, the total number of bytes copied is returned and it is equal to
1696 /// the length of the `to` file as reported by `metadata`.
1697 ///
1698 /// If you’re wanting to copy the contents of one file to another and you’re
1699 /// working with [`File`]s, see the [`io::copy`] function.
1700 ///
1701 /// [`io::copy`]: ../io/fn.copy.html
1702 /// [`File`]: ./struct.File.html
1703 ///
1704 /// # Platform-specific behavior
1705 ///
1706 /// This function currently corresponds to the `open` function in Unix
1707 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1708 /// `O_CLOEXEC` is set for returned file descriptors.
1709 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1710 /// NTFS streams are copied but only the size of the main stream is returned by
1711 /// this function. On MacOS, this function corresponds to `fclonefileat` and
1712 /// `fcopyfile`.
1713 /// Note that, this [may change in the future][changes].
1714 ///
1715 /// [changes]: ../io/index.html#platform-specific-behavior
1716 ///
1717 /// # Errors
1718 ///
1719 /// This function will return an error in the following situations, but is not
1720 /// limited to just these cases:
1721 ///
1722 /// * The `from` path is not a file.
1723 /// * The `from` file does not exist.
1724 /// * The current process does not have the permission rights to access
1725 ///   `from` or write `to`.
1726 ///
1727 /// # Examples
1728 ///
1729 /// ```no_run
1730 /// use std::fs;
1731 ///
1732 /// fn main() -> std::io::Result<()> {
1733 ///     fs::copy("foo.txt", "bar.txt")?;  // Copy foo.txt to bar.txt
1734 ///     Ok(())
1735 /// }
1736 /// ```
1737 #[stable(feature = "rust1", since = "1.0.0")]
1738 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1739     fs_imp::copy(from.as_ref(), to.as_ref())
1740 }
1741
1742 /// Creates a new hard link on the filesystem.
1743 ///
1744 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1745 /// often require these two paths to both be located on the same filesystem.
1746 ///
1747 /// # Platform-specific behavior
1748 ///
1749 /// This function currently corresponds to the `link` function on Unix
1750 /// and the `CreateHardLink` function on Windows.
1751 /// Note that, this [may change in the future][changes].
1752 ///
1753 /// [changes]: ../io/index.html#platform-specific-behavior
1754 ///
1755 /// # Errors
1756 ///
1757 /// This function will return an error in the following situations, but is not
1758 /// limited to just these cases:
1759 ///
1760 /// * The `src` path is not a file or doesn't exist.
1761 ///
1762 /// # Examples
1763 ///
1764 /// ```no_run
1765 /// use std::fs;
1766 ///
1767 /// fn main() -> std::io::Result<()> {
1768 ///     fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1769 ///     Ok(())
1770 /// }
1771 /// ```
1772 #[stable(feature = "rust1", since = "1.0.0")]
1773 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1774     fs_imp::link(src.as_ref(), dst.as_ref())
1775 }
1776
1777 /// Creates a new symbolic link on the filesystem.
1778 ///
1779 /// The `dst` path will be a symbolic link pointing to the `src` path.
1780 /// On Windows, this will be a file symlink, not a directory symlink;
1781 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1782 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1783 /// used instead to make the intent explicit.
1784 ///
1785 /// [`std::os::unix::fs::symlink`]: ../os/unix/fs/fn.symlink.html
1786 /// [`std::os::windows::fs::symlink_file`]: ../os/windows/fs/fn.symlink_file.html
1787 /// [`symlink_dir`]: ../os/windows/fs/fn.symlink_dir.html
1788 ///
1789 ///
1790 /// # Examples
1791 ///
1792 /// ```no_run
1793 /// use std::fs;
1794 ///
1795 /// fn main() -> std::io::Result<()> {
1796 ///     fs::soft_link("a.txt", "b.txt")?;
1797 ///     Ok(())
1798 /// }
1799 /// ```
1800 #[stable(feature = "rust1", since = "1.0.0")]
1801 #[rustc_deprecated(
1802     since = "1.1.0",
1803     reason = "replaced with std::os::unix::fs::symlink and \
1804               std::os::windows::fs::{symlink_file, symlink_dir}"
1805 )]
1806 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1807     fs_imp::symlink(src.as_ref(), dst.as_ref())
1808 }
1809
1810 /// Reads a symbolic link, returning the file that the link points to.
1811 ///
1812 /// # Platform-specific behavior
1813 ///
1814 /// This function currently corresponds to the `readlink` function on Unix
1815 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1816 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1817 /// Note that, this [may change in the future][changes].
1818 ///
1819 /// [changes]: ../io/index.html#platform-specific-behavior
1820 ///
1821 /// # Errors
1822 ///
1823 /// This function will return an error in the following situations, but is not
1824 /// limited to just these cases:
1825 ///
1826 /// * `path` is not a symbolic link.
1827 /// * `path` does not exist.
1828 ///
1829 /// # Examples
1830 ///
1831 /// ```no_run
1832 /// use std::fs;
1833 ///
1834 /// fn main() -> std::io::Result<()> {
1835 ///     let path = fs::read_link("a.txt")?;
1836 ///     Ok(())
1837 /// }
1838 /// ```
1839 #[stable(feature = "rust1", since = "1.0.0")]
1840 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1841     fs_imp::readlink(path.as_ref())
1842 }
1843
1844 /// Returns the canonical, absolute form of a path with all intermediate
1845 /// components normalized and symbolic links resolved.
1846 ///
1847 /// # Platform-specific behavior
1848 ///
1849 /// This function currently corresponds to the `realpath` function on Unix
1850 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1851 /// Note that, this [may change in the future][changes].
1852 ///
1853 /// On Windows, this converts the path to use [extended length path][path]
1854 /// syntax, which allows your program to use longer path names, but means you
1855 /// can only join backslash-delimited paths to it, and it may be incompatible
1856 /// with other applications (if passed to the application on the command-line,
1857 /// or written to a file another application may read).
1858 ///
1859 /// [changes]: ../io/index.html#platform-specific-behavior
1860 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1861 ///
1862 /// # Errors
1863 ///
1864 /// This function will return an error in the following situations, but is not
1865 /// limited to just these cases:
1866 ///
1867 /// * `path` does not exist.
1868 /// * A non-final component in path is not a directory.
1869 ///
1870 /// # Examples
1871 ///
1872 /// ```no_run
1873 /// use std::fs;
1874 ///
1875 /// fn main() -> std::io::Result<()> {
1876 ///     let path = fs::canonicalize("../a/../foo.txt")?;
1877 ///     Ok(())
1878 /// }
1879 /// ```
1880 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1881 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1882     fs_imp::canonicalize(path.as_ref())
1883 }
1884
1885 /// Creates a new, empty directory at the provided path
1886 ///
1887 /// # Platform-specific behavior
1888 ///
1889 /// This function currently corresponds to the `mkdir` function on Unix
1890 /// and the `CreateDirectory` function on Windows.
1891 /// Note that, this [may change in the future][changes].
1892 ///
1893 /// [changes]: ../io/index.html#platform-specific-behavior
1894 ///
1895 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1896 /// return an error. To create a directory and all its missing parents at the
1897 /// same time, use the [`create_dir_all`] function.
1898 ///
1899 /// # Errors
1900 ///
1901 /// This function will return an error in the following situations, but is not
1902 /// limited to just these cases:
1903 ///
1904 /// * User lacks permissions to create directory at `path`.
1905 /// * A parent of the given path doesn't exist. (To create a directory and all
1906 ///   its missing parents at the same time, use the [`create_dir_all`]
1907 ///   function.)
1908 /// * `path` already exists.
1909 ///
1910 /// [`create_dir_all`]: fn.create_dir_all.html
1911 ///
1912 /// # Examples
1913 ///
1914 /// ```no_run
1915 /// use std::fs;
1916 ///
1917 /// fn main() -> std::io::Result<()> {
1918 ///     fs::create_dir("/some/dir")?;
1919 ///     Ok(())
1920 /// }
1921 /// ```
1922 #[stable(feature = "rust1", since = "1.0.0")]
1923 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1924     DirBuilder::new().create(path.as_ref())
1925 }
1926
1927 /// Recursively create a directory and all of its parent components if they
1928 /// are missing.
1929 ///
1930 /// # Platform-specific behavior
1931 ///
1932 /// This function currently corresponds to the `mkdir` function on Unix
1933 /// and the `CreateDirectory` function on Windows.
1934 /// Note that, this [may change in the future][changes].
1935 ///
1936 /// [changes]: ../io/index.html#platform-specific-behavior
1937 ///
1938 /// # Errors
1939 ///
1940 /// This function will return an error in the following situations, but is not
1941 /// limited to just these cases:
1942 ///
1943 /// * If any directory in the path specified by `path`
1944 /// does not already exist and it could not be created otherwise. The specific
1945 /// error conditions for when a directory is being created (after it is
1946 /// determined to not exist) are outlined by [`fs::create_dir`].
1947 ///
1948 /// Notable exception is made for situations where any of the directories
1949 /// specified in the `path` could not be created as it was being created concurrently.
1950 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1951 /// concurrently from multiple threads or processes is guaranteed not to fail
1952 /// due to a race condition with itself.
1953 ///
1954 /// [`fs::create_dir`]: fn.create_dir.html
1955 ///
1956 /// # Examples
1957 ///
1958 /// ```no_run
1959 /// use std::fs;
1960 ///
1961 /// fn main() -> std::io::Result<()> {
1962 ///     fs::create_dir_all("/some/dir")?;
1963 ///     Ok(())
1964 /// }
1965 /// ```
1966 #[stable(feature = "rust1", since = "1.0.0")]
1967 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1968     DirBuilder::new().recursive(true).create(path.as_ref())
1969 }
1970
1971 /// Removes an existing, empty directory.
1972 ///
1973 /// # Platform-specific behavior
1974 ///
1975 /// This function currently corresponds to the `rmdir` function on Unix
1976 /// and the `RemoveDirectory` function on Windows.
1977 /// Note that, this [may change in the future][changes].
1978 ///
1979 /// [changes]: ../io/index.html#platform-specific-behavior
1980 ///
1981 /// # Errors
1982 ///
1983 /// This function will return an error in the following situations, but is not
1984 /// limited to just these cases:
1985 ///
1986 /// * The user lacks permissions to remove the directory at the provided `path`.
1987 /// * The directory isn't empty.
1988 ///
1989 /// # Examples
1990 ///
1991 /// ```no_run
1992 /// use std::fs;
1993 ///
1994 /// fn main() -> std::io::Result<()> {
1995 ///     fs::remove_dir("/some/dir")?;
1996 ///     Ok(())
1997 /// }
1998 /// ```
1999 #[stable(feature = "rust1", since = "1.0.0")]
2000 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
2001     fs_imp::rmdir(path.as_ref())
2002 }
2003
2004 /// Removes a directory at this path, after removing all its contents. Use
2005 /// carefully!
2006 ///
2007 /// This function does **not** follow symbolic links and it will simply remove the
2008 /// symbolic link itself.
2009 ///
2010 /// # Platform-specific behavior
2011 ///
2012 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
2013 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
2014 /// on Windows.
2015 /// Note that, this [may change in the future][changes].
2016 ///
2017 /// [changes]: ../io/index.html#platform-specific-behavior
2018 ///
2019 /// # Errors
2020 ///
2021 /// See [`fs::remove_file`] and [`fs::remove_dir`].
2022 ///
2023 /// [`fs::remove_file`]:  fn.remove_file.html
2024 /// [`fs::remove_dir`]: fn.remove_dir.html
2025 ///
2026 /// # Examples
2027 ///
2028 /// ```no_run
2029 /// use std::fs;
2030 ///
2031 /// fn main() -> std::io::Result<()> {
2032 ///     fs::remove_dir_all("/some/dir")?;
2033 ///     Ok(())
2034 /// }
2035 /// ```
2036 #[stable(feature = "rust1", since = "1.0.0")]
2037 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2038     fs_imp::remove_dir_all(path.as_ref())
2039 }
2040
2041 /// Returns an iterator over the entries within a directory.
2042 ///
2043 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
2044 /// New errors may be encountered after an iterator is initially constructed.
2045 ///
2046 /// [`io::Result`]: ../io/type.Result.html
2047 /// [`DirEntry`]: struct.DirEntry.html
2048 ///
2049 /// # Platform-specific behavior
2050 ///
2051 /// This function currently corresponds to the `opendir` function on Unix
2052 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2053 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2054 /// Note that, this [may change in the future][changes].
2055 ///
2056 /// [changes]: ../io/index.html#platform-specific-behavior
2057 ///
2058 /// The order in which this iterator returns entries is platform and filesystem
2059 /// dependent.
2060 ///
2061 /// # Errors
2062 ///
2063 /// This function will return an error in the following situations, but is not
2064 /// limited to just these cases:
2065 ///
2066 /// * The provided `path` doesn't exist.
2067 /// * The process lacks permissions to view the contents.
2068 /// * The `path` points at a non-directory file.
2069 ///
2070 /// # Examples
2071 ///
2072 /// ```
2073 /// use std::io;
2074 /// use std::fs::{self, DirEntry};
2075 /// use std::path::Path;
2076 ///
2077 /// // one possible implementation of walking a directory only visiting files
2078 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2079 ///     if dir.is_dir() {
2080 ///         for entry in fs::read_dir(dir)? {
2081 ///             let entry = entry?;
2082 ///             let path = entry.path();
2083 ///             if path.is_dir() {
2084 ///                 visit_dirs(&path, cb)?;
2085 ///             } else {
2086 ///                 cb(&entry);
2087 ///             }
2088 ///         }
2089 ///     }
2090 ///     Ok(())
2091 /// }
2092 /// ```
2093 ///
2094 /// ```rust,no_run
2095 /// use std::{fs, io};
2096 ///
2097 /// fn main() -> io::Result<()> {
2098 ///     let mut entries = fs::read_dir(".")?
2099 ///         .map(|res| res.map(|e| e.path()))
2100 ///         .collect::<Result<Vec<_>, io::Error>>()?;
2101 ///
2102 ///     // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2103 ///     // ordering is required the entries should be explicitly sorted.
2104 ///
2105 ///     entries.sort();
2106 ///
2107 ///     // The entries have now been sorted by their path.
2108 ///
2109 ///     Ok(())
2110 /// }
2111 /// ```
2112 #[stable(feature = "rust1", since = "1.0.0")]
2113 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2114     fs_imp::readdir(path.as_ref()).map(ReadDir)
2115 }
2116
2117 /// Changes the permissions found on a file or a directory.
2118 ///
2119 /// # Platform-specific behavior
2120 ///
2121 /// This function currently corresponds to the `chmod` function on Unix
2122 /// and the `SetFileAttributes` function on Windows.
2123 /// Note that, this [may change in the future][changes].
2124 ///
2125 /// [changes]: ../io/index.html#platform-specific-behavior
2126 ///
2127 /// # Errors
2128 ///
2129 /// This function will return an error in the following situations, but is not
2130 /// limited to just these cases:
2131 ///
2132 /// * `path` does not exist.
2133 /// * The user lacks the permission to change attributes of the file.
2134 ///
2135 /// # Examples
2136 ///
2137 /// ```no_run
2138 /// use std::fs;
2139 ///
2140 /// fn main() -> std::io::Result<()> {
2141 ///     let mut perms = fs::metadata("foo.txt")?.permissions();
2142 ///     perms.set_readonly(true);
2143 ///     fs::set_permissions("foo.txt", perms)?;
2144 ///     Ok(())
2145 /// }
2146 /// ```
2147 #[stable(feature = "set_permissions", since = "1.1.0")]
2148 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
2149     fs_imp::set_perm(path.as_ref(), perm.0)
2150 }
2151
2152 impl DirBuilder {
2153     /// Creates a new set of options with default mode/security settings for all
2154     /// platforms and also non-recursive.
2155     ///
2156     /// # Examples
2157     ///
2158     /// ```
2159     /// use std::fs::DirBuilder;
2160     ///
2161     /// let builder = DirBuilder::new();
2162     /// ```
2163     #[stable(feature = "dir_builder", since = "1.6.0")]
2164     pub fn new() -> DirBuilder {
2165         DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
2166     }
2167
2168     /// Indicates that directories should be created recursively, creating all
2169     /// parent directories. Parents that do not exist are created with the same
2170     /// security and permissions settings.
2171     ///
2172     /// This option defaults to `false`.
2173     ///
2174     /// # Examples
2175     ///
2176     /// ```
2177     /// use std::fs::DirBuilder;
2178     ///
2179     /// let mut builder = DirBuilder::new();
2180     /// builder.recursive(true);
2181     /// ```
2182     #[stable(feature = "dir_builder", since = "1.6.0")]
2183     pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2184         self.recursive = recursive;
2185         self
2186     }
2187
2188     /// Creates the specified directory with the options configured in this
2189     /// builder.
2190     ///
2191     /// It is considered an error if the directory already exists unless
2192     /// recursive mode is enabled.
2193     ///
2194     /// # Examples
2195     ///
2196     /// ```no_run
2197     /// use std::fs::{self, DirBuilder};
2198     ///
2199     /// let path = "/tmp/foo/bar/baz";
2200     /// DirBuilder::new()
2201     ///     .recursive(true)
2202     ///     .create(path).unwrap();
2203     ///
2204     /// assert!(fs::metadata(path).unwrap().is_dir());
2205     /// ```
2206     #[stable(feature = "dir_builder", since = "1.6.0")]
2207     pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2208         self._create(path.as_ref())
2209     }
2210
2211     fn _create(&self, path: &Path) -> io::Result<()> {
2212         if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
2213     }
2214
2215     fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2216         if path == Path::new("") {
2217             return Ok(());
2218         }
2219
2220         match self.inner.mkdir(path) {
2221             Ok(()) => return Ok(()),
2222             Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2223             Err(_) if path.is_dir() => return Ok(()),
2224             Err(e) => return Err(e),
2225         }
2226         match path.parent() {
2227             Some(p) => self.create_dir_all(p)?,
2228             None => {
2229                 return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree"));
2230             }
2231         }
2232         match self.inner.mkdir(path) {
2233             Ok(()) => Ok(()),
2234             Err(_) if path.is_dir() => Ok(()),
2235             Err(e) => Err(e),
2236         }
2237     }
2238 }
2239
2240 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2241     fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2242         &mut self.inner
2243     }
2244 }
2245
2246 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten", target_env = "sgx"))))]
2247 mod tests {
2248     use crate::io::prelude::*;
2249
2250     use crate::fs::{self, File, OpenOptions};
2251     use crate::io::{ErrorKind, SeekFrom};
2252     use crate::path::Path;
2253     use crate::str;
2254     use crate::sys_common::io::test::{tmpdir, TempDir};
2255     use crate::thread;
2256
2257     use rand::{rngs::StdRng, RngCore, SeedableRng};
2258
2259     #[cfg(unix)]
2260     use crate::os::unix::fs::symlink as symlink_dir;
2261     #[cfg(unix)]
2262     use crate::os::unix::fs::symlink as symlink_file;
2263     #[cfg(unix)]
2264     use crate::os::unix::fs::symlink as symlink_junction;
2265     #[cfg(windows)]
2266     use crate::os::windows::fs::{symlink_dir, symlink_file};
2267     #[cfg(windows)]
2268     use crate::sys::fs::symlink_junction;
2269
2270     macro_rules! check {
2271         ($e:expr) => {
2272             match $e {
2273                 Ok(t) => t,
2274                 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
2275             }
2276         };
2277     }
2278
2279     #[cfg(windows)]
2280     macro_rules! error {
2281         ($e:expr, $s:expr) => {
2282             match $e {
2283                 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2284                 Err(ref err) => assert!(
2285                     err.raw_os_error() == Some($s),
2286                     format!("`{}` did not have a code of `{}`", err, $s)
2287                 ),
2288             }
2289         };
2290     }
2291
2292     #[cfg(unix)]
2293     macro_rules! error {
2294         ($e:expr, $s:expr) => {
2295             error_contains!($e, $s)
2296         };
2297     }
2298
2299     macro_rules! error_contains {
2300         ($e:expr, $s:expr) => {
2301             match $e {
2302                 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2303                 Err(ref err) => assert!(
2304                     err.to_string().contains($s),
2305                     format!("`{}` did not contain `{}`", err, $s)
2306                 ),
2307             }
2308         };
2309     }
2310
2311     // Several test fail on windows if the user does not have permission to
2312     // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
2313     // disabling these test on Windows, use this function to test whether we
2314     // have permission, and return otherwise. This way, we still don't run these
2315     // tests most of the time, but at least we do if the user has the right
2316     // permissions.
2317     pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
2318         if cfg!(unix) {
2319             return true;
2320         }
2321         let link = tmpdir.join("some_hopefully_unique_link_name");
2322
2323         match symlink_file(r"nonexisting_target", link) {
2324             Ok(_) => true,
2325             // ERROR_PRIVILEGE_NOT_HELD = 1314
2326             Err(ref err) if err.raw_os_error() == Some(1314) => false,
2327             Err(_) => true,
2328         }
2329     }
2330
2331     #[test]
2332     fn file_test_io_smoke_test() {
2333         let message = "it's alright. have a good time";
2334         let tmpdir = tmpdir();
2335         let filename = &tmpdir.join("file_rt_io_file_test.txt");
2336         {
2337             let mut write_stream = check!(File::create(filename));
2338             check!(write_stream.write(message.as_bytes()));
2339         }
2340         {
2341             let mut read_stream = check!(File::open(filename));
2342             let mut read_buf = [0; 1028];
2343             let read_str = match check!(read_stream.read(&mut read_buf)) {
2344                 0 => panic!("shouldn't happen"),
2345                 n => str::from_utf8(&read_buf[..n]).unwrap().to_string(),
2346             };
2347             assert_eq!(read_str, message);
2348         }
2349         check!(fs::remove_file(filename));
2350     }
2351
2352     #[test]
2353     fn invalid_path_raises() {
2354         let tmpdir = tmpdir();
2355         let filename = &tmpdir.join("file_that_does_not_exist.txt");
2356         let result = File::open(filename);
2357
2358         #[cfg(all(unix, not(target_os = "vxworks")))]
2359         error!(result, "No such file or directory");
2360         #[cfg(target_os = "vxworks")]
2361         error!(result, "no such file or directory");
2362         #[cfg(windows)]
2363         error!(result, 2); // ERROR_FILE_NOT_FOUND
2364     }
2365
2366     #[test]
2367     fn file_test_iounlinking_invalid_path_should_raise_condition() {
2368         let tmpdir = tmpdir();
2369         let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
2370
2371         let result = fs::remove_file(filename);
2372
2373         #[cfg(all(unix, not(target_os = "vxworks")))]
2374         error!(result, "No such file or directory");
2375         #[cfg(target_os = "vxworks")]
2376         error!(result, "no such file or directory");
2377         #[cfg(windows)]
2378         error!(result, 2); // ERROR_FILE_NOT_FOUND
2379     }
2380
2381     #[test]
2382     fn file_test_io_non_positional_read() {
2383         let message: &str = "ten-four";
2384         let mut read_mem = [0; 8];
2385         let tmpdir = tmpdir();
2386         let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
2387         {
2388             let mut rw_stream = check!(File::create(filename));
2389             check!(rw_stream.write(message.as_bytes()));
2390         }
2391         {
2392             let mut read_stream = check!(File::open(filename));
2393             {
2394                 let read_buf = &mut read_mem[0..4];
2395                 check!(read_stream.read(read_buf));
2396             }
2397             {
2398                 let read_buf = &mut read_mem[4..8];
2399                 check!(read_stream.read(read_buf));
2400             }
2401         }
2402         check!(fs::remove_file(filename));
2403         let read_str = str::from_utf8(&read_mem).unwrap();
2404         assert_eq!(read_str, message);
2405     }
2406
2407     #[test]
2408     fn file_test_io_seek_and_tell_smoke_test() {
2409         let message = "ten-four";
2410         let mut read_mem = [0; 4];
2411         let set_cursor = 4 as u64;
2412         let tell_pos_pre_read;
2413         let tell_pos_post_read;
2414         let tmpdir = tmpdir();
2415         let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
2416         {
2417             let mut rw_stream = check!(File::create(filename));
2418             check!(rw_stream.write(message.as_bytes()));
2419         }
2420         {
2421             let mut read_stream = check!(File::open(filename));
2422             check!(read_stream.seek(SeekFrom::Start(set_cursor)));
2423             tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
2424             check!(read_stream.read(&mut read_mem));
2425             tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
2426         }
2427         check!(fs::remove_file(filename));
2428         let read_str = str::from_utf8(&read_mem).unwrap();
2429         assert_eq!(read_str, &message[4..8]);
2430         assert_eq!(tell_pos_pre_read, set_cursor);
2431         assert_eq!(tell_pos_post_read, message.len() as u64);
2432     }
2433
2434     #[test]
2435     fn file_test_io_seek_and_write() {
2436         let initial_msg = "food-is-yummy";
2437         let overwrite_msg = "-the-bar!!";
2438         let final_msg = "foo-the-bar!!";
2439         let seek_idx = 3;
2440         let mut read_mem = [0; 13];
2441         let tmpdir = tmpdir();
2442         let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
2443         {
2444             let mut rw_stream = check!(File::create(filename));
2445             check!(rw_stream.write(initial_msg.as_bytes()));
2446             check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
2447             check!(rw_stream.write(overwrite_msg.as_bytes()));
2448         }
2449         {
2450             let mut read_stream = check!(File::open(filename));
2451             check!(read_stream.read(&mut read_mem));
2452         }
2453         check!(fs::remove_file(filename));
2454         let read_str = str::from_utf8(&read_mem).unwrap();
2455         assert!(read_str == final_msg);
2456     }
2457
2458     #[test]
2459     fn file_test_io_seek_shakedown() {
2460         //                   01234567890123
2461         let initial_msg = "qwer-asdf-zxcv";
2462         let chunk_one: &str = "qwer";
2463         let chunk_two: &str = "asdf";
2464         let chunk_three: &str = "zxcv";
2465         let mut read_mem = [0; 4];
2466         let tmpdir = tmpdir();
2467         let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
2468         {
2469             let mut rw_stream = check!(File::create(filename));
2470             check!(rw_stream.write(initial_msg.as_bytes()));
2471         }
2472         {
2473             let mut read_stream = check!(File::open(filename));
2474
2475             check!(read_stream.seek(SeekFrom::End(-4)));
2476             check!(read_stream.read(&mut read_mem));
2477             assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
2478
2479             check!(read_stream.seek(SeekFrom::Current(-9)));
2480             check!(read_stream.read(&mut read_mem));
2481             assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
2482
2483             check!(read_stream.seek(SeekFrom::Start(0)));
2484             check!(read_stream.read(&mut read_mem));
2485             assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
2486         }
2487         check!(fs::remove_file(filename));
2488     }
2489
2490     #[test]
2491     fn file_test_io_eof() {
2492         let tmpdir = tmpdir();
2493         let filename = tmpdir.join("file_rt_io_file_test_eof.txt");
2494         let mut buf = [0; 256];
2495         {
2496             let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2497             let mut rw = check!(oo.open(&filename));
2498             assert_eq!(check!(rw.read(&mut buf)), 0);
2499             assert_eq!(check!(rw.read(&mut buf)), 0);
2500         }
2501         check!(fs::remove_file(&filename));
2502     }
2503
2504     #[test]
2505     #[cfg(unix)]
2506     fn file_test_io_read_write_at() {
2507         use crate::os::unix::fs::FileExt;
2508
2509         let tmpdir = tmpdir();
2510         let filename = tmpdir.join("file_rt_io_file_test_read_write_at.txt");
2511         let mut buf = [0; 256];
2512         let write1 = "asdf";
2513         let write2 = "qwer-";
2514         let write3 = "-zxcv";
2515         let content = "qwer-asdf-zxcv";
2516         {
2517             let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2518             let mut rw = check!(oo.open(&filename));
2519             assert_eq!(check!(rw.write_at(write1.as_bytes(), 5)), write1.len());
2520             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2521             assert_eq!(check!(rw.read_at(&mut buf, 5)), write1.len());
2522             assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2523             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2524             assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2525             assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok("\0\0\0\0\0"));
2526             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2527             assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2528             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2529             assert_eq!(check!(rw.read(&mut buf)), write1.len());
2530             assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2531             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2532             assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2533             assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2534             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2535             assert_eq!(check!(rw.write_at(write3.as_bytes(), 9)), write3.len());
2536             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2537         }
2538         {
2539             let mut read = check!(File::open(&filename));
2540             assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2541             assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2542             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 0);
2543             assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2544             assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2545             assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2546             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 9);
2547             assert_eq!(check!(read.read(&mut buf)), write3.len());
2548             assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2549             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2550             assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2551             assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2552             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2553             assert_eq!(check!(read.read_at(&mut buf, 14)), 0);
2554             assert_eq!(check!(read.read_at(&mut buf, 15)), 0);
2555             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2556         }
2557         check!(fs::remove_file(&filename));
2558     }
2559
2560     #[test]
2561     #[cfg(unix)]
2562     fn set_get_unix_permissions() {
2563         use crate::os::unix::fs::PermissionsExt;
2564
2565         let tmpdir = tmpdir();
2566         let filename = &tmpdir.join("set_get_unix_permissions");
2567         check!(fs::create_dir(filename));
2568         let mask = 0o7777;
2569
2570         check!(fs::set_permissions(filename, fs::Permissions::from_mode(0)));
2571         let metadata0 = check!(fs::metadata(filename));
2572         assert_eq!(mask & metadata0.permissions().mode(), 0);
2573
2574         check!(fs::set_permissions(filename, fs::Permissions::from_mode(0o1777)));
2575         let metadata1 = check!(fs::metadata(filename));
2576         #[cfg(all(unix, not(target_os = "vxworks")))]
2577         assert_eq!(mask & metadata1.permissions().mode(), 0o1777);
2578         #[cfg(target_os = "vxworks")]
2579         assert_eq!(mask & metadata1.permissions().mode(), 0o0777);
2580     }
2581
2582     #[test]
2583     #[cfg(windows)]
2584     fn file_test_io_seek_read_write() {
2585         use crate::os::windows::fs::FileExt;
2586
2587         let tmpdir = tmpdir();
2588         let filename = tmpdir.join("file_rt_io_file_test_seek_read_write.txt");
2589         let mut buf = [0; 256];
2590         let write1 = "asdf";
2591         let write2 = "qwer-";
2592         let write3 = "-zxcv";
2593         let content = "qwer-asdf-zxcv";
2594         {
2595             let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2596             let mut rw = check!(oo.open(&filename));
2597             assert_eq!(check!(rw.seek_write(write1.as_bytes(), 5)), write1.len());
2598             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2599             assert_eq!(check!(rw.seek_read(&mut buf, 5)), write1.len());
2600             assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2601             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2602             assert_eq!(check!(rw.seek(SeekFrom::Start(0))), 0);
2603             assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2604             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2605             assert_eq!(check!(rw.read(&mut buf)), write1.len());
2606             assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2607             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2608             assert_eq!(check!(rw.seek_read(&mut buf[..write2.len()], 0)), write2.len());
2609             assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2610             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2611             assert_eq!(check!(rw.seek_write(write3.as_bytes(), 9)), write3.len());
2612             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 14);
2613         }
2614         {
2615             let mut read = check!(File::open(&filename));
2616             assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2617             assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2618             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2619             assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2620             assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2621             assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2622             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2623             assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2624             assert_eq!(check!(read.read(&mut buf)), write3.len());
2625             assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2626             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2627             assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2628             assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2629             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2630             assert_eq!(check!(read.seek_read(&mut buf, 14)), 0);
2631             assert_eq!(check!(read.seek_read(&mut buf, 15)), 0);
2632         }
2633         check!(fs::remove_file(&filename));
2634     }
2635
2636     #[test]
2637     fn file_test_stat_is_correct_on_is_file() {
2638         let tmpdir = tmpdir();
2639         let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
2640         {
2641             let mut opts = OpenOptions::new();
2642             let mut fs = check!(opts.read(true).write(true).create(true).open(filename));
2643             let msg = "hw";
2644             fs.write(msg.as_bytes()).unwrap();
2645
2646             let fstat_res = check!(fs.metadata());
2647             assert!(fstat_res.is_file());
2648         }
2649         let stat_res_fn = check!(fs::metadata(filename));
2650         assert!(stat_res_fn.is_file());
2651         let stat_res_meth = check!(filename.metadata());
2652         assert!(stat_res_meth.is_file());
2653         check!(fs::remove_file(filename));
2654     }
2655
2656     #[test]
2657     fn file_test_stat_is_correct_on_is_dir() {
2658         let tmpdir = tmpdir();
2659         let filename = &tmpdir.join("file_stat_correct_on_is_dir");
2660         check!(fs::create_dir(filename));
2661         let stat_res_fn = check!(fs::metadata(filename));
2662         assert!(stat_res_fn.is_dir());
2663         let stat_res_meth = check!(filename.metadata());
2664         assert!(stat_res_meth.is_dir());
2665         check!(fs::remove_dir(filename));
2666     }
2667
2668     #[test]
2669     fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
2670         let tmpdir = tmpdir();
2671         let dir = &tmpdir.join("fileinfo_false_on_dir");
2672         check!(fs::create_dir(dir));
2673         assert!(!dir.is_file());
2674         check!(fs::remove_dir(dir));
2675     }
2676
2677     #[test]
2678     fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
2679         let tmpdir = tmpdir();
2680         let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
2681         check!(check!(File::create(file)).write(b"foo"));
2682         assert!(file.exists());
2683         check!(fs::remove_file(file));
2684         assert!(!file.exists());
2685     }
2686
2687     #[test]
2688     fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
2689         let tmpdir = tmpdir();
2690         let dir = &tmpdir.join("before_and_after_dir");
2691         assert!(!dir.exists());
2692         check!(fs::create_dir(dir));
2693         assert!(dir.exists());
2694         assert!(dir.is_dir());
2695         check!(fs::remove_dir(dir));
2696         assert!(!dir.exists());
2697     }
2698
2699     #[test]
2700     fn file_test_directoryinfo_readdir() {
2701         let tmpdir = tmpdir();
2702         let dir = &tmpdir.join("di_readdir");
2703         check!(fs::create_dir(dir));
2704         let prefix = "foo";
2705         for n in 0..3 {
2706             let f = dir.join(&format!("{}.txt", n));
2707             let mut w = check!(File::create(&f));
2708             let msg_str = format!("{}{}", prefix, n.to_string());
2709             let msg = msg_str.as_bytes();
2710             check!(w.write(msg));
2711         }
2712         let files = check!(fs::read_dir(dir));
2713         let mut mem = [0; 4];
2714         for f in files {
2715             let f = f.unwrap().path();
2716             {
2717                 let n = f.file_stem().unwrap();
2718                 check!(check!(File::open(&f)).read(&mut mem));
2719                 let read_str = str::from_utf8(&mem).unwrap();
2720                 let expected = format!("{}{}", prefix, n.to_str().unwrap());
2721                 assert_eq!(expected, read_str);
2722             }
2723             check!(fs::remove_file(&f));
2724         }
2725         check!(fs::remove_dir(dir));
2726     }
2727
2728     #[test]
2729     fn file_create_new_already_exists_error() {
2730         let tmpdir = tmpdir();
2731         let file = &tmpdir.join("file_create_new_error_exists");
2732         check!(fs::File::create(file));
2733         let e = fs::OpenOptions::new().write(true).create_new(true).open(file).unwrap_err();
2734         assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2735     }
2736
2737     #[test]
2738     fn mkdir_path_already_exists_error() {
2739         let tmpdir = tmpdir();
2740         let dir = &tmpdir.join("mkdir_error_twice");
2741         check!(fs::create_dir(dir));
2742         let e = fs::create_dir(dir).unwrap_err();
2743         assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2744     }
2745
2746     #[test]
2747     fn recursive_mkdir() {
2748         let tmpdir = tmpdir();
2749         let dir = tmpdir.join("d1/d2");
2750         check!(fs::create_dir_all(&dir));
2751         assert!(dir.is_dir())
2752     }
2753
2754     #[test]
2755     fn recursive_mkdir_failure() {
2756         let tmpdir = tmpdir();
2757         let dir = tmpdir.join("d1");
2758         let file = dir.join("f1");
2759
2760         check!(fs::create_dir_all(&dir));
2761         check!(File::create(&file));
2762
2763         let result = fs::create_dir_all(&file);
2764
2765         assert!(result.is_err());
2766     }
2767
2768     #[test]
2769     fn concurrent_recursive_mkdir() {
2770         for _ in 0..100 {
2771             let dir = tmpdir();
2772             let mut dir = dir.join("a");
2773             for _ in 0..40 {
2774                 dir = dir.join("a");
2775             }
2776             let mut join = vec![];
2777             for _ in 0..8 {
2778                 let dir = dir.clone();
2779                 join.push(thread::spawn(move || {
2780                     check!(fs::create_dir_all(&dir));
2781                 }))
2782             }
2783
2784             // No `Display` on result of `join()`
2785             join.drain(..).map(|join| join.join().unwrap()).count();
2786         }
2787     }
2788
2789     #[test]
2790     fn recursive_mkdir_slash() {
2791         check!(fs::create_dir_all(Path::new("/")));
2792     }
2793
2794     #[test]
2795     fn recursive_mkdir_dot() {
2796         check!(fs::create_dir_all(Path::new(".")));
2797     }
2798
2799     #[test]
2800     fn recursive_mkdir_empty() {
2801         check!(fs::create_dir_all(Path::new("")));
2802     }
2803
2804     #[test]
2805     fn recursive_rmdir() {
2806         let tmpdir = tmpdir();
2807         let d1 = tmpdir.join("d1");
2808         let dt = d1.join("t");
2809         let dtt = dt.join("t");
2810         let d2 = tmpdir.join("d2");
2811         let canary = d2.join("do_not_delete");
2812         check!(fs::create_dir_all(&dtt));
2813         check!(fs::create_dir_all(&d2));
2814         check!(check!(File::create(&canary)).write(b"foo"));
2815         check!(symlink_junction(&d2, &dt.join("d2")));
2816         let _ = symlink_file(&canary, &d1.join("canary"));
2817         check!(fs::remove_dir_all(&d1));
2818
2819         assert!(!d1.is_dir());
2820         assert!(canary.exists());
2821     }
2822
2823     #[test]
2824     fn recursive_rmdir_of_symlink() {
2825         // test we do not recursively delete a symlink but only dirs.
2826         let tmpdir = tmpdir();
2827         let link = tmpdir.join("d1");
2828         let dir = tmpdir.join("d2");
2829         let canary = dir.join("do_not_delete");
2830         check!(fs::create_dir_all(&dir));
2831         check!(check!(File::create(&canary)).write(b"foo"));
2832         check!(symlink_junction(&dir, &link));
2833         check!(fs::remove_dir_all(&link));
2834
2835         assert!(!link.is_dir());
2836         assert!(canary.exists());
2837     }
2838
2839     #[test]
2840     // only Windows makes a distinction between file and directory symlinks.
2841     #[cfg(windows)]
2842     fn recursive_rmdir_of_file_symlink() {
2843         let tmpdir = tmpdir();
2844         if !got_symlink_permission(&tmpdir) {
2845             return;
2846         };
2847
2848         let f1 = tmpdir.join("f1");
2849         let f2 = tmpdir.join("f2");
2850         check!(check!(File::create(&f1)).write(b"foo"));
2851         check!(symlink_file(&f1, &f2));
2852         match fs::remove_dir_all(&f2) {
2853             Ok(..) => panic!("wanted a failure"),
2854             Err(..) => {}
2855         }
2856     }
2857
2858     #[test]
2859     fn unicode_path_is_dir() {
2860         assert!(Path::new(".").is_dir());
2861         assert!(!Path::new("test/stdtest/fs.rs").is_dir());
2862
2863         let tmpdir = tmpdir();
2864
2865         let mut dirpath = tmpdir.path().to_path_buf();
2866         dirpath.push("test-가一ー你好");
2867         check!(fs::create_dir(&dirpath));
2868         assert!(dirpath.is_dir());
2869
2870         let mut filepath = dirpath;
2871         filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
2872         check!(File::create(&filepath)); // ignore return; touch only
2873         assert!(!filepath.is_dir());
2874         assert!(filepath.exists());
2875     }
2876
2877     #[test]
2878     fn unicode_path_exists() {
2879         assert!(Path::new(".").exists());
2880         assert!(!Path::new("test/nonexistent-bogus-path").exists());
2881
2882         let tmpdir = tmpdir();
2883         let unicode = tmpdir.path();
2884         let unicode = unicode.join("test-각丁ー再见");
2885         check!(fs::create_dir(&unicode));
2886         assert!(unicode.exists());
2887         assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
2888     }
2889
2890     #[test]
2891     fn copy_file_does_not_exist() {
2892         let from = Path::new("test/nonexistent-bogus-path");
2893         let to = Path::new("test/other-bogus-path");
2894
2895         match fs::copy(&from, &to) {
2896             Ok(..) => panic!(),
2897             Err(..) => {
2898                 assert!(!from.exists());
2899                 assert!(!to.exists());
2900             }
2901         }
2902     }
2903
2904     #[test]
2905     fn copy_src_does_not_exist() {
2906         let tmpdir = tmpdir();
2907         let from = Path::new("test/nonexistent-bogus-path");
2908         let to = tmpdir.join("out.txt");
2909         check!(check!(File::create(&to)).write(b"hello"));
2910         assert!(fs::copy(&from, &to).is_err());
2911         assert!(!from.exists());
2912         let mut v = Vec::new();
2913         check!(check!(File::open(&to)).read_to_end(&mut v));
2914         assert_eq!(v, b"hello");
2915     }
2916
2917     #[test]
2918     fn copy_file_ok() {
2919         let tmpdir = tmpdir();
2920         let input = tmpdir.join("in.txt");
2921         let out = tmpdir.join("out.txt");
2922
2923         check!(check!(File::create(&input)).write(b"hello"));
2924         check!(fs::copy(&input, &out));
2925         let mut v = Vec::new();
2926         check!(check!(File::open(&out)).read_to_end(&mut v));
2927         assert_eq!(v, b"hello");
2928
2929         assert_eq!(check!(input.metadata()).permissions(), check!(out.metadata()).permissions());
2930     }
2931
2932     #[test]
2933     fn copy_file_dst_dir() {
2934         let tmpdir = tmpdir();
2935         let out = tmpdir.join("out");
2936
2937         check!(File::create(&out));
2938         match fs::copy(&*out, tmpdir.path()) {
2939             Ok(..) => panic!(),
2940             Err(..) => {}
2941         }
2942     }
2943
2944     #[test]
2945     fn copy_file_dst_exists() {
2946         let tmpdir = tmpdir();
2947         let input = tmpdir.join("in");
2948         let output = tmpdir.join("out");
2949
2950         check!(check!(File::create(&input)).write("foo".as_bytes()));
2951         check!(check!(File::create(&output)).write("bar".as_bytes()));
2952         check!(fs::copy(&input, &output));
2953
2954         let mut v = Vec::new();
2955         check!(check!(File::open(&output)).read_to_end(&mut v));
2956         assert_eq!(v, b"foo".to_vec());
2957     }
2958
2959     #[test]
2960     fn copy_file_src_dir() {
2961         let tmpdir = tmpdir();
2962         let out = tmpdir.join("out");
2963
2964         match fs::copy(tmpdir.path(), &out) {
2965             Ok(..) => panic!(),
2966             Err(..) => {}
2967         }
2968         assert!(!out.exists());
2969     }
2970
2971     #[test]
2972     fn copy_file_preserves_perm_bits() {
2973         let tmpdir = tmpdir();
2974         let input = tmpdir.join("in.txt");
2975         let out = tmpdir.join("out.txt");
2976
2977         let attr = check!(check!(File::create(&input)).metadata());
2978         let mut p = attr.permissions();
2979         p.set_readonly(true);
2980         check!(fs::set_permissions(&input, p));
2981         check!(fs::copy(&input, &out));
2982         assert!(check!(out.metadata()).permissions().readonly());
2983         check!(fs::set_permissions(&input, attr.permissions()));
2984         check!(fs::set_permissions(&out, attr.permissions()));
2985     }
2986
2987     #[test]
2988     #[cfg(windows)]
2989     fn copy_file_preserves_streams() {
2990         let tmp = tmpdir();
2991         check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
2992         assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 0);
2993         assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
2994         let mut v = Vec::new();
2995         check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
2996         assert_eq!(v, b"carrot".to_vec());
2997     }
2998
2999     #[test]
3000     fn copy_file_returns_metadata_len() {
3001         let tmp = tmpdir();
3002         let in_path = tmp.join("in.txt");
3003         let out_path = tmp.join("out.txt");
3004         check!(check!(File::create(&in_path)).write(b"lettuce"));
3005         #[cfg(windows)]
3006         check!(check!(File::create(tmp.join("in.txt:bunny"))).write(b"carrot"));
3007         let copied_len = check!(fs::copy(&in_path, &out_path));
3008         assert_eq!(check!(out_path.metadata()).len(), copied_len);
3009     }
3010
3011     #[test]
3012     fn copy_file_follows_dst_symlink() {
3013         let tmp = tmpdir();
3014         if !got_symlink_permission(&tmp) {
3015             return;
3016         };
3017
3018         let in_path = tmp.join("in.txt");
3019         let out_path = tmp.join("out.txt");
3020         let out_path_symlink = tmp.join("out_symlink.txt");
3021
3022         check!(fs::write(&in_path, "foo"));
3023         check!(fs::write(&out_path, "bar"));
3024         check!(symlink_file(&out_path, &out_path_symlink));
3025
3026         check!(fs::copy(&in_path, &out_path_symlink));
3027
3028         assert!(check!(out_path_symlink.symlink_metadata()).file_type().is_symlink());
3029         assert_eq!(check!(fs::read(&out_path_symlink)), b"foo".to_vec());
3030         assert_eq!(check!(fs::read(&out_path)), b"foo".to_vec());
3031     }
3032
3033     #[test]
3034     fn symlinks_work() {
3035         let tmpdir = tmpdir();
3036         if !got_symlink_permission(&tmpdir) {
3037             return;
3038         };
3039
3040         let input = tmpdir.join("in.txt");
3041         let out = tmpdir.join("out.txt");
3042
3043         check!(check!(File::create(&input)).write("foobar".as_bytes()));
3044         check!(symlink_file(&input, &out));
3045         assert!(check!(out.symlink_metadata()).file_type().is_symlink());
3046         assert_eq!(check!(fs::metadata(&out)).len(), check!(fs::metadata(&input)).len());
3047         let mut v = Vec::new();
3048         check!(check!(File::open(&out)).read_to_end(&mut v));
3049         assert_eq!(v, b"foobar".to_vec());
3050     }
3051
3052     #[test]
3053     fn symlink_noexist() {
3054         // Symlinks can point to things that don't exist
3055         let tmpdir = tmpdir();
3056         if !got_symlink_permission(&tmpdir) {
3057             return;
3058         };
3059
3060         // Use a relative path for testing. Symlinks get normalized by Windows,
3061         // so we may not get the same path back for absolute paths
3062         check!(symlink_file(&"foo", &tmpdir.join("bar")));
3063         assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(), "foo");
3064     }
3065
3066     #[test]
3067     fn read_link() {
3068         if cfg!(windows) {
3069             // directory symlink
3070             assert_eq!(
3071                 check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
3072                 r"C:\ProgramData"
3073             );
3074             // junction
3075             assert_eq!(
3076                 check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
3077                 r"C:\Users\Default"
3078             );
3079             // junction with special permissions
3080             assert_eq!(
3081                 check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
3082                 r"C:\Users"
3083             );
3084         }
3085         let tmpdir = tmpdir();
3086         let link = tmpdir.join("link");
3087         if !got_symlink_permission(&tmpdir) {
3088             return;
3089         };
3090         check!(symlink_file(&"foo", &link));
3091         assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
3092     }
3093
3094     #[test]
3095     fn readlink_not_symlink() {
3096         let tmpdir = tmpdir();
3097         match fs::read_link(tmpdir.path()) {
3098             Ok(..) => panic!("wanted a failure"),
3099             Err(..) => {}
3100         }
3101     }
3102
3103     #[test]
3104     fn links_work() {
3105         let tmpdir = tmpdir();
3106         let input = tmpdir.join("in.txt");
3107         let out = tmpdir.join("out.txt");
3108
3109         check!(check!(File::create(&input)).write("foobar".as_bytes()));
3110         check!(fs::hard_link(&input, &out));
3111         assert_eq!(check!(fs::metadata(&out)).len(), check!(fs::metadata(&input)).len());
3112         assert_eq!(check!(fs::metadata(&out)).len(), check!(input.metadata()).len());
3113         let mut v = Vec::new();
3114         check!(check!(File::open(&out)).read_to_end(&mut v));
3115         assert_eq!(v, b"foobar".to_vec());
3116
3117         // can't link to yourself
3118         match fs::hard_link(&input, &input) {
3119             Ok(..) => panic!("wanted a failure"),
3120             Err(..) => {}
3121         }
3122         // can't link to something that doesn't exist
3123         match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
3124             Ok(..) => panic!("wanted a failure"),
3125             Err(..) => {}
3126         }
3127     }
3128
3129     #[test]
3130     fn chmod_works() {
3131         let tmpdir = tmpdir();
3132         let file = tmpdir.join("in.txt");
3133
3134         check!(File::create(&file));
3135         let attr = check!(fs::metadata(&file));
3136         assert!(!attr.permissions().readonly());
3137         let mut p = attr.permissions();
3138         p.set_readonly(true);
3139         check!(fs::set_permissions(&file, p.clone()));
3140         let attr = check!(fs::metadata(&file));
3141         assert!(attr.permissions().readonly());
3142
3143         match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
3144             Ok(..) => panic!("wanted an error"),
3145             Err(..) => {}
3146         }
3147
3148         p.set_readonly(false);
3149         check!(fs::set_permissions(&file, p));
3150     }
3151
3152     #[test]
3153     fn fchmod_works() {
3154         let tmpdir = tmpdir();
3155         let path = tmpdir.join("in.txt");
3156
3157         let file = check!(File::create(&path));
3158         let attr = check!(fs::metadata(&path));
3159         assert!(!attr.permissions().readonly());
3160         let mut p = attr.permissions();
3161         p.set_readonly(true);
3162         check!(file.set_permissions(p.clone()));
3163         let attr = check!(fs::metadata(&path));
3164         assert!(attr.permissions().readonly());
3165
3166         p.set_readonly(false);
3167         check!(file.set_permissions(p));
3168     }
3169
3170     #[test]
3171     fn sync_doesnt_kill_anything() {
3172         let tmpdir = tmpdir();
3173         let path = tmpdir.join("in.txt");
3174
3175         let mut file = check!(File::create(&path));
3176         check!(file.sync_all());
3177         check!(file.sync_data());
3178         check!(file.write(b"foo"));
3179         check!(file.sync_all());
3180         check!(file.sync_data());
3181     }
3182
3183     #[test]
3184     fn truncate_works() {
3185         let tmpdir = tmpdir();
3186         let path = tmpdir.join("in.txt");
3187
3188         let mut file = check!(File::create(&path));
3189         check!(file.write(b"foo"));
3190         check!(file.sync_all());
3191
3192         // Do some simple things with truncation
3193         assert_eq!(check!(file.metadata()).len(), 3);
3194         check!(file.set_len(10));
3195         assert_eq!(check!(file.metadata()).len(), 10);
3196         check!(file.write(b"bar"));
3197         check!(file.sync_all());
3198         assert_eq!(check!(file.metadata()).len(), 10);
3199
3200         let mut v = Vec::new();
3201         check!(check!(File::open(&path)).read_to_end(&mut v));
3202         assert_eq!(v, b"foobar\0\0\0\0".to_vec());
3203
3204         // Truncate to a smaller length, don't seek, and then write something.
3205         // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
3206         // past the end of the file).
3207         check!(file.set_len(2));
3208         assert_eq!(check!(file.metadata()).len(), 2);
3209         check!(file.write(b"wut"));
3210         check!(file.sync_all());
3211         assert_eq!(check!(file.metadata()).len(), 9);
3212         let mut v = Vec::new();
3213         check!(check!(File::open(&path)).read_to_end(&mut v));
3214         assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
3215     }
3216
3217     #[test]
3218     fn open_flavors() {
3219         use crate::fs::OpenOptions as OO;
3220         fn c<T: Clone>(t: &T) -> T {
3221             t.clone()
3222         }
3223
3224         let tmpdir = tmpdir();
3225
3226         let mut r = OO::new();
3227         r.read(true);
3228         let mut w = OO::new();
3229         w.write(true);
3230         let mut rw = OO::new();
3231         rw.read(true).write(true);
3232         let mut a = OO::new();
3233         a.append(true);
3234         let mut ra = OO::new();
3235         ra.read(true).append(true);
3236
3237         #[cfg(windows)]
3238         let invalid_options = 87; // ERROR_INVALID_PARAMETER
3239         #[cfg(all(unix, not(target_os = "vxworks")))]
3240         let invalid_options = "Invalid argument";
3241         #[cfg(target_os = "vxworks")]
3242         let invalid_options = "invalid argument";
3243
3244         // Test various combinations of creation modes and access modes.
3245         //
3246         // Allowed:
3247         // creation mode           | read  | write | read-write | append | read-append |
3248         // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
3249         // not set (open existing) |   X   |   X   |     X      |   X    |      X      |
3250         // create                  |       |   X   |     X      |   X    |      X      |
3251         // truncate                |       |   X   |     X      |        |             |
3252         // create and truncate     |       |   X   |     X      |        |             |
3253         // create_new              |       |   X   |     X      |   X    |      X      |
3254         //
3255         // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
3256
3257         // write-only
3258         check!(c(&w).create_new(true).open(&tmpdir.join("a")));
3259         check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
3260         check!(c(&w).truncate(true).open(&tmpdir.join("a")));
3261         check!(c(&w).create(true).open(&tmpdir.join("a")));
3262         check!(c(&w).open(&tmpdir.join("a")));
3263
3264         // read-only
3265         error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
3266         error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
3267         error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
3268         error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
3269         check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
3270
3271         // read-write
3272         check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
3273         check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
3274         check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
3275         check!(c(&rw).create(true).open(&tmpdir.join("c")));
3276         check!(c(&rw).open(&tmpdir.join("c")));
3277
3278         // append
3279         check!(c(&a).create_new(true).open(&tmpdir.join("d")));
3280         error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
3281         error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
3282         check!(c(&a).create(true).open(&tmpdir.join("d")));
3283         check!(c(&a).open(&tmpdir.join("d")));
3284
3285         // read-append
3286         check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
3287         error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
3288         error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
3289         check!(c(&ra).create(true).open(&tmpdir.join("e")));
3290         check!(c(&ra).open(&tmpdir.join("e")));
3291
3292         // Test opening a file without setting an access mode
3293         let mut blank = OO::new();
3294         error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
3295
3296         // Test write works
3297         check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
3298
3299         // Test write fails for read-only
3300         check!(r.open(&tmpdir.join("h")));
3301         {
3302             let mut f = check!(r.open(&tmpdir.join("h")));
3303             assert!(f.write("wut".as_bytes()).is_err());
3304         }
3305
3306         // Test write overwrites
3307         {
3308             let mut f = check!(c(&w).open(&tmpdir.join("h")));
3309             check!(f.write("baz".as_bytes()));
3310         }
3311         {
3312             let mut f = check!(c(&r).open(&tmpdir.join("h")));
3313             let mut b = vec![0; 6];
3314             check!(f.read(&mut b));
3315             assert_eq!(b, "bazbar".as_bytes());
3316         }
3317
3318         // Test truncate works
3319         {
3320             let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
3321             check!(f.write("foo".as_bytes()));
3322         }
3323         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3324
3325         // Test append works
3326         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3327         {
3328             let mut f = check!(c(&a).open(&tmpdir.join("h")));
3329             check!(f.write("bar".as_bytes()));
3330         }
3331         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
3332
3333         // Test .append(true) equals .write(true).append(true)
3334         {
3335             let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
3336             check!(f.write("baz".as_bytes()));
3337         }
3338         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
3339     }
3340
3341     #[test]
3342     fn _assert_send_sync() {
3343         fn _assert_send_sync<T: Send + Sync>() {}
3344         _assert_send_sync::<OpenOptions>();
3345     }
3346
3347     #[test]
3348     fn binary_file() {
3349         let mut bytes = [0; 1024];
3350         StdRng::from_entropy().fill_bytes(&mut bytes);
3351
3352         let tmpdir = tmpdir();
3353
3354         check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
3355         let mut v = Vec::new();
3356         check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
3357         assert!(v == &bytes[..]);
3358     }
3359
3360     #[test]
3361     fn write_then_read() {
3362         let mut bytes = [0; 1024];
3363         StdRng::from_entropy().fill_bytes(&mut bytes);
3364
3365         let tmpdir = tmpdir();
3366
3367         check!(fs::write(&tmpdir.join("test"), &bytes[..]));
3368         let v = check!(fs::read(&tmpdir.join("test")));
3369         assert!(v == &bytes[..]);
3370
3371         check!(fs::write(&tmpdir.join("not-utf8"), &[0xFF]));
3372         error_contains!(
3373             fs::read_to_string(&tmpdir.join("not-utf8")),
3374             "stream did not contain valid UTF-8"
3375         );
3376
3377         let s = "𐁁𐀓𐀠𐀴𐀍";
3378         check!(fs::write(&tmpdir.join("utf8"), s.as_bytes()));
3379         let string = check!(fs::read_to_string(&tmpdir.join("utf8")));
3380         assert_eq!(string, s);
3381     }
3382
3383     #[test]
3384     fn file_try_clone() {
3385         let tmpdir = tmpdir();
3386
3387         let mut f1 = check!(
3388             OpenOptions::new().read(true).write(true).create(true).open(&tmpdir.join("test"))
3389         );
3390         let mut f2 = check!(f1.try_clone());
3391
3392         check!(f1.write_all(b"hello world"));
3393         check!(f1.seek(SeekFrom::Start(2)));
3394
3395         let mut buf = vec![];
3396         check!(f2.read_to_end(&mut buf));
3397         assert_eq!(buf, b"llo world");
3398         drop(f2);
3399
3400         check!(f1.write_all(b"!"));
3401     }
3402
3403     #[test]
3404     #[cfg(not(windows))]
3405     fn unlink_readonly() {
3406         let tmpdir = tmpdir();
3407         let path = tmpdir.join("file");
3408         check!(File::create(&path));
3409         let mut perm = check!(fs::metadata(&path)).permissions();
3410         perm.set_readonly(true);
3411         check!(fs::set_permissions(&path, perm));
3412         check!(fs::remove_file(&path));
3413     }
3414
3415     #[test]
3416     fn mkdir_trailing_slash() {
3417         let tmpdir = tmpdir();
3418         let path = tmpdir.join("file");
3419         check!(fs::create_dir_all(&path.join("a/")));
3420     }
3421
3422     #[test]
3423     fn canonicalize_works_simple() {
3424         let tmpdir = tmpdir();
3425         let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3426         let file = tmpdir.join("test");
3427         File::create(&file).unwrap();
3428         assert_eq!(fs::canonicalize(&file).unwrap(), file);
3429     }
3430
3431     #[test]
3432     fn realpath_works() {
3433         let tmpdir = tmpdir();
3434         if !got_symlink_permission(&tmpdir) {
3435             return;
3436         };
3437
3438         let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3439         let file = tmpdir.join("test");
3440         let dir = tmpdir.join("test2");
3441         let link = dir.join("link");
3442         let linkdir = tmpdir.join("test3");
3443
3444         File::create(&file).unwrap();
3445         fs::create_dir(&dir).unwrap();
3446         symlink_file(&file, &link).unwrap();
3447         symlink_dir(&dir, &linkdir).unwrap();
3448
3449         assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
3450
3451         assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
3452         assert_eq!(fs::canonicalize(&file).unwrap(), file);
3453         assert_eq!(fs::canonicalize(&link).unwrap(), file);
3454         assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
3455         assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
3456     }
3457
3458     #[test]
3459     fn realpath_works_tricky() {
3460         let tmpdir = tmpdir();
3461         if !got_symlink_permission(&tmpdir) {
3462             return;
3463         };
3464
3465         let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3466         let a = tmpdir.join("a");
3467         let b = a.join("b");
3468         let c = b.join("c");
3469         let d = a.join("d");
3470         let e = d.join("e");
3471         let f = a.join("f");
3472
3473         fs::create_dir_all(&b).unwrap();
3474         fs::create_dir_all(&d).unwrap();
3475         File::create(&f).unwrap();
3476         if cfg!(not(windows)) {
3477             symlink_file("../d/e", &c).unwrap();
3478             symlink_file("../f", &e).unwrap();
3479         }
3480         if cfg!(windows) {
3481             symlink_file(r"..\d\e", &c).unwrap();
3482             symlink_file(r"..\f", &e).unwrap();
3483         }
3484
3485         assert_eq!(fs::canonicalize(&c).unwrap(), f);
3486         assert_eq!(fs::canonicalize(&e).unwrap(), f);
3487     }
3488
3489     #[test]
3490     fn dir_entry_methods() {
3491         let tmpdir = tmpdir();
3492
3493         fs::create_dir_all(&tmpdir.join("a")).unwrap();
3494         File::create(&tmpdir.join("b")).unwrap();
3495
3496         for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
3497             let fname = file.file_name();
3498             match fname.to_str() {
3499                 Some("a") => {
3500                     assert!(file.file_type().unwrap().is_dir());
3501                     assert!(file.metadata().unwrap().is_dir());
3502                 }
3503                 Some("b") => {
3504                     assert!(file.file_type().unwrap().is_file());
3505                     assert!(file.metadata().unwrap().is_file());
3506                 }
3507                 f => panic!("unknown file name: {:?}", f),
3508             }
3509         }
3510     }
3511
3512     #[test]
3513     fn dir_entry_debug() {
3514         let tmpdir = tmpdir();
3515         File::create(&tmpdir.join("b")).unwrap();
3516         let mut read_dir = tmpdir.path().read_dir().unwrap();
3517         let dir_entry = read_dir.next().unwrap().unwrap();
3518         let actual = format!("{:?}", dir_entry);
3519         let expected = format!("DirEntry({:?})", dir_entry.0.path());
3520         assert_eq!(actual, expected);
3521     }
3522
3523     #[test]
3524     fn read_dir_not_found() {
3525         let res = fs::read_dir("/path/that/does/not/exist");
3526         assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
3527     }
3528
3529     #[test]
3530     fn create_dir_all_with_junctions() {
3531         let tmpdir = tmpdir();
3532         let target = tmpdir.join("target");
3533
3534         let junction = tmpdir.join("junction");
3535         let b = junction.join("a/b");
3536
3537         let link = tmpdir.join("link");
3538         let d = link.join("c/d");
3539
3540         fs::create_dir(&target).unwrap();
3541
3542         check!(symlink_junction(&target, &junction));
3543         check!(fs::create_dir_all(&b));
3544         // the junction itself is not a directory, but `is_dir()` on a Path
3545         // follows links
3546         assert!(junction.is_dir());
3547         assert!(b.exists());
3548
3549         if !got_symlink_permission(&tmpdir) {
3550             return;
3551         };
3552         check!(symlink_dir(&target, &link));
3553         check!(fs::create_dir_all(&d));
3554         assert!(link.is_dir());
3555         assert!(d.exists());
3556     }
3557
3558     #[test]
3559     fn metadata_access_times() {
3560         let tmpdir = tmpdir();
3561
3562         let b = tmpdir.join("b");
3563         File::create(&b).unwrap();
3564
3565         let a = check!(fs::metadata(&tmpdir.path()));
3566         let b = check!(fs::metadata(&b));
3567
3568         assert_eq!(check!(a.accessed()), check!(a.accessed()));
3569         assert_eq!(check!(a.modified()), check!(a.modified()));
3570         assert_eq!(check!(b.accessed()), check!(b.modified()));
3571
3572         if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
3573             check!(a.created());
3574             check!(b.created());
3575         }
3576
3577         if cfg!(target_os = "linux") {
3578             // Not always available
3579             match (a.created(), b.created()) {
3580                 (Ok(t1), Ok(t2)) => assert!(t1 <= t2),
3581                 (Err(e1), Err(e2))
3582                     if e1.kind() == ErrorKind::Other && e2.kind() == ErrorKind::Other => {}
3583                 (a, b) => panic!(
3584                     "creation time must be always supported or not supported: {:?} {:?}",
3585                     a, b,
3586                 ),
3587             }
3588         }
3589     }
3590 }