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