Debian Codegraph @

src/platform/req.rs

raw symbols SCIP
1 //! Platform requirements
2
3 use crate::error::Error;
4 use crate::platform::Platform;
5 use std::{fmt, str::FromStr, string::String};
6
7 #[cfg(feature = "serde")]
8 use serde::{de, ser, Deserialize, Serialize};
9
10 /// Platform requirements: glob-like expressions for matching Rust platforms
11 /// as identified by a "target triple", e.g. `i686-apple-darwin`.
12 ///
13 /// For a list of all valid platforms, "target triples", see:
14 ///
15 /// <https://doc.rust-lang.org/nightly/rustc/platform-support.html>
16 ///
17 /// Platforms can be grouped with simple globbing rules:
18 ///
19 /// - Start with wildcard: `*-gnu`
20 /// - End with wildcard: `x86_64-*`
21 /// - Start and end with wildcard: `*windows*`
22 #[derive(Clone, Debug, Eq, PartialEq)]
23 pub struct PlatformReq(String);
24
25 /// Wildcard character used for globbing
26 pub const WILDCARD: char = '*';
27
28 impl PlatformReq {
29 /// Borrow this platform requirement as a string slice
30 pub fn as_str(&self) -> &str {
31 self.0.as_ref()
32 }
33
34 /// Does this platform requirement match the given platform string?
35 ///
36 /// This matcher accepts a platform "target triple" string ala
37 /// `x86_64-unknown-linux-gnu` and matches it against this
38 /// `Platform`, using simple glob like rules.
39 pub fn matches(&self, platform: &Platform) -> bool {
40 let self_len = self.as_str().len();
41
42 // Universal matcher
43 if self.0.len() == 1 && self.0.chars().next().unwrap() == WILDCARD {
44 return true;
45 }
46
47 let mut chars = self.as_str().chars();
48 let starts_with_wildcard = chars.next().unwrap() == WILDCARD;
49 let ends_with_wildcard = chars.last() == Some(WILDCARD);
50
51 if starts_with_wildcard {
52 if ends_with_wildcard {
53 // Contains expression: `*windows*`
54 platform
55 .target_triple
56 .contains(&self.0[1..self_len.checked_sub(1).unwrap()])
57 } else {
58 // Suffix expression: `*-gnu`
59 platform.target_triple.ends_with(&self.0[1..])
60 }
61 } else if ends_with_wildcard {
62 // Prefix expression: `x86_64-*`
63 platform
64 .target_triple
65 .starts_with(&self.0[..self_len.checked_sub(1).unwrap()])
66 } else {
67 // No wildcards: direct comparison
68 self.as_str() == platform.target_triple
69 }
70 }
71
72 /// Expand glob expressions into a list of all known matching platforms
73 pub fn matching_platforms(&self) -> impl Iterator<Item = &Platform> {
74 matching_platforms(self, Platform::ALL)
75 }
76 }
77
78 // Split into its own function for unit testing
79 #[inline]
80 fn matching_platforms<'a>(
81 req: &'a PlatformReq,
82 platforms: &'a [Platform],
83 ) -> impl Iterator<Item = &'a Platform> {
84 platforms
85 .iter()
86 .filter(move |&platform| req.matches(platform))
87 }
88
89 impl FromStr for PlatformReq {
90 type Err = Error;
91
92 /// Create a new platform requirement. Platforms support glob-like
93 /// wildcards on the beginning and end, e.g. `*windows*`.
94 ///
95 /// Must match at least one known Rust platform "target triple"
96 /// (e.g. `x86_64-unknown-linux-gnu`) to be considered valid.
97 fn from_str(req_str: &str) -> Result<PlatformReq, Error> {
98 let platform_req = PlatformReq(req_str.into());
99
100 if platform_req.0.is_empty() || platform_req.matching_platforms().next().is_none() {
101 Err(Error)
102 } else {
103 Ok(platform_req)
104 }
105 }
106 }
107
108 impl fmt::Display for PlatformReq {
109 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110 f.write_str(self.as_str())
111 }
112 }
113
114 #[cfg(feature = "serde")]
115 impl Serialize for PlatformReq {
116 fn serialize<S: ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
117 serializer.serialize_str(self.as_str())
118 }
119 }
120
121 #[cfg(feature = "serde")]
122 impl<'de> Deserialize<'de> for PlatformReq {
123 fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
124 use de::Error;
125 String::deserialize(deserializer)?
126 .parse()
127 .map_err(D::Error::custom)
128 }
129 }
130
131 #[cfg(test)]
132 mod tests {
133 use super::*;
134 use std::{str::FromStr, vec::Vec};
135
136 use crate::platform::platforms::*;
137 const TEST_PLATFORM_LIST: &[Platform] = &[
138 AARCH64_PC_WINDOWS_MSVC,
139 AARCH64_UNKNOWN_LINUX_MUSL,
140 ARMV7_UNKNOWN_LINUX_MUSLEABI,
141 ARMV7_UNKNOWN_LINUX_MUSLEABIHF,
142 SPARC_UNKNOWN_LINUX_GNU,
143 SPARC64_UNKNOWN_LINUX_GNU,
144 SPARC64_UNKNOWN_NETBSD,
145 SPARC64_UNKNOWN_OPENBSD,
146 SPARCV9_SUN_SOLARIS,
147 AARCH64_UWP_WINDOWS_MSVC,
148 I686_PC_WINDOWS_GNU,
149 I686_PC_WINDOWS_MSVC,
150 I686_UWP_WINDOWS_GNU,
151 I686_UWP_WINDOWS_MSVC,
152 MIPS64_UNKNOWN_LINUX_GNUABI64,
153 MIPS64_UNKNOWN_LINUX_MUSLABI64,
154 THUMBV7A_PC_WINDOWS_MSVC,
155 THUMBV7A_UWP_WINDOWS_MSVC,
156 RISCV64GC_UNKNOWN_LINUX_MUSL,
157 X86_64_PC_WINDOWS_GNU,
158 ];
159
160 #[test]
161 fn prefix_glob_test() {
162 let req = PlatformReq::from_str("sparc*").unwrap();
163
164 assert_eq!(
165 matching_platforms(&req, TEST_PLATFORM_LIST)
166 .map(|p| p.target_triple)
167 .collect::<Vec<_>>(),
168 [
169 "sparc-unknown-linux-gnu",
170 "sparc64-unknown-linux-gnu",
171 "sparc64-unknown-netbsd",
172 "sparc64-unknown-openbsd",
173 "sparcv9-sun-solaris"
174 ]
175 );
176 }
177
178 #[test]
179 fn suffix_glob_test() {
180 let req = PlatformReq::from_str("*-musl").unwrap();
181
182 assert_eq!(
183 matching_platforms(&req, TEST_PLATFORM_LIST)
184 .map(|p| p.target_triple)
185 .collect::<Vec<_>>(),
186 ["aarch64-unknown-linux-musl", "riscv64gc-unknown-linux-musl"]
187 );
188 }
189
190 #[test]
191 fn contains_glob_test() {
192 let req = PlatformReq::from_str("*windows*").unwrap();
193
194 assert_eq!(
195 matching_platforms(&req, TEST_PLATFORM_LIST)
196 .map(|p| p.target_triple)
197 .collect::<Vec<_>>(),
198 [
199 "aarch64-pc-windows-msvc",
200 "aarch64-uwp-windows-msvc",
201 "i686-pc-windows-gnu",
202 "i686-pc-windows-msvc",
203 "i686-uwp-windows-gnu",
204 "i686-uwp-windows-msvc",
205 "thumbv7a-pc-windows-msvc",
206 "thumbv7a-uwp-windows-msvc",
207 "x86_64-pc-windows-gnu",
208 ]
209 );
210 }
211
212 #[test]
213 fn direct_match_test() {
214 let req = PlatformReq::from_str("x86_64-unknown-dragonfly").unwrap();
215
216 assert_eq!(
217 req.matching_platforms()
218 .map(|p| p.target_triple)
219 .collect::<Vec<_>>(),
220 ["x86_64-unknown-dragonfly"]
221 );
222 }
223
224 #[test]
225 fn wildcard_test() {
226 let req = PlatformReq::from_str("*").unwrap();
227 assert_eq!(req.matching_platforms().count(), Platform::ALL.len())
228 }
229
230 // How to handle this is debatable...
231 #[test]
232 fn double_wildcard_test() {
233 let req = PlatformReq::from_str("**").unwrap();
234 assert_eq!(req.matching_platforms().count(), Platform::ALL.len())
235 }
236
237 #[test]
238 fn invalid_req_tests() {
239 assert!(PlatformReq::from_str("").is_err());
240 assert!(PlatformReq::from_str(" ").is_err());
241 assert!(PlatformReq::from_str("derp").is_err());
242 assert!(PlatformReq::from_str("***").is_err());
243 }
244 }