tempfile/file/
mod.rs

1use std::error;
2use std::ffi::OsStr;
3use std::fmt;
4use std::fs::{self, File, OpenOptions};
5use std::io::{self, Read, Seek, SeekFrom, Write};
6use std::mem;
7use std::ops::Deref;
8#[cfg(unix)]
9use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd};
10#[cfg(target_os = "wasi")]
11use std::os::wasi::io::{AsFd, AsRawFd, BorrowedFd, RawFd};
12#[cfg(windows)]
13use std::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, RawHandle};
14use std::path::{Path, PathBuf};
15
16use crate::env;
17use crate::error::IoResultExt;
18use crate::Builder;
19
20mod imp;
21
22/// Create a new temporary file.
23///
24/// The file will be created in the location returned by [`env::temp_dir()`].
25///
26/// # Security
27///
28/// This variant is secure/reliable in the presence of a pathological temporary file cleaner.
29///
30/// # Resource Leaking
31///
32/// The temporary file will be automatically removed by the OS when the last handle to it is closed.
33/// This doesn't rely on Rust destructors being run, so will (almost) never fail to clean up the temporary file.
34///
35/// # Errors
36///
37/// If the file can not be created, `Err` is returned.
38///
39/// # Examples
40///
41/// ```
42/// use tempfile::tempfile;
43/// use std::io::Write;
44///
45/// // Create a file inside of `env::temp_dir()`.
46/// let mut file = tempfile()?;
47///
48/// writeln!(file, "Brian was here. Briefly.")?;
49/// # Ok::<(), std::io::Error>(())
50/// ```
51pub fn tempfile() -> io::Result<File> {
52    tempfile_in(env::temp_dir())
53}
54
55/// Create a new temporary file in the specified directory.
56///
57/// # Security
58///
59/// This variant is secure/reliable in the presence of a pathological temporary file cleaner.
60/// If the temporary file isn't created in [`env::temp_dir()`] then temporary file cleaners aren't an issue.
61///
62/// # Resource Leaking
63///
64/// The temporary file will be automatically removed by the OS when the last handle to it is closed.
65/// This doesn't rely on Rust destructors being run, so will (almost) never fail to clean up the temporary file.
66///
67/// # Errors
68///
69/// If the file can not be created, `Err` is returned.
70///
71/// # Examples
72///
73/// ```
74/// use tempfile::tempfile_in;
75/// use std::io::Write;
76///
77/// // Create a file inside of the current working directory
78/// let mut file = tempfile_in("./")?;
79///
80/// writeln!(file, "Brian was here. Briefly.")?;
81/// # Ok::<(), std::io::Error>(())
82/// ```
83pub fn tempfile_in<P: AsRef<Path>>(dir: P) -> io::Result<File> {
84    imp::create(dir.as_ref())
85}
86
87/// Error returned when persisting a temporary file path fails.
88#[derive(Debug)]
89pub struct PathPersistError {
90    /// The underlying IO error.
91    pub error: io::Error,
92    /// The temporary file path that couldn't be persisted.
93    pub path: TempPath,
94}
95
96impl From<PathPersistError> for io::Error {
97    #[inline]
98    fn from(error: PathPersistError) -> io::Error {
99        error.error
100    }
101}
102
103impl From<PathPersistError> for TempPath {
104    #[inline]
105    fn from(error: PathPersistError) -> TempPath {
106        error.path
107    }
108}
109
110impl fmt::Display for PathPersistError {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        write!(f, "failed to persist temporary file path: {}", self.error)
113    }
114}
115
116impl error::Error for PathPersistError {
117    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
118        Some(&self.error)
119    }
120}
121
122/// A path to a named temporary file without an open file handle.
123///
124/// This is useful when the temporary file needs to be used by a child process,
125/// for example.
126///
127/// When dropped, the temporary file is deleted unless `keep(true)` was called
128/// on the builder that constructed this value.
129pub struct TempPath {
130    path: Box<Path>,
131    keep: bool,
132}
133
134impl TempPath {
135    /// Close and remove the temporary file.
136    ///
137    /// Use this if you want to detect errors in deleting the file.
138    ///
139    /// # Errors
140    ///
141    /// If the file cannot be deleted, `Err` is returned.
142    ///
143    /// # Examples
144    ///
145    /// ```no_run
146    /// use tempfile::NamedTempFile;
147    ///
148    /// let file = NamedTempFile::new()?;
149    ///
150    /// // Close the file, but keep the path to it around.
151    /// let path = file.into_temp_path();
152    ///
153    /// // By closing the `TempPath` explicitly, we can check that it has
154    /// // been deleted successfully. If we don't close it explicitly, the
155    /// // file will still be deleted when `file` goes out of scope, but we
156    /// // won't know whether deleting the file succeeded.
157    /// path.close()?;
158    /// # Ok::<(), std::io::Error>(())
159    /// ```
160    pub fn close(mut self) -> io::Result<()> {
161        let result = fs::remove_file(&self.path).with_err_path(|| &*self.path);
162        self.path = PathBuf::new().into_boxed_path();
163        mem::forget(self);
164        result
165    }
166
167    /// Persist the temporary file at the target path.
168    ///
169    /// If a file exists at the target path, persist will atomically replace it.
170    /// If this method fails, it will return `self` in the resulting
171    /// [`PathPersistError`].
172    ///
173    /// Note: Temporary files cannot be persisted across filesystems. Also
174    /// neither the file contents nor the containing directory are
175    /// synchronized, so the update may not yet have reached the disk when
176    /// `persist` returns.
177    ///
178    /// # Security
179    ///
180    /// Only use this method if you're positive that a temporary file cleaner
181    /// won't have deleted your file. Otherwise, you might end up persisting an
182    /// attacker controlled file.
183    ///
184    /// # Errors
185    ///
186    /// If the file cannot be moved to the new location, `Err` is returned.
187    ///
188    /// # Examples
189    ///
190    /// ```no_run
191    /// use std::io::Write;
192    /// use tempfile::NamedTempFile;
193    ///
194    /// let mut file = NamedTempFile::new()?;
195    /// writeln!(file, "Brian was here. Briefly.")?;
196    ///
197    /// let path = file.into_temp_path();
198    /// path.persist("./saved_file.txt")?;
199    /// # Ok::<(), std::io::Error>(())
200    /// ```
201    ///
202    /// [`PathPersistError`]: struct.PathPersistError.html
203    pub fn persist<P: AsRef<Path>>(mut self, new_path: P) -> Result<(), PathPersistError> {
204        match imp::persist(&self.path, new_path.as_ref(), true) {
205            Ok(_) => {
206                // Don't drop `self`. We don't want to try deleting the old
207                // temporary file path. (It'll fail, but the failure is never
208                // seen.)
209                self.path = PathBuf::new().into_boxed_path();
210                mem::forget(self);
211                Ok(())
212            }
213            Err(e) => Err(PathPersistError {
214                error: e,
215                path: self,
216            }),
217        }
218    }
219
220    /// Persist the temporary file at the target path if and only if no file exists there.
221    ///
222    /// If a file exists at the target path, fail. If this method fails, it will
223    /// return `self` in the resulting [`PathPersistError`].
224    ///
225    /// Note: Temporary files cannot be persisted across filesystems. Also Note:
226    /// This method is not atomic. It can leave the original link to the
227    /// temporary file behind.
228    ///
229    /// # Security
230    ///
231    /// Only use this method if you're positive that a temporary file cleaner
232    /// won't have deleted your file. Otherwise, you might end up persisting an
233    /// attacker controlled file.
234    ///
235    /// # Errors
236    ///
237    /// If the file cannot be moved to the new location or a file already exists
238    /// there, `Err` is returned.
239    ///
240    /// # Examples
241    ///
242    /// ```no_run
243    /// use tempfile::NamedTempFile;
244    /// use std::io::Write;
245    ///
246    /// let mut file = NamedTempFile::new()?;
247    /// writeln!(file, "Brian was here. Briefly.")?;
248    ///
249    /// let path = file.into_temp_path();
250    /// path.persist_noclobber("./saved_file.txt")?;
251    /// # Ok::<(), std::io::Error>(())
252    /// ```
253    ///
254    /// [`PathPersistError`]: struct.PathPersistError.html
255    pub fn persist_noclobber<P: AsRef<Path>>(
256        mut self,
257        new_path: P,
258    ) -> Result<(), PathPersistError> {
259        match imp::persist(&self.path, new_path.as_ref(), false) {
260            Ok(_) => {
261                // Don't drop `self`. We don't want to try deleting the old
262                // temporary file path. (It'll fail, but the failure is never
263                // seen.)
264                self.path = PathBuf::new().into_boxed_path();
265                mem::forget(self);
266                Ok(())
267            }
268            Err(e) => Err(PathPersistError {
269                error: e,
270                path: self,
271            }),
272        }
273    }
274
275    /// Keep the temporary file from being deleted. This function will turn the
276    /// temporary file into a non-temporary file without moving it.
277    ///
278    /// # Errors
279    ///
280    /// On some platforms (e.g., Windows), we need to mark the file as
281    /// non-temporary. This operation could fail.
282    ///
283    /// # Examples
284    ///
285    /// ```no_run
286    /// use std::io::Write;
287    /// use tempfile::NamedTempFile;
288    ///
289    /// let mut file = NamedTempFile::new()?;
290    /// writeln!(file, "Brian was here. Briefly.")?;
291    ///
292    /// let path = file.into_temp_path();
293    /// let path = path.keep()?;
294    /// # Ok::<(), std::io::Error>(())
295    /// ```
296    ///
297    /// [`PathPersistError`]: struct.PathPersistError.html
298    pub fn keep(mut self) -> Result<PathBuf, PathPersistError> {
299        match imp::keep(&self.path) {
300            Ok(_) => {
301                // Don't drop `self`. We don't want to try deleting the old
302                // temporary file path. (It'll fail, but the failure is never
303                // seen.)
304                let path = mem::replace(&mut self.path, PathBuf::new().into_boxed_path());
305                mem::forget(self);
306                Ok(path.into())
307            }
308            Err(e) => Err(PathPersistError {
309                error: e,
310                path: self,
311            }),
312        }
313    }
314
315    /// Create a new TempPath from an existing path. This can be done even if no
316    /// file exists at the given path.
317    ///
318    /// This is mostly useful for interacting with libraries and external
319    /// components that provide files to be consumed or expect a path with no
320    /// existing file to be given.
321    pub fn from_path(path: impl Into<PathBuf>) -> Self {
322        Self {
323            path: path.into().into_boxed_path(),
324            keep: false,
325        }
326    }
327
328    pub(crate) fn new(path: PathBuf, keep: bool) -> Self {
329        Self {
330            path: path.into_boxed_path(),
331            keep,
332        }
333    }
334}
335
336impl fmt::Debug for TempPath {
337    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338        self.path.fmt(f)
339    }
340}
341
342impl Drop for TempPath {
343    fn drop(&mut self) {
344        if !self.keep {
345            let _ = fs::remove_file(&self.path);
346        }
347    }
348}
349
350impl Deref for TempPath {
351    type Target = Path;
352
353    fn deref(&self) -> &Path {
354        &self.path
355    }
356}
357
358impl AsRef<Path> for TempPath {
359    fn as_ref(&self) -> &Path {
360        &self.path
361    }
362}
363
364impl AsRef<OsStr> for TempPath {
365    fn as_ref(&self) -> &OsStr {
366        self.path.as_os_str()
367    }
368}
369
370/// A named temporary file.
371///
372/// The default constructor, [`NamedTempFile::new()`], creates files in
373/// the location returned by [`env::temp_dir()`], but `NamedTempFile`
374/// can be configured to manage a temporary file in any location
375/// by constructing with [`NamedTempFile::new_in()`].
376///
377/// # Security
378///
379/// Most operating systems employ temporary file cleaners to delete old
380/// temporary files. Unfortunately these temporary file cleaners don't always
381/// reliably _detect_ whether the temporary file is still being used.
382///
383/// Specifically, the following sequence of events can happen:
384///
385/// 1. A user creates a temporary file with `NamedTempFile::new()`.
386/// 2. Time passes.
387/// 3. The temporary file cleaner deletes (unlinks) the temporary file from the
388///    filesystem.
389/// 4. Some other program creates a new file to replace this deleted temporary
390///    file.
391/// 5. The user tries to re-open the temporary file (in the same program or in a
392///    different program) by path. Unfortunately, they'll end up opening the
393///    file created by the other program, not the original file.
394///
395/// ## Operating System Specific Concerns
396///
397/// The behavior of temporary files and temporary file cleaners differ by
398/// operating system.
399///
400/// ### Windows
401///
402/// On Windows, open files _can't_ be deleted. This removes most of the concerns
403/// around temporary file cleaners.
404///
405/// Furthermore, temporary files are, by default, created in per-user temporary
406/// file directories so only an application running as the same user would be
407/// able to interfere (which they could do anyways). However, an application
408/// running as the same user can still _accidentally_ re-create deleted
409/// temporary files if the number of random bytes in the temporary file name is
410/// too small.
411///
412/// So, the only real concern on Windows is:
413///
414/// 1. Opening a named temporary file in a world-writable directory.
415/// 2. Using the `into_temp_path()` and/or `into_parts()` APIs to close the file
416///    handle without deleting the underlying file.
417/// 3. Continuing to use the file by path.
418///
419/// ### UNIX
420///
421/// Unlike on Windows, UNIX (and UNIX like) systems allow open files to be
422/// "unlinked" (deleted).
423///
424/// #### MacOS
425///
426/// Like on Windows, temporary files are created in per-user temporary file
427/// directories by default so calling `NamedTempFile::new()` should be
428/// relatively safe.
429///
430/// #### Linux
431///
432/// Unfortunately, most _Linux_ distributions don't create per-user temporary
433/// file directories. Worse, systemd's tmpfiles daemon (a common temporary file
434/// cleaner) will happily remove open temporary files if they haven't been
435/// modified within the last 10 days.
436///
437/// # Resource Leaking
438///
439/// If the program exits before the `NamedTempFile` destructor is
440/// run, the temporary file will not be deleted. This can happen
441/// if the process exits using [`std::process::exit()`], a segfault occurs,
442/// receiving an interrupt signal like `SIGINT` that is not handled, or by using
443/// a statically declared `NamedTempFile` instance (like with [`lazy_static`]).
444///
445/// Use the [`tempfile()`] function unless you need a named file path.
446///
447/// [`tempfile()`]: fn.tempfile.html
448/// [`NamedTempFile::new()`]: #method.new
449/// [`NamedTempFile::new_in()`]: #method.new_in
450/// [`std::process::exit()`]: http://doc.rust-lang.org/std/process/fn.exit.html
451/// [`lazy_static`]: https://github.com/rust-lang-nursery/lazy-static.rs/issues/62
452pub struct NamedTempFile<F = File> {
453    path: TempPath,
454    file: F,
455}
456
457impl<F> fmt::Debug for NamedTempFile<F> {
458    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
459        write!(f, "NamedTempFile({:?})", self.path)
460    }
461}
462
463impl<F> AsRef<Path> for NamedTempFile<F> {
464    #[inline]
465    fn as_ref(&self) -> &Path {
466        self.path()
467    }
468}
469
470/// Error returned when persisting a temporary file fails.
471pub struct PersistError<F = File> {
472    /// The underlying IO error.
473    pub error: io::Error,
474    /// The temporary file that couldn't be persisted.
475    pub file: NamedTempFile<F>,
476}
477
478impl<F> fmt::Debug for PersistError<F> {
479    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
480        write!(f, "PersistError({:?})", self.error)
481    }
482}
483
484impl<F> From<PersistError<F>> for io::Error {
485    #[inline]
486    fn from(error: PersistError<F>) -> io::Error {
487        error.error
488    }
489}
490
491impl<F> From<PersistError<F>> for NamedTempFile<F> {
492    #[inline]
493    fn from(error: PersistError<F>) -> NamedTempFile<F> {
494        error.file
495    }
496}
497
498impl<F> fmt::Display for PersistError<F> {
499    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
500        write!(f, "failed to persist temporary file: {}", self.error)
501    }
502}
503
504impl<F> error::Error for PersistError<F> {
505    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
506        Some(&self.error)
507    }
508}
509
510impl NamedTempFile<File> {
511    /// Create a new named temporary file.
512    ///
513    /// See [`Builder`] for more configuration.
514    ///
515    /// # Security
516    ///
517    /// This will create a temporary file in the default temporary file
518    /// directory (platform dependent). This has security implications on many
519    /// platforms so please read the security section of this type's
520    /// documentation.
521    ///
522    /// Reasons to use this method:
523    ///
524    ///   1. The file has a short lifetime and your temporary file cleaner is
525    ///      sane (doesn't delete recently accessed files).
526    ///
527    ///   2. You trust every user on your system (i.e. you are the only user).
528    ///
529    ///   3. You have disabled your system's temporary file cleaner or verified
530    ///      that your system doesn't have a temporary file cleaner.
531    ///
532    /// Reasons not to use this method:
533    ///
534    ///   1. You'll fix it later. No you won't.
535    ///
536    ///   2. You don't care about the security of the temporary file. If none of
537    ///      the "reasons to use this method" apply, referring to a temporary
538    ///      file by name may allow an attacker to create/overwrite your
539    ///      non-temporary files. There are exceptions but if you don't already
540    ///      know them, don't use this method.
541    ///
542    /// # Errors
543    ///
544    /// If the file can not be created, `Err` is returned.
545    ///
546    /// # Examples
547    ///
548    /// Create a named temporary file and write some data to it:
549    ///
550    /// ```no_run
551    /// use std::io::Write;
552    /// use tempfile::NamedTempFile;
553    ///
554    /// let mut file = NamedTempFile::new()?;
555    ///
556    /// writeln!(file, "Brian was here. Briefly.")?;
557    /// # Ok::<(), std::io::Error>(())
558    /// ```
559    ///
560    /// [`Builder`]: struct.Builder.html
561    pub fn new() -> io::Result<NamedTempFile> {
562        Builder::new().tempfile()
563    }
564
565    /// Create a new named temporary file in the specified directory.
566    ///
567    /// This is equivalent to:
568    ///
569    /// ```ignore
570    /// Builder::new().tempfile_in(dir)
571    /// ```
572    ///
573    /// See [`NamedTempFile::new()`] for details.
574    ///
575    /// [`NamedTempFile::new()`]: #method.new
576    pub fn new_in<P: AsRef<Path>>(dir: P) -> io::Result<NamedTempFile> {
577        Builder::new().tempfile_in(dir)
578    }
579
580    /// Create a new named temporary file with the specified filename suffix.
581    ///
582    /// See [`NamedTempFile::new()`] for details.
583    ///
584    /// [`NamedTempFile::new()`]: #method.new
585    pub fn with_suffix<S: AsRef<OsStr>>(suffix: S) -> io::Result<NamedTempFile> {
586        Builder::new().suffix(&suffix).tempfile()
587    }
588    /// Create a new named temporary file with the specified filename suffix,
589    /// in the specified directory.
590    ///
591    /// This is equivalent to:
592    ///
593    /// ```ignore
594    /// Builder::new().suffix(&suffix).tempfile_in(directory)
595    /// ```
596    ///
597    /// See [`NamedTempFile::new()`] for details.
598    ///
599    /// [`NamedTempFile::new()`]: #method.new
600    pub fn with_suffix_in<S: AsRef<OsStr>, P: AsRef<Path>>(
601        suffix: S,
602        dir: P,
603    ) -> io::Result<NamedTempFile> {
604        Builder::new().suffix(&suffix).tempfile_in(dir)
605    }
606
607    /// Create a new named temporary file with the specified filename prefix.
608    ///
609    /// See [`NamedTempFile::new()`] for details.
610    ///
611    /// [`NamedTempFile::new()`]: #method.new
612    pub fn with_prefix<S: AsRef<OsStr>>(prefix: S) -> io::Result<NamedTempFile> {
613        Builder::new().prefix(&prefix).tempfile()
614    }
615    /// Create a new named temporary file with the specified filename prefix,
616    /// in the specified directory.
617    ///
618    /// This is equivalent to:
619    ///
620    /// ```ignore
621    /// Builder::new().prefix(&prefix).tempfile_in(directory)
622    /// ```
623    ///
624    /// See [`NamedTempFile::new()`] for details.
625    ///
626    /// [`NamedTempFile::new()`]: #method.new
627    pub fn with_prefix_in<S: AsRef<OsStr>, P: AsRef<Path>>(
628        prefix: S,
629        dir: P,
630    ) -> io::Result<NamedTempFile> {
631        Builder::new().prefix(&prefix).tempfile_in(dir)
632    }
633}
634
635impl<F> NamedTempFile<F> {
636    /// Get the temporary file's path.
637    ///
638    /// # Security
639    ///
640    /// Referring to a temporary file's path may not be secure in all cases.
641    /// Please read the security section on the top level documentation of this
642    /// type for details.
643    ///
644    /// # Examples
645    ///
646    /// ```no_run
647    /// use tempfile::NamedTempFile;
648    ///
649    /// let file = NamedTempFile::new()?;
650    ///
651    /// println!("{:?}", file.path());
652    /// # Ok::<(), std::io::Error>(())
653    /// ```
654    #[inline]
655    pub fn path(&self) -> &Path {
656        &self.path
657    }
658
659    /// Close and remove the temporary file.
660    ///
661    /// Use this if you want to detect errors in deleting the file.
662    ///
663    /// # Errors
664    ///
665    /// If the file cannot be deleted, `Err` is returned.
666    ///
667    /// # Examples
668    ///
669    /// ```no_run
670    /// use tempfile::NamedTempFile;
671    ///
672    /// let file = NamedTempFile::new()?;
673    ///
674    /// // By closing the `NamedTempFile` explicitly, we can check that it has
675    /// // been deleted successfully. If we don't close it explicitly,
676    /// // the file will still be deleted when `file` goes out
677    /// // of scope, but we won't know whether deleting the file
678    /// // succeeded.
679    /// file.close()?;
680    /// # Ok::<(), std::io::Error>(())
681    /// ```
682    pub fn close(self) -> io::Result<()> {
683        let NamedTempFile { path, .. } = self;
684        path.close()
685    }
686
687    /// Persist the temporary file at the target path.
688    ///
689    /// If a file exists at the target path, persist will atomically replace it.
690    /// If this method fails, it will return `self` in the resulting
691    /// [`PersistError`].
692    ///
693    /// Note: Temporary files cannot be persisted across filesystems. Also
694    /// neither the file contents nor the containing directory are
695    /// synchronized, so the update may not yet have reached the disk when
696    /// `persist` returns.
697    ///
698    /// # Security
699    ///
700    /// This method persists the temporary file using its path and may not be
701    /// secure in all cases. Please read the security section on the top
702    /// level documentation of this type for details.
703    ///
704    /// # Errors
705    ///
706    /// If the file cannot be moved to the new location, `Err` is returned.
707    ///
708    /// # Examples
709    ///
710    /// ```no_run
711    /// use std::io::Write;
712    /// use tempfile::NamedTempFile;
713    ///
714    /// let file = NamedTempFile::new()?;
715    ///
716    /// let mut persisted_file = file.persist("./saved_file.txt")?;
717    /// writeln!(persisted_file, "Brian was here. Briefly.")?;
718    /// # Ok::<(), std::io::Error>(())
719    /// ```
720    ///
721    /// [`PersistError`]: struct.PersistError.html
722    pub fn persist<P: AsRef<Path>>(self, new_path: P) -> Result<F, PersistError<F>> {
723        let NamedTempFile { path, file } = self;
724        match path.persist(new_path) {
725            Ok(_) => Ok(file),
726            Err(err) => {
727                let PathPersistError { error, path } = err;
728                Err(PersistError {
729                    file: NamedTempFile { path, file },
730                    error,
731                })
732            }
733        }
734    }
735
736    /// Persist the temporary file at the target path if and only if no file exists there.
737    ///
738    /// If a file exists at the target path, fail. If this method fails, it will
739    /// return `self` in the resulting PersistError.
740    ///
741    /// Note: Temporary files cannot be persisted across filesystems. Also Note:
742    /// This method is not atomic. It can leave the original link to the
743    /// temporary file behind.
744    ///
745    /// # Security
746    ///
747    /// This method persists the temporary file using its path and may not be
748    /// secure in all cases. Please read the security section on the top
749    /// level documentation of this type for details.
750    ///
751    /// # Errors
752    ///
753    /// If the file cannot be moved to the new location or a file already exists there,
754    /// `Err` is returned.
755    ///
756    /// # Examples
757    ///
758    /// ```no_run
759    /// use std::io::Write;
760    /// use tempfile::NamedTempFile;
761    ///
762    /// let file = NamedTempFile::new()?;
763    ///
764    /// let mut persisted_file = file.persist_noclobber("./saved_file.txt")?;
765    /// writeln!(persisted_file, "Brian was here. Briefly.")?;
766    /// # Ok::<(), std::io::Error>(())
767    /// ```
768    pub fn persist_noclobber<P: AsRef<Path>>(self, new_path: P) -> Result<F, PersistError<F>> {
769        let NamedTempFile { path, file } = self;
770        match path.persist_noclobber(new_path) {
771            Ok(_) => Ok(file),
772            Err(err) => {
773                let PathPersistError { error, path } = err;
774                Err(PersistError {
775                    file: NamedTempFile { path, file },
776                    error,
777                })
778            }
779        }
780    }
781
782    /// Keep the temporary file from being deleted. This function will turn the
783    /// temporary file into a non-temporary file without moving it.
784    ///
785    ///
786    /// # Errors
787    ///
788    /// On some platforms (e.g., Windows), we need to mark the file as
789    /// non-temporary. This operation could fail.
790    ///
791    /// # Examples
792    ///
793    /// ```no_run
794    /// use std::io::Write;
795    /// use tempfile::NamedTempFile;
796    ///
797    /// let mut file = NamedTempFile::new()?;
798    /// writeln!(file, "Brian was here. Briefly.")?;
799    ///
800    /// let (file, path) = file.keep()?;
801    /// # Ok::<(), std::io::Error>(())
802    /// ```
803    ///
804    /// [`PathPersistError`]: struct.PathPersistError.html
805    pub fn keep(self) -> Result<(F, PathBuf), PersistError<F>> {
806        let (file, path) = (self.file, self.path);
807        match path.keep() {
808            Ok(path) => Ok((file, path)),
809            Err(PathPersistError { error, path }) => Err(PersistError {
810                file: NamedTempFile { path, file },
811                error,
812            }),
813        }
814    }
815
816    /// Get a reference to the underlying file.
817    pub fn as_file(&self) -> &F {
818        &self.file
819    }
820
821    /// Get a mutable reference to the underlying file.
822    pub fn as_file_mut(&mut self) -> &mut F {
823        &mut self.file
824    }
825
826    /// Convert the temporary file into a `std::fs::File`.
827    ///
828    /// The inner file will be deleted.
829    pub fn into_file(self) -> F {
830        self.file
831    }
832
833    /// Closes the file, leaving only the temporary file path.
834    ///
835    /// This is useful when another process must be able to open the temporary
836    /// file.
837    pub fn into_temp_path(self) -> TempPath {
838        self.path
839    }
840
841    /// Converts the named temporary file into its constituent parts.
842    ///
843    /// Note: When the path is dropped, the file is deleted but the file handle
844    /// is still usable.
845    pub fn into_parts(self) -> (F, TempPath) {
846        (self.file, self.path)
847    }
848
849    /// Creates a `NamedTempFile` from its constituent parts.
850    ///
851    /// This can be used with [`NamedTempFile::into_parts`] to reconstruct the
852    /// `NamedTempFile`.
853    pub fn from_parts(file: F, path: TempPath) -> Self {
854        Self { file, path }
855    }
856}
857
858impl NamedTempFile<File> {
859    /// Securely reopen the temporary file.
860    ///
861    /// This function is useful when you need multiple independent handles to
862    /// the same file. It's perfectly fine to drop the original `NamedTempFile`
863    /// while holding on to `File`s returned by this function; the `File`s will
864    /// remain usable. However, they may not be nameable.
865    ///
866    /// # Errors
867    ///
868    /// If the file cannot be reopened, `Err` is returned.
869    ///
870    /// # Security
871    ///
872    /// Unlike `File::open(my_temp_file.path())`, `NamedTempFile::reopen()`
873    /// guarantees that the re-opened file is the _same_ file, even in the
874    /// presence of pathological temporary file cleaners.
875    ///
876    /// # Examples
877    ///
878    /// ```no_run
879    /// use tempfile::NamedTempFile;
880    ///
881    /// let file = NamedTempFile::new()?;
882    ///
883    /// let another_handle = file.reopen()?;
884    /// # Ok::<(), std::io::Error>(())
885    /// ```
886    pub fn reopen(&self) -> io::Result<File> {
887        imp::reopen(self.as_file(), NamedTempFile::path(self))
888            .with_err_path(|| NamedTempFile::path(self))
889    }
890}
891
892impl<F: Read> Read for NamedTempFile<F> {
893    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
894        self.as_file_mut().read(buf).with_err_path(|| self.path())
895    }
896
897    fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
898        self.as_file_mut()
899            .read_vectored(bufs)
900            .with_err_path(|| self.path())
901    }
902
903    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
904        self.as_file_mut()
905            .read_to_end(buf)
906            .with_err_path(|| self.path())
907    }
908
909    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
910        self.as_file_mut()
911            .read_to_string(buf)
912            .with_err_path(|| self.path())
913    }
914
915    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
916        self.as_file_mut()
917            .read_exact(buf)
918            .with_err_path(|| self.path())
919    }
920}
921
922impl Read for &NamedTempFile<File> {
923    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
924        self.as_file().read(buf).with_err_path(|| self.path())
925    }
926
927    fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
928        self.as_file()
929            .read_vectored(bufs)
930            .with_err_path(|| self.path())
931    }
932
933    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
934        self.as_file()
935            .read_to_end(buf)
936            .with_err_path(|| self.path())
937    }
938
939    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
940        self.as_file()
941            .read_to_string(buf)
942            .with_err_path(|| self.path())
943    }
944
945    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
946        self.as_file().read_exact(buf).with_err_path(|| self.path())
947    }
948}
949
950impl<F: Write> Write for NamedTempFile<F> {
951    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
952        self.as_file_mut().write(buf).with_err_path(|| self.path())
953    }
954    #[inline]
955    fn flush(&mut self) -> io::Result<()> {
956        self.as_file_mut().flush().with_err_path(|| self.path())
957    }
958
959    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
960        self.as_file_mut()
961            .write_vectored(bufs)
962            .with_err_path(|| self.path())
963    }
964
965    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
966        self.as_file_mut()
967            .write_all(buf)
968            .with_err_path(|| self.path())
969    }
970
971    fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
972        self.as_file_mut()
973            .write_fmt(fmt)
974            .with_err_path(|| self.path())
975    }
976}
977
978impl Write for &NamedTempFile<File> {
979    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
980        self.as_file().write(buf).with_err_path(|| self.path())
981    }
982    #[inline]
983    fn flush(&mut self) -> io::Result<()> {
984        self.as_file().flush().with_err_path(|| self.path())
985    }
986
987    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
988        self.as_file()
989            .write_vectored(bufs)
990            .with_err_path(|| self.path())
991    }
992
993    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
994        self.as_file().write_all(buf).with_err_path(|| self.path())
995    }
996
997    fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
998        self.as_file().write_fmt(fmt).with_err_path(|| self.path())
999    }
1000}
1001
1002impl<F: Seek> Seek for NamedTempFile<F> {
1003    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
1004        self.as_file_mut().seek(pos).with_err_path(|| self.path())
1005    }
1006}
1007
1008impl Seek for &NamedTempFile<File> {
1009    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
1010        self.as_file().seek(pos).with_err_path(|| self.path())
1011    }
1012}
1013
1014#[cfg(any(unix, target_os = "wasi"))]
1015impl<F: AsFd> AsFd for NamedTempFile<F> {
1016    fn as_fd(&self) -> BorrowedFd<'_> {
1017        self.as_file().as_fd()
1018    }
1019}
1020
1021#[cfg(any(unix, target_os = "wasi"))]
1022impl<F: AsRawFd> AsRawFd for NamedTempFile<F> {
1023    #[inline]
1024    fn as_raw_fd(&self) -> RawFd {
1025        self.as_file().as_raw_fd()
1026    }
1027}
1028
1029#[cfg(windows)]
1030impl<F: AsHandle> AsHandle for NamedTempFile<F> {
1031    #[inline]
1032    fn as_handle(&self) -> BorrowedHandle<'_> {
1033        self.as_file().as_handle()
1034    }
1035}
1036
1037#[cfg(windows)]
1038impl<F: AsRawHandle> AsRawHandle for NamedTempFile<F> {
1039    #[inline]
1040    fn as_raw_handle(&self) -> RawHandle {
1041        self.as_file().as_raw_handle()
1042    }
1043}
1044
1045pub(crate) fn create_named(
1046    mut path: PathBuf,
1047    open_options: &mut OpenOptions,
1048    permissions: Option<&std::fs::Permissions>,
1049    keep: bool,
1050) -> io::Result<NamedTempFile> {
1051    // Make the path absolute. Otherwise, changing directories could cause us to
1052    // delete the wrong file.
1053    if !path.is_absolute() {
1054        path = std::env::current_dir()?.join(path)
1055    }
1056    imp::create_named(&path, open_options, permissions)
1057        .with_err_path(|| path.clone())
1058        .map(|file| NamedTempFile {
1059            path: TempPath {
1060                path: path.into_boxed_path(),
1061                keep,
1062            },
1063            file,
1064        })
1065}