Debian Codegraph @

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

raw
1 use std::{
2 cell::UnsafeCell,
3 ffi::{OsStr, OsString},
4 fmt::{self, Write},
5 marker::PhantomData,
6 mem::MaybeUninit,
7 panic::{RefUnwindSafe, UnwindSafe},
8 path::Path,
9 sync::Once,
10 };
11
12 use crate::{Error, ErrorKind};
13
14 pub(super) struct JoinOsStrs<'a, T> {
15 pub(super) slice: &'a [T],
16 pub(super) delimiter: char,
17 }
18
19 impl<T> fmt::Display for JoinOsStrs<'_, T>
20 where
21 T: AsRef<OsStr>,
22 {
23 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24 let len = self.slice.len();
25 for (index, os_str) in self.slice.iter().enumerate() {
26 // TODO: Use OsStr::display once it is stablised,
27 // Path and OsStr has the same `Display` impl
28 write!(f, "{}", Path::new(os_str).display())?;
29 if index + 1 < len {
30 f.write_char(self.delimiter)?;
31 }
32 }
33 Ok(())
34 }
35 }
36
37 pub(super) struct OptionOsStrDisplay<T>(pub(super) Option<T>);
38
39 impl<T> fmt::Display for OptionOsStrDisplay<T>
40 where
41 T: AsRef<OsStr>,
42 {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 // TODO: Use OsStr::display once it is stablised
45 // Path and OsStr has the same `Display` impl
46 if let Some(os_str) = self.0.as_ref() {
47 write!(f, "Some({})", Path::new(os_str).display())
48 } else {
49 f.write_str("None")
50 }
51 }
52 }
53
54 pub(crate) struct OnceLock<T> {
55 once: Once,
56 value: UnsafeCell<MaybeUninit<T>>,
57 _marker: PhantomData<T>,
58 }
59
60 impl<T> Default for OnceLock<T> {
61 fn default() -> Self {
62 Self::new()
63 }
64 }
65
66 impl<T> OnceLock<T> {
67 pub(crate) const fn new() -> Self {
68 Self {
69 once: Once::new(),
70 value: UnsafeCell::new(MaybeUninit::uninit()),
71 _marker: PhantomData,
72 }
73 }
74
75 #[inline]
76 fn is_initialized(&self) -> bool {
77 self.once.is_completed()
78 }
79
80 unsafe fn get_unchecked(&self) -> &T {
81 debug_assert!(self.is_initialized());
82 #[allow(clippy::needless_borrow)]
83 #[allow(unused_unsafe)]
84 unsafe {
85 (&*self.value.get()).assume_init_ref()
86 }
87 }
88
89 pub(crate) fn get_or_init(&self, f: impl FnOnce() -> T) -> &T {
90 self.once.call_once(|| {
91 unsafe { &mut *self.value.get() }.write(f());
92 });
93 unsafe { self.get_unchecked() }
94 }
95
96 pub(crate) fn get(&self) -> Option<&T> {
97 if self.is_initialized() {
98 // Safe b/c checked is_initialized
99 Some(unsafe { self.get_unchecked() })
100 } else {
101 None
102 }
103 }
104 }
105
106 impl<T: fmt::Debug> fmt::Debug for OnceLock<T> {
107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108 let mut d = f.debug_tuple("OnceLock");
109 match self.get() {
110 Some(v) => d.field(v),
111 None => d.field(&format_args!("<uninit>")),
112 };
113 d.finish()
114 }
115 }
116
117 unsafe impl<T: Sync + Send> Sync for OnceLock<T> {}
118 unsafe impl<T: Send> Send for OnceLock<T> {}
119
120 impl<T: RefUnwindSafe + UnwindSafe> RefUnwindSafe for OnceLock<T> {}
121 impl<T: UnwindSafe> UnwindSafe for OnceLock<T> {}
122
123 impl<T> Drop for OnceLock<T> {
124 #[inline]
125 fn drop(&mut self) {
126 if self.once.is_completed() {
127 // SAFETY: The cell is initialized and being dropped, so it can't
128 // be accessed again.
129 unsafe { self.value.get_mut().assume_init_drop() };
130 }
131 }
132 }
133
134 /// Access an environment variable that's set by Cargo.
135 ///
136 /// <https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts>
137 ///
138 /// Cargo doesn't need to be told about these with `rerun-if-env-changed`, and
139 /// that we don't want to allow overwriting them with `Build::env`.
140 #[allow(clippy::disallowed_methods)] // Cargo env, no need for cache busting.
141 pub(crate) fn cargo_env_var_os(key: &str) -> Option<OsString> {
142 std::env::var_os(key)
143 }
144
145 pub(crate) fn cargo_env_var(key: &str) -> Result<String, Error> {
146 if let Some(value) = cargo_env_var_os(key) {
147 match value.into_string() {
148 Ok(value) => Ok(value),
149 Err(value) => Err(Error::new(
150 ErrorKind::EnvVarNotFound,
151 format!("environment variable {key} is not valid utf-8: {value:?}"),
152 )),
153 }
154 } else {
155 Err(Error::new(
156 ErrorKind::EnvVarNotFound,
157 format!("environment variable {key} not defined"),
158 ))
159 }
160 }