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, temporary files are, by default, created in per-user temporary
403/// file directories so only an application running as the same user would be
404/// able to interfere (which they could do anyways). However, an application
405/// running as the same user can still _accidentally_ re-create deleted
406/// temporary files if the number of random bytes in the temporary file name is
407/// too small.
408///
409/// ### MacOS
410///
411/// Like on Windows, temporary files are created in per-user temporary file
412/// directories by default so calling `NamedTempFile::new()` should be
413/// relatively safe.
414///
415/// ### Linux
416///
417/// Unfortunately, most _Linux_ distributions don't create per-user temporary
418/// file directories. Worse, systemd's tmpfiles daemon (a common temporary file
419/// cleaner) will happily remove open temporary files if they haven't been
420/// modified within the last 10 days.
421///
422/// # Resource Leaking
423///
424/// If the program exits before the `NamedTempFile` destructor is
425/// run, the temporary file will not be deleted. This can happen
426/// if the process exits using [`std::process::exit()`], a segfault occurs,
427/// receiving an interrupt signal like `SIGINT` that is not handled, or by using
428/// a statically declared `NamedTempFile` instance (like with [`lazy_static`]).
429///
430/// Use the [`tempfile()`] function unless you need a named file path.
431///
432/// [`tempfile()`]: fn.tempfile.html
433/// [`NamedTempFile::new()`]: #method.new
434/// [`NamedTempFile::new_in()`]: #method.new_in
435/// [`std::process::exit()`]: http://doc.rust-lang.org/std/process/fn.exit.html
436/// [`lazy_static`]: https://github.com/rust-lang-nursery/lazy-static.rs/issues/62
437pub struct NamedTempFile<F = File> {
438 path: TempPath,
439 file: F,
440}
441
442impl<F> fmt::Debug for NamedTempFile<F> {
443 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
444 write!(f, "NamedTempFile({:?})", self.path)
445 }
446}
447
448impl<F> AsRef<Path> for NamedTempFile<F> {
449 #[inline]
450 fn as_ref(&self) -> &Path {
451 self.path()
452 }
453}
454
455/// Error returned when persisting a temporary file fails.
456pub struct PersistError<F = File> {
457 /// The underlying IO error.
458 pub error: io::Error,
459 /// The temporary file that couldn't be persisted.
460 pub file: NamedTempFile<F>,
461}
462
463impl<F> fmt::Debug for PersistError<F> {
464 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465 write!(f, "PersistError({:?})", self.error)
466 }
467}
468
469impl<F> From<PersistError<F>> for io::Error {
470 #[inline]
471 fn from(error: PersistError<F>) -> io::Error {
472 error.error
473 }
474}
475
476impl<F> From<PersistError<F>> for NamedTempFile<F> {
477 #[inline]
478 fn from(error: PersistError<F>) -> NamedTempFile<F> {
479 error.file
480 }
481}
482
483impl<F> fmt::Display for PersistError<F> {
484 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
485 write!(f, "failed to persist temporary file: {}", self.error)
486 }
487}
488
489impl<F> error::Error for PersistError<F> {
490 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
491 Some(&self.error)
492 }
493}
494
495impl NamedTempFile<File> {
496 /// Create a new named temporary file.
497 ///
498 /// See [`Builder`] for more configuration.
499 ///
500 /// # Security
501 ///
502 /// This will create a temporary file in the default temporary file
503 /// directory (platform dependent). This has security implications on many
504 /// platforms so please read the security section of this type's
505 /// documentation.
506 ///
507 /// Reasons to use this method:
508 ///
509 /// 1. The file has a short lifetime and your temporary file cleaner is
510 /// sane (doesn't delete recently accessed files).
511 ///
512 /// 2. You trust every user on your system (i.e. you are the only user).
513 ///
514 /// 3. You have disabled your system's temporary file cleaner or verified
515 /// that your system doesn't have a temporary file cleaner.
516 ///
517 /// Reasons not to use this method:
518 ///
519 /// 1. You'll fix it later. No you won't.
520 ///
521 /// 2. You don't care about the security of the temporary file. If none of
522 /// the "reasons to use this method" apply, referring to a temporary
523 /// file by name may allow an attacker to create/overwrite your
524 /// non-temporary files. There are exceptions but if you don't already
525 /// know them, don't use this method.
526 ///
527 /// # Errors
528 ///
529 /// If the file can not be created, `Err` is returned.
530 ///
531 /// # Examples
532 ///
533 /// Create a named temporary file and write some data to it:
534 ///
535 /// ```no_run
536 /// use std::io::Write;
537 /// use tempfile::NamedTempFile;
538 ///
539 /// let mut file = NamedTempFile::new()?;
540 ///
541 /// writeln!(file, "Brian was here. Briefly.")?;
542 /// # Ok::<(), std::io::Error>(())
543 /// ```
544 ///
545 /// [`Builder`]: struct.Builder.html
546 pub fn new() -> io::Result<NamedTempFile> {
547 Builder::new().tempfile()
548 }
549
550 /// Create a new named temporary file in the specified directory.
551 ///
552 /// This is equivalent to:
553 ///
554 /// ```ignore
555 /// Builder::new().tempfile_in(dir)
556 /// ```
557 ///
558 /// See [`NamedTempFile::new()`] for details.
559 ///
560 /// [`NamedTempFile::new()`]: #method.new
561 pub fn new_in<P: AsRef<Path>>(dir: P) -> io::Result<NamedTempFile> {
562 Builder::new().tempfile_in(dir)
563 }
564
565 /// Create a new named temporary file with the specified filename suffix.
566 ///
567 /// See [`NamedTempFile::new()`] for details.
568 ///
569 /// [`NamedTempFile::new()`]: #method.new
570 pub fn with_suffix<S: AsRef<OsStr>>(suffix: S) -> io::Result<NamedTempFile> {
571 Builder::new().suffix(&suffix).tempfile()
572 }
573 /// Create a new named temporary file with the specified filename suffix,
574 /// in the specified directory.
575 ///
576 /// This is equivalent to:
577 ///
578 /// ```ignore
579 /// Builder::new().suffix(&suffix).tempfile_in(directory)
580 /// ```
581 ///
582 /// See [`NamedTempFile::new()`] for details.
583 ///
584 /// [`NamedTempFile::new()`]: #method.new
585 pub fn with_suffix_in<S: AsRef<OsStr>, P: AsRef<Path>>(
586 suffix: S,
587 dir: P,
588 ) -> io::Result<NamedTempFile> {
589 Builder::new().suffix(&suffix).tempfile_in(dir)
590 }
591
592 /// Create a new named temporary file with the specified filename prefix.
593 ///
594 /// See [`NamedTempFile::new()`] for details.
595 ///
596 /// [`NamedTempFile::new()`]: #method.new
597 pub fn with_prefix<S: AsRef<OsStr>>(prefix: S) -> io::Result<NamedTempFile> {
598 Builder::new().prefix(&prefix).tempfile()
599 }
600 /// Create a new named temporary file with the specified filename prefix,
601 /// in the specified directory.
602 ///
603 /// This is equivalent to:
604 ///
605 /// ```ignore
606 /// Builder::new().prefix(&prefix).tempfile_in(directory)
607 /// ```
608 ///
609 /// See [`NamedTempFile::new()`] for details.
610 ///
611 /// [`NamedTempFile::new()`]: #method.new
612 pub fn with_prefix_in<S: AsRef<OsStr>, P: AsRef<Path>>(
613 prefix: S,
614 dir: P,
615 ) -> io::Result<NamedTempFile> {
616 Builder::new().prefix(&prefix).tempfile_in(dir)
617 }
618}
619
620impl<F> NamedTempFile<F> {
621 /// Get the temporary file's path.
622 ///
623 /// # Security
624 ///
625 /// Referring to a temporary file's path may not be secure in all cases.
626 /// Please read the security section on the top level documentation of this
627 /// type for details.
628 ///
629 /// # Examples
630 ///
631 /// ```no_run
632 /// use tempfile::NamedTempFile;
633 ///
634 /// let file = NamedTempFile::new()?;
635 ///
636 /// println!("{:?}", file.path());
637 /// # Ok::<(), std::io::Error>(())
638 /// ```
639 #[inline]
640 pub fn path(&self) -> &Path {
641 &self.path
642 }
643
644 /// Close and remove the temporary file.
645 ///
646 /// Use this if you want to detect errors in deleting the file.
647 ///
648 /// # Errors
649 ///
650 /// If the file cannot be deleted, `Err` is returned.
651 ///
652 /// # Examples
653 ///
654 /// ```no_run
655 /// use tempfile::NamedTempFile;
656 ///
657 /// let file = NamedTempFile::new()?;
658 ///
659 /// // By closing the `NamedTempFile` explicitly, we can check that it has
660 /// // been deleted successfully. If we don't close it explicitly,
661 /// // the file will still be deleted when `file` goes out
662 /// // of scope, but we won't know whether deleting the file
663 /// // succeeded.
664 /// file.close()?;
665 /// # Ok::<(), std::io::Error>(())
666 /// ```
667 pub fn close(self) -> io::Result<()> {
668 let NamedTempFile { path, .. } = self;
669 path.close()
670 }
671
672 /// Persist the temporary file at the target path.
673 ///
674 /// If a file exists at the target path, persist will atomically replace it.
675 /// If this method fails, it will return `self` in the resulting
676 /// [`PersistError`].
677 ///
678 /// Note: Temporary files cannot be persisted across filesystems. Also
679 /// neither the file contents nor the containing directory are
680 /// synchronized, so the update may not yet have reached the disk when
681 /// `persist` returns.
682 ///
683 /// # Security
684 ///
685 /// This method persists the temporary file using its path and may not be
686 /// secure in all cases. Please read the security section on the top
687 /// level documentation of this type for details.
688 ///
689 /// # Errors
690 ///
691 /// If the file cannot be moved to the new location, `Err` is returned.
692 ///
693 /// # Examples
694 ///
695 /// ```no_run
696 /// use std::io::Write;
697 /// use tempfile::NamedTempFile;
698 ///
699 /// let file = NamedTempFile::new()?;
700 ///
701 /// let mut persisted_file = file.persist("./saved_file.txt")?;
702 /// writeln!(persisted_file, "Brian was here. Briefly.")?;
703 /// # Ok::<(), std::io::Error>(())
704 /// ```
705 ///
706 /// [`PersistError`]: struct.PersistError.html
707 pub fn persist<P: AsRef<Path>>(self, new_path: P) -> Result<F, PersistError<F>> {
708 let NamedTempFile { path, file } = self;
709 match path.persist(new_path) {
710 Ok(_) => Ok(file),
711 Err(err) => {
712 let PathPersistError { error, path } = err;
713 Err(PersistError {
714 file: NamedTempFile { path, file },
715 error,
716 })
717 }
718 }
719 }
720
721 /// Persist the temporary file at the target path if and only if no file exists there.
722 ///
723 /// If a file exists at the target path, fail. If this method fails, it will
724 /// return `self` in the resulting PersistError.
725 ///
726 /// Note: Temporary files cannot be persisted across filesystems. Also Note:
727 /// This method is not atomic. It can leave the original link to the
728 /// temporary file behind.
729 ///
730 /// # Security
731 ///
732 /// This method persists the temporary file using its path and may not be
733 /// secure in all cases. Please read the security section on the top
734 /// level documentation of this type for details.
735 ///
736 /// # Errors
737 ///
738 /// If the file cannot be moved to the new location or a file already exists there,
739 /// `Err` is returned.
740 ///
741 /// # Examples
742 ///
743 /// ```no_run
744 /// use std::io::Write;
745 /// use tempfile::NamedTempFile;
746 ///
747 /// let file = NamedTempFile::new()?;
748 ///
749 /// let mut persisted_file = file.persist_noclobber("./saved_file.txt")?;
750 /// writeln!(persisted_file, "Brian was here. Briefly.")?;
751 /// # Ok::<(), std::io::Error>(())
752 /// ```
753 pub fn persist_noclobber<P: AsRef<Path>>(self, new_path: P) -> Result<F, PersistError<F>> {
754 let NamedTempFile { path, file } = self;
755 match path.persist_noclobber(new_path) {
756 Ok(_) => Ok(file),
757 Err(err) => {
758 let PathPersistError { error, path } = err;
759 Err(PersistError {
760 file: NamedTempFile { path, file },
761 error,
762 })
763 }
764 }
765 }
766
767 /// Keep the temporary file from being deleted. This function will turn the
768 /// temporary file into a non-temporary file without moving it.
769 ///
770 ///
771 /// # Errors
772 ///
773 /// On some platforms (e.g., Windows), we need to mark the file as
774 /// non-temporary. This operation could fail.
775 ///
776 /// # Examples
777 ///
778 /// ```no_run
779 /// use std::io::Write;
780 /// use tempfile::NamedTempFile;
781 ///
782 /// let mut file = NamedTempFile::new()?;
783 /// writeln!(file, "Brian was here. Briefly.")?;
784 ///
785 /// let (file, path) = file.keep()?;
786 /// # Ok::<(), std::io::Error>(())
787 /// ```
788 ///
789 /// [`PathPersistError`]: struct.PathPersistError.html
790 pub fn keep(self) -> Result<(F, PathBuf), PersistError<F>> {
791 let (file, path) = (self.file, self.path);
792 match path.keep() {
793 Ok(path) => Ok((file, path)),
794 Err(PathPersistError { error, path }) => Err(PersistError {
795 file: NamedTempFile { path, file },
796 error,
797 }),
798 }
799 }
800
801 /// Get a reference to the underlying file.
802 pub fn as_file(&self) -> &F {
803 &self.file
804 }
805
806 /// Get a mutable reference to the underlying file.
807 pub fn as_file_mut(&mut self) -> &mut F {
808 &mut self.file
809 }
810
811 /// Turn this named temporary file into an "unnamed" temporary file as if you
812 /// had constructed it with [`tempfile()`].
813 ///
814 /// The underlying file will be removed from the filesystem but the returned [`File`]
815 /// can still be read/written.
816 pub fn into_file(self) -> F {
817 self.file
818 }
819
820 /// Closes the file, leaving only the temporary file path.
821 ///
822 /// This is useful when another process must be able to open the temporary
823 /// file.
824 pub fn into_temp_path(self) -> TempPath {
825 self.path
826 }
827
828 /// Converts the named temporary file into its constituent parts.
829 ///
830 /// Note: When the path is dropped, the underlying file will be removed from the filesystem but
831 /// the returned [`File`] can still be read/written.
832 pub fn into_parts(self) -> (F, TempPath) {
833 (self.file, self.path)
834 }
835
836 /// Creates a `NamedTempFile` from its constituent parts.
837 ///
838 /// This can be used with [`NamedTempFile::into_parts`] to reconstruct the
839 /// `NamedTempFile`.
840 pub fn from_parts(file: F, path: TempPath) -> Self {
841 Self { file, path }
842 }
843}
844
845impl NamedTempFile<File> {
846 /// Securely reopen the temporary file.
847 ///
848 /// This function is useful when you need multiple independent handles to
849 /// the same file. It's perfectly fine to drop the original `NamedTempFile`
850 /// while holding on to `File`s returned by this function; the `File`s will
851 /// remain usable. However, they may not be nameable.
852 ///
853 /// # Errors
854 ///
855 /// If the file cannot be reopened, `Err` is returned.
856 ///
857 /// # Security
858 ///
859 /// Unlike `File::open(my_temp_file.path())`, `NamedTempFile::reopen()`
860 /// guarantees that the re-opened file is the _same_ file, even in the
861 /// presence of pathological temporary file cleaners.
862 ///
863 /// # Examples
864 ///
865 /// ```no_run
866 /// use tempfile::NamedTempFile;
867 ///
868 /// let file = NamedTempFile::new()?;
869 ///
870 /// let another_handle = file.reopen()?;
871 /// # Ok::<(), std::io::Error>(())
872 /// ```
873 pub fn reopen(&self) -> io::Result<File> {
874 imp::reopen(self.as_file(), NamedTempFile::path(self))
875 .with_err_path(|| NamedTempFile::path(self))
876 }
877}
878
879impl<F: Read> Read for NamedTempFile<F> {
880 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
881 self.as_file_mut().read(buf).with_err_path(|| self.path())
882 }
883
884 fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
885 self.as_file_mut()
886 .read_vectored(bufs)
887 .with_err_path(|| self.path())
888 }
889
890 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
891 self.as_file_mut()
892 .read_to_end(buf)
893 .with_err_path(|| self.path())
894 }
895
896 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
897 self.as_file_mut()
898 .read_to_string(buf)
899 .with_err_path(|| self.path())
900 }
901
902 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
903 self.as_file_mut()
904 .read_exact(buf)
905 .with_err_path(|| self.path())
906 }
907}
908
909impl Read for &NamedTempFile<File> {
910 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
911 self.as_file().read(buf).with_err_path(|| self.path())
912 }
913
914 fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
915 self.as_file()
916 .read_vectored(bufs)
917 .with_err_path(|| self.path())
918 }
919
920 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
921 self.as_file()
922 .read_to_end(buf)
923 .with_err_path(|| self.path())
924 }
925
926 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
927 self.as_file()
928 .read_to_string(buf)
929 .with_err_path(|| self.path())
930 }
931
932 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
933 self.as_file().read_exact(buf).with_err_path(|| self.path())
934 }
935}
936
937impl<F: Write> Write for NamedTempFile<F> {
938 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
939 self.as_file_mut().write(buf).with_err_path(|| self.path())
940 }
941 #[inline]
942 fn flush(&mut self) -> io::Result<()> {
943 self.as_file_mut().flush().with_err_path(|| self.path())
944 }
945
946 fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
947 self.as_file_mut()
948 .write_vectored(bufs)
949 .with_err_path(|| self.path())
950 }
951
952 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
953 self.as_file_mut()
954 .write_all(buf)
955 .with_err_path(|| self.path())
956 }
957
958 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
959 self.as_file_mut()
960 .write_fmt(fmt)
961 .with_err_path(|| self.path())
962 }
963}
964
965impl Write for &NamedTempFile<File> {
966 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
967 self.as_file().write(buf).with_err_path(|| self.path())
968 }
969 #[inline]
970 fn flush(&mut self) -> io::Result<()> {
971 self.as_file().flush().with_err_path(|| self.path())
972 }
973
974 fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
975 self.as_file()
976 .write_vectored(bufs)
977 .with_err_path(|| self.path())
978 }
979
980 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
981 self.as_file().write_all(buf).with_err_path(|| self.path())
982 }
983
984 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
985 self.as_file().write_fmt(fmt).with_err_path(|| self.path())
986 }
987}
988
989impl<F: Seek> Seek for NamedTempFile<F> {
990 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
991 self.as_file_mut().seek(pos).with_err_path(|| self.path())
992 }
993}
994
995impl Seek for &NamedTempFile<File> {
996 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
997 self.as_file().seek(pos).with_err_path(|| self.path())
998 }
999}
1000
1001#[cfg(any(unix, target_os = "wasi"))]
1002impl<F: AsFd> AsFd for NamedTempFile<F> {
1003 fn as_fd(&self) -> BorrowedFd<'_> {
1004 self.as_file().as_fd()
1005 }
1006}
1007
1008#[cfg(any(unix, target_os = "wasi"))]
1009impl<F: AsRawFd> AsRawFd for NamedTempFile<F> {
1010 #[inline]
1011 fn as_raw_fd(&self) -> RawFd {
1012 self.as_file().as_raw_fd()
1013 }
1014}
1015
1016#[cfg(windows)]
1017impl<F: AsHandle> AsHandle for NamedTempFile<F> {
1018 #[inline]
1019 fn as_handle(&self) -> BorrowedHandle<'_> {
1020 self.as_file().as_handle()
1021 }
1022}
1023
1024#[cfg(windows)]
1025impl<F: AsRawHandle> AsRawHandle for NamedTempFile<F> {
1026 #[inline]
1027 fn as_raw_handle(&self) -> RawHandle {
1028 self.as_file().as_raw_handle()
1029 }
1030}
1031
1032pub(crate) fn create_named(
1033 path: PathBuf,
1034 open_options: &mut OpenOptions,
1035 permissions: Option<&std::fs::Permissions>,
1036 keep: bool,
1037) -> io::Result<NamedTempFile> {
1038 imp::create_named(&path, open_options, permissions)
1039 .with_err_path(|| path.clone())
1040 .map(|file| NamedTempFile {
1041 path: TempPath {
1042 path: path.into_boxed_path(),
1043 keep,
1044 },
1045 file,
1046 })
1047}