1use std::fmt;
6use std::str::FromStr;
7use std::sync::LazyLock;
8
9use regex::Regex;
10
11use crate::config::{
12 MAX_CRATE_NAME_CHARS, MAX_ITEM_PATH_CHARS, MAX_QUERY_CHARS, MAX_VERSION_CHARS,
13};
14use crate::error::{AppError, AppResult, ErrorKind};
15
16#[derive(Debug, Clone, PartialEq, Eq, Hash)]
18pub struct CrateName(String);
19
20impl CrateName {
21 pub fn parse(name: &str) -> AppResult<Self> {
38 let name = name.trim();
39 if name.is_empty() {
40 return Err(AppError::new(
41 ErrorKind::InvalidInput,
42 "crate name is empty",
43 ));
44 }
45 if name.chars().count() > MAX_CRATE_NAME_CHARS {
46 return Err(AppError::new(
47 ErrorKind::InvalidInput,
48 format!("crate name exceeds {MAX_CRATE_NAME_CHARS} characters"),
49 ));
50 }
51 static RE: LazyLock<Regex> = LazyLock::new(|| {
52 Regex::new(r"^[a-zA-Z][a-zA-Z0-9_-]*$")
53 .expect("hardcoded crate-name regex is valid by construction")
54 });
55 if !RE.is_match(name) {
56 return Err(AppError::new(
57 ErrorKind::InvalidInput,
58 format!("invalid crate name '{name}'"),
59 ));
60 }
61 Ok(Self(name.to_string()))
62 }
63
64 pub fn as_str(&self) -> &str {
66 &self.0
67 }
68
69 pub fn is_stdlib(&self) -> bool {
71 matches!(self.0.as_str(), "std" | "core" | "alloc")
72 }
73}
74
75impl AsRef<str> for CrateName {
76 fn as_ref(&self) -> &str {
77 self.as_str()
78 }
79}
80
81impl fmt::Display for CrateName {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 f.write_str(self.as_str())
84 }
85}
86
87impl FromStr for CrateName {
88 type Err = AppError;
89
90 fn from_str(s: &str) -> Result<Self, Self::Err> {
96 Self::parse(s)
97 }
98}
99
100impl TryFrom<&str> for CrateName {
101 type Error = AppError;
102
103 fn try_from(value: &str) -> Result<Self, Self::Error> {
109 Self::parse(value)
110 }
111}
112
113#[derive(Debug, Clone, PartialEq, Eq, Hash)]
115pub struct ItemPath {
116 raw: String,
118 segments: Vec<String>,
120}
121
122impl ItemPath {
123 pub fn parse(path: &str) -> AppResult<Self> {
130 let path = path.trim();
131 if path.is_empty() || path == "::" || path == "/" {
132 return Err(AppError::new(ErrorKind::InvalidInput, "item path is empty"));
133 }
134 if path.chars().count() > MAX_ITEM_PATH_CHARS {
135 return Err(AppError::new(
136 ErrorKind::InvalidInput,
137 format!("item path exceeds {MAX_ITEM_PATH_CHARS} characters"),
138 ));
139 }
140 let normalized = path.replace('/', "::");
141 let parts: Vec<String> = normalized
142 .split("::")
143 .map(|s| s.trim().to_string())
144 .filter(|s| !s.is_empty())
145 .collect();
146 if parts.is_empty() {
147 return Err(AppError::new(
148 ErrorKind::InvalidInput,
149 "item path has no segments",
150 ));
151 }
152 let mut segments = Vec::with_capacity(parts.len());
153 for seg in &parts {
154 if seg == "." || seg == ".." {
155 return Err(AppError::new(
156 ErrorKind::InvalidInput,
157 format!("invalid item path segment '{seg}'"),
158 ));
159 }
160 if seg.chars().any(|c| c.is_whitespace()) {
161 return Err(AppError::new(
162 ErrorKind::InvalidInput,
163 format!("item path segment contains whitespace: '{seg}'"),
164 ));
165 }
166 if !seg
168 .chars()
169 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
170 {
171 return Err(AppError::new(
172 ErrorKind::InvalidInput,
173 format!(
174 "invalid item path segment '{seg}' (use letters, digits, underscore or hyphen; hyphens normalize to underscore; separate with :: or /)"
175 ),
176 ));
177 }
178 segments.push(crate::item_kind::rustc_crate_name(seg));
179 }
180 Ok(Self {
181 raw: path.to_string(),
182 segments,
183 })
184 }
185
186 pub fn segments(&self) -> &[String] {
188 &self.segments
189 }
190
191 pub fn into_segments(self) -> Vec<String> {
193 self.segments
194 }
195
196 pub fn as_str(&self) -> &str {
198 &self.raw
199 }
200}
201
202impl AsRef<str> for ItemPath {
203 fn as_ref(&self) -> &str {
204 self.as_str()
205 }
206}
207
208impl fmt::Display for ItemPath {
209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 f.write_str(&self.segments.join("::"))
211 }
212}
213
214impl FromStr for ItemPath {
215 type Err = AppError;
216
217 fn from_str(s: &str) -> Result<Self, Self::Err> {
223 Self::parse(s)
224 }
225}
226
227#[derive(Debug, Clone, PartialEq, Eq, Hash)]
229pub struct SearchQuery(String);
230
231impl SearchQuery {
232 pub fn parse(query: &str, allow_empty: bool) -> AppResult<Self> {
241 let q = query.trim();
242 if !allow_empty && q.is_empty() {
243 return Err(AppError::new(
244 ErrorKind::InvalidInput,
245 "search query is empty",
246 ));
247 }
248 if q.chars().count() > MAX_QUERY_CHARS {
249 return Err(AppError::new(
250 ErrorKind::InvalidInput,
251 format!("query exceeds {MAX_QUERY_CHARS} characters"),
252 ));
253 }
254 Ok(Self(q.to_string()))
255 }
256
257 pub fn as_str(&self) -> &str {
259 &self.0
260 }
261}
262
263impl AsRef<str> for SearchQuery {
264 fn as_ref(&self) -> &str {
265 self.as_str()
266 }
267}
268
269impl fmt::Display for SearchQuery {
270 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271 f.write_str(self.as_str())
272 }
273}
274
275#[derive(Debug, Clone, PartialEq, Eq, Hash)]
277pub struct VersionArg(String);
278
279impl VersionArg {
280 pub fn parse_opt(raw: Option<&str>) -> AppResult<Self> {
287 let v = raw
288 .map(str::trim)
289 .filter(|s| !s.is_empty())
290 .unwrap_or("latest");
291 Self::parse(v)
292 }
293
294 pub fn parse(v: &str) -> AppResult<Self> {
301 let v = v.trim();
302 if v.chars().count() > MAX_VERSION_CHARS {
303 return Err(AppError::new(
304 ErrorKind::InvalidInput,
305 format!("version exceeds {MAX_VERSION_CHARS} characters"),
306 ));
307 }
308 if v == "latest" {
309 return Ok(Self(v.to_string()));
310 }
311 if matches!(v, "stable" | "beta" | "nightly") {
312 return Ok(Self(v.to_string()));
313 }
314 if v.starts_with('v') || v.starts_with('V') {
315 return Err(AppError::new(
316 ErrorKind::InvalidInput,
317 "version must not start with 'v' prefix",
318 ));
319 }
320 if v.contains('+') {
321 return Err(AppError::new(
322 ErrorKind::InvalidInput,
323 "version build metadata is not accepted",
324 ));
325 }
326 static RE: LazyLock<Regex> = LazyLock::new(|| {
327 Regex::new(r"^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$")
328 .expect("hardcoded semver-ish version regex is valid by construction")
329 });
330 if !RE.is_match(v) {
331 return Err(AppError::new(
332 ErrorKind::InvalidInput,
333 format!("invalid version '{v}'"),
334 ));
335 }
336 Ok(Self(v.to_string()))
337 }
338
339 pub fn as_str(&self) -> &str {
341 &self.0
342 }
343
344 pub fn stdlib_channel(&self) -> &str {
346 crate::config::stdlib_channel(self.as_str())
347 }
348}
349
350impl AsRef<str> for VersionArg {
351 fn as_ref(&self) -> &str {
352 self.as_str()
353 }
354}
355
356impl fmt::Display for VersionArg {
357 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
358 f.write_str(self.as_str())
359 }
360}
361
362impl FromStr for VersionArg {
363 type Err = AppError;
364
365 fn from_str(s: &str) -> Result<Self, Self::Err> {
371 Self::parse(s)
372 }
373}
374
375#[cfg(test)]
376mod tests {
377 use super::*;
378
379 #[test]
380 fn crate_name_ok_and_stdlib() {
381 let s = CrateName::parse("serde").unwrap();
382 assert_eq!(s.as_str(), "serde");
383 assert!(!s.is_stdlib());
384 assert!(CrateName::parse("async-trait").unwrap().as_str() == "async-trait");
385 for n in ["std", "core", "alloc"] {
386 let c = CrateName::parse(n).unwrap();
387 assert!(c.is_stdlib(), "{n}");
388 }
389 }
390
391 #[test]
392 fn crate_name_err() {
393 assert!(CrateName::parse("").is_err());
394 assert!(CrateName::parse("1bad").is_err());
395 assert!(CrateName::parse(&"a".repeat(MAX_CRATE_NAME_CHARS + 1)).is_err());
396 }
397
398 #[test]
399 fn item_path_segments_and_display() {
400 let p = ItemPath::parse("clap::Parser").unwrap();
401 assert_eq!(p.segments(), &["clap".to_string(), "Parser".to_string()]);
402 assert_eq!(p.to_string(), "clap::Parser");
403 let slash = ItemPath::parse("runtime/Runtime").unwrap();
404 assert_eq!(
405 slash.segments(),
406 &["runtime".to_string(), "Runtime".to_string()]
407 );
408 assert_eq!(
409 ItemPath::parse("async_trait").unwrap().segments(),
410 &["async_trait".to_string()]
411 );
412 assert_eq!(
414 ItemPath::parse("async-trait").unwrap().segments(),
415 &["async_trait".to_string()]
416 );
417 assert_eq!(
418 ItemPath::parse("foo-bar::Baz-Quux").unwrap().segments(),
419 &["foo_bar".to_string(), "Baz_Quux".to_string()]
420 );
421 }
422
423 #[test]
424 fn item_path_err() {
425 assert!(ItemPath::parse("").is_err());
426 assert!(ItemPath::parse("::").is_err());
427 assert!(ItemPath::parse("has space").is_err());
428 assert!(ItemPath::parse("foo.bar").is_err());
429 assert!(ItemPath::parse("..").is_err());
430 assert!(ItemPath::parse("a/../b").is_err());
431 }
432
433 #[test]
434 fn search_query_rules() {
435 assert!(SearchQuery::parse("", false).is_err());
436 assert_eq!(SearchQuery::parse(" ", true).unwrap().as_str(), "");
437 assert_eq!(
438 SearchQuery::parse("serde", false).unwrap().as_str(),
439 "serde"
440 );
441 assert!(SearchQuery::parse(&"q".repeat(MAX_QUERY_CHARS + 1), false).is_err());
442 }
443
444 #[test]
445 fn version_arg_policy() {
446 assert_eq!(VersionArg::parse_opt(None).unwrap().as_str(), "latest");
447 assert_eq!(VersionArg::parse_opt(Some("")).unwrap().as_str(), "latest");
448 assert_eq!(VersionArg::parse("1.0.0").unwrap().as_str(), "1.0.0");
449 assert_eq!(
450 VersionArg::parse("stable").unwrap().stdlib_channel(),
451 "stable"
452 );
453 assert_eq!(
454 VersionArg::parse("latest").unwrap().stdlib_channel(),
455 "stable"
456 );
457 assert!(VersionArg::parse("v1.0.0").is_err());
458 assert!(VersionArg::parse("1.0.0+build").is_err());
459 assert!(VersionArg::parse("not-a-version").is_err());
460 }
461}
462
463#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
465#[serde(rename_all = "snake_case")]
466pub enum MatchMode {
467 Exact,
469 #[default]
471 Prefix,
472 Substring,
474}
475
476impl MatchMode {
477 pub fn as_str(self) -> &'static str {
479 match self {
480 Self::Exact => "exact",
481 Self::Prefix => "prefix",
482 Self::Substring => "substring",
483 }
484 }
485
486 pub fn parse(input: &str) -> AppResult<Self> {
492 match input.trim().to_ascii_lowercase().as_str() {
493 "exact" => Ok(Self::Exact),
494 "prefix" => Ok(Self::Prefix),
495 "substring" | "contains" | "substr" => Ok(Self::Substring),
496 other => Err(AppError::new(
497 ErrorKind::InvalidInput,
498 format!("unknown match mode '{other}' (expected exact|prefix|substring)"),
499 )),
500 }
501 }
502
503 pub fn score(self, name: &str, query: &str) -> Option<u8> {
505 let q = query.trim();
506 if q.is_empty() {
507 return Some(0);
508 }
509 let q = q.to_ascii_lowercase();
510 let name_l = name.to_ascii_lowercase();
511 let leaf = name_l.rsplit("::").next().unwrap_or(name_l.as_str());
512 let exact_leaf = leaf == q;
513 let prefix_leaf = leaf.starts_with(&q);
514 let exact_path = name_l == q;
515 let contains = name_l.contains(&q) || leaf.contains(&q);
516 match self {
517 Self::Exact => {
518 if exact_leaf {
519 Some(0)
520 } else if exact_path {
521 Some(1)
522 } else {
523 None
524 }
525 }
526 Self::Prefix => {
527 if exact_leaf {
528 Some(0)
529 } else if prefix_leaf {
530 Some(1)
531 } else if exact_path {
532 Some(2)
533 } else {
534 None
535 }
536 }
537 Self::Substring => {
538 if exact_leaf {
539 Some(0)
540 } else if prefix_leaf {
541 Some(1)
542 } else if exact_path {
543 Some(2)
544 } else if contains {
545 Some(3)
546 } else {
547 None
548 }
549 }
550 }
551 }
552}
553
554impl std::str::FromStr for MatchMode {
555 type Err = AppError;
556 fn from_str(s: &str) -> Result<Self, Self::Err> {
557 Self::parse(s)
558 }
559}