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 for seg in &parts {
153 if seg == "." || seg == ".." {
154 return Err(AppError::new(
155 ErrorKind::InvalidInput,
156 format!("invalid item path segment '{seg}'"),
157 ));
158 }
159 if seg.chars().any(|c| c.is_whitespace()) {
160 return Err(AppError::new(
161 ErrorKind::InvalidInput,
162 format!("item path segment contains whitespace: '{seg}'"),
163 ));
164 }
165 if !seg.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
166 return Err(AppError::new(
167 ErrorKind::InvalidInput,
168 format!(
169 "invalid item path segment '{seg}' (use letters, digits, underscore; separate with :: or /)"
170 ),
171 ));
172 }
173 }
174 Ok(Self {
175 raw: path.to_string(),
176 segments: parts,
177 })
178 }
179
180 pub fn segments(&self) -> &[String] {
182 &self.segments
183 }
184
185 pub fn into_segments(self) -> Vec<String> {
187 self.segments
188 }
189
190 pub fn as_str(&self) -> &str {
192 &self.raw
193 }
194}
195
196impl AsRef<str> for ItemPath {
197 fn as_ref(&self) -> &str {
198 self.as_str()
199 }
200}
201
202impl fmt::Display for ItemPath {
203 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204 f.write_str(&self.segments.join("::"))
205 }
206}
207
208impl FromStr for ItemPath {
209 type Err = AppError;
210
211 fn from_str(s: &str) -> Result<Self, Self::Err> {
217 Self::parse(s)
218 }
219}
220
221#[derive(Debug, Clone, PartialEq, Eq, Hash)]
223pub struct SearchQuery(String);
224
225impl SearchQuery {
226 pub fn parse(query: &str, allow_empty: bool) -> AppResult<Self> {
235 let q = query.trim();
236 if !allow_empty && q.is_empty() {
237 return Err(AppError::new(
238 ErrorKind::InvalidInput,
239 "search query is empty",
240 ));
241 }
242 if q.chars().count() > MAX_QUERY_CHARS {
243 return Err(AppError::new(
244 ErrorKind::InvalidInput,
245 format!("query exceeds {MAX_QUERY_CHARS} characters"),
246 ));
247 }
248 Ok(Self(q.to_string()))
249 }
250
251 pub fn as_str(&self) -> &str {
253 &self.0
254 }
255}
256
257impl AsRef<str> for SearchQuery {
258 fn as_ref(&self) -> &str {
259 self.as_str()
260 }
261}
262
263impl fmt::Display for SearchQuery {
264 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265 f.write_str(self.as_str())
266 }
267}
268
269#[derive(Debug, Clone, PartialEq, Eq, Hash)]
271pub struct VersionArg(String);
272
273impl VersionArg {
274 pub fn parse_opt(raw: Option<&str>) -> AppResult<Self> {
281 let v = raw
282 .map(str::trim)
283 .filter(|s| !s.is_empty())
284 .unwrap_or("latest");
285 Self::parse(v)
286 }
287
288 pub fn parse(v: &str) -> AppResult<Self> {
295 let v = v.trim();
296 if v.chars().count() > MAX_VERSION_CHARS {
297 return Err(AppError::new(
298 ErrorKind::InvalidInput,
299 format!("version exceeds {MAX_VERSION_CHARS} characters"),
300 ));
301 }
302 if v == "latest" {
303 return Ok(Self(v.to_string()));
304 }
305 if matches!(v, "stable" | "beta" | "nightly") {
306 return Ok(Self(v.to_string()));
307 }
308 if v.starts_with('v') || v.starts_with('V') {
309 return Err(AppError::new(
310 ErrorKind::InvalidInput,
311 "version must not start with 'v' prefix",
312 ));
313 }
314 if v.contains('+') {
315 return Err(AppError::new(
316 ErrorKind::InvalidInput,
317 "version build metadata is not accepted",
318 ));
319 }
320 static RE: LazyLock<Regex> = LazyLock::new(|| {
321 Regex::new(r"^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$")
322 .expect("hardcoded semver-ish version regex is valid by construction")
323 });
324 if !RE.is_match(v) {
325 return Err(AppError::new(
326 ErrorKind::InvalidInput,
327 format!("invalid version '{v}'"),
328 ));
329 }
330 Ok(Self(v.to_string()))
331 }
332
333 pub fn as_str(&self) -> &str {
335 &self.0
336 }
337
338 pub fn stdlib_channel(&self) -> &str {
340 crate::config::stdlib_channel(self.as_str())
341 }
342}
343
344impl AsRef<str> for VersionArg {
345 fn as_ref(&self) -> &str {
346 self.as_str()
347 }
348}
349
350impl fmt::Display for VersionArg {
351 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352 f.write_str(self.as_str())
353 }
354}
355
356impl FromStr for VersionArg {
357 type Err = AppError;
358
359 fn from_str(s: &str) -> Result<Self, Self::Err> {
365 Self::parse(s)
366 }
367}
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372
373 #[test]
374 fn crate_name_ok_and_stdlib() {
375 let s = CrateName::parse("serde").unwrap();
376 assert_eq!(s.as_str(), "serde");
377 assert!(!s.is_stdlib());
378 assert!(CrateName::parse("async-trait").unwrap().as_str() == "async-trait");
379 for n in ["std", "core", "alloc"] {
380 let c = CrateName::parse(n).unwrap();
381 assert!(c.is_stdlib(), "{n}");
382 }
383 }
384
385 #[test]
386 fn crate_name_err() {
387 assert!(CrateName::parse("").is_err());
388 assert!(CrateName::parse("1bad").is_err());
389 assert!(CrateName::parse(&"a".repeat(MAX_CRATE_NAME_CHARS + 1)).is_err());
390 }
391
392 #[test]
393 fn item_path_segments_and_display() {
394 let p = ItemPath::parse("clap::Parser").unwrap();
395 assert_eq!(p.segments(), &["clap".to_string(), "Parser".to_string()]);
396 assert_eq!(p.to_string(), "clap::Parser");
397 let slash = ItemPath::parse("runtime/Runtime").unwrap();
398 assert_eq!(
399 slash.segments(),
400 &["runtime".to_string(), "Runtime".to_string()]
401 );
402 assert_eq!(
403 ItemPath::parse("async_trait").unwrap().segments(),
404 &["async_trait".to_string()]
405 );
406 }
407
408 #[test]
409 fn item_path_err() {
410 assert!(ItemPath::parse("").is_err());
411 assert!(ItemPath::parse("::").is_err());
412 assert!(ItemPath::parse("has space").is_err());
413 assert!(ItemPath::parse("foo.bar").is_err());
414 assert!(ItemPath::parse("..").is_err());
415 assert!(ItemPath::parse("a/../b").is_err());
416 }
417
418 #[test]
419 fn search_query_rules() {
420 assert!(SearchQuery::parse("", false).is_err());
421 assert_eq!(SearchQuery::parse(" ", true).unwrap().as_str(), "");
422 assert_eq!(
423 SearchQuery::parse("serde", false).unwrap().as_str(),
424 "serde"
425 );
426 assert!(SearchQuery::parse(&"q".repeat(MAX_QUERY_CHARS + 1), false).is_err());
427 }
428
429 #[test]
430 fn version_arg_policy() {
431 assert_eq!(VersionArg::parse_opt(None).unwrap().as_str(), "latest");
432 assert_eq!(VersionArg::parse_opt(Some("")).unwrap().as_str(), "latest");
433 assert_eq!(VersionArg::parse("1.0.0").unwrap().as_str(), "1.0.0");
434 assert_eq!(
435 VersionArg::parse("stable").unwrap().stdlib_channel(),
436 "stable"
437 );
438 assert_eq!(
439 VersionArg::parse("latest").unwrap().stdlib_channel(),
440 "stable"
441 );
442 assert!(VersionArg::parse("v1.0.0").is_err());
443 assert!(VersionArg::parse("1.0.0+build").is_err());
444 assert!(VersionArg::parse("not-a-version").is_err());
445 }
446}
447
448#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
450#[serde(rename_all = "snake_case")]
451pub enum MatchMode {
452 Exact,
454 #[default]
456 Prefix,
457 Substring,
459}
460
461impl MatchMode {
462 pub fn as_str(self) -> &'static str {
464 match self {
465 Self::Exact => "exact",
466 Self::Prefix => "prefix",
467 Self::Substring => "substring",
468 }
469 }
470
471 pub fn parse(input: &str) -> AppResult<Self> {
477 match input.trim().to_ascii_lowercase().as_str() {
478 "exact" => Ok(Self::Exact),
479 "prefix" => Ok(Self::Prefix),
480 "substring" | "contains" | "substr" => Ok(Self::Substring),
481 other => Err(AppError::new(
482 ErrorKind::InvalidInput,
483 format!("unknown match mode '{other}' (expected exact|prefix|substring)"),
484 )),
485 }
486 }
487
488 pub fn score(self, name: &str, query: &str) -> Option<u8> {
490 let q = query.trim();
491 if q.is_empty() {
492 return Some(0);
493 }
494 let q = q.to_ascii_lowercase();
495 let name_l = name.to_ascii_lowercase();
496 let leaf = name_l.rsplit("::").next().unwrap_or(name_l.as_str());
497 let exact_leaf = leaf == q;
498 let prefix_leaf = leaf.starts_with(&q);
499 let exact_path = name_l == q;
500 let contains = name_l.contains(&q) || leaf.contains(&q);
501 match self {
502 Self::Exact => {
503 if exact_leaf {
504 Some(0)
505 } else if exact_path {
506 Some(1)
507 } else {
508 None
509 }
510 }
511 Self::Prefix => {
512 if exact_leaf {
513 Some(0)
514 } else if prefix_leaf {
515 Some(1)
516 } else if exact_path {
517 Some(2)
518 } else {
519 None
520 }
521 }
522 Self::Substring => {
523 if exact_leaf {
524 Some(0)
525 } else if prefix_leaf {
526 Some(1)
527 } else if exact_path {
528 Some(2)
529 } else if contains {
530 Some(3)
531 } else {
532 None
533 }
534 }
535 }
536 }
537}
538
539impl std::str::FromStr for MatchMode {
540 type Err = AppError;
541 fn from_str(s: &str) -> Result<Self, Self::Err> {
542 Self::parse(s)
543 }
544}