Debian Codegraph @

debian/rust-vendor/cc/src/tempfile.rs

raw
1 #![cfg_attr(target_family = "wasm", allow(unused))]
2
3 #[cfg(any(all(unix, not(target_os = "wasi")), windows))]
4 use std::os;
5
6 use std::{
7 collections::hash_map::RandomState,
8 fs::{remove_file, File, OpenOptions},
9 hash::{BuildHasher, Hasher},
10 io,
11 path::{Path, PathBuf},
12 };
13
14 #[cfg(not(any(unix, target_family = "wasm", windows, target_os = "motor")))]
15 compile_error!("Your system is not supported since cc cannot create named tempfile");
16
17 fn rand() -> u64 {
18 RandomState::new().build_hasher().finish()
19 }
20
21 fn tmpname(suffix: &str) -> String {
22 format!("{}{}", rand(), suffix)
23 }
24
25 fn create_named(path: &Path) -> io::Result<File> {
26 let mut open_options = OpenOptions::new();
27
28 open_options.read(true).write(true).create_new(true);
29
30 #[cfg(all(unix, not(target_os = "wasi")))]
31 <OpenOptions as os::unix::fs::OpenOptionsExt>::mode(&mut open_options, 0o600);
32
33 #[cfg(windows)]
34 <OpenOptions as os::windows::fs::OpenOptionsExt>::custom_flags(
35 &mut open_options,
36 ::find_msvc_tools::windows_sys::FILE_ATTRIBUTE_TEMPORARY,
37 );
38
39 open_options.open(path)
40 }
41
42 pub(super) struct NamedTempfile {
43 path: PathBuf,
44 file: Option<File>,
45 }
46
47 impl NamedTempfile {
48 pub(super) fn new(base: &Path, suffix: &str) -> io::Result<Self> {
49 for _ in 0..10 {
50 let path = base.join(tmpname(suffix));
51 match create_named(&path) {
52 Ok(file) => {
53 return Ok(Self {
54 file: Some(file),
55 path,
56 })
57 }
58 Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
59 Err(e) => return Err(e),
60 };
61 }
62
63 Err(io::Error::new(
64 io::ErrorKind::AlreadyExists,
65 format!(
66 "too many temporary files exist in base `{}` with suffix `{}`",
67 base.display(),
68 suffix
69 ),
70 ))
71 }
72
73 pub(super) fn path(&self) -> &Path {
74 &self.path
75 }
76
77 pub(super) fn take_file(&mut self) -> Option<File> {
78 self.file.take()
79 }
80 }
81
82 impl Drop for NamedTempfile {
83 fn drop(&mut self) {
84 // On Windows you have to close all handle to it before
85 // removing the file.
86 self.file.take();
87 let _ = remove_file(&self.path);
88 }
89 }