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