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