docsrs_cli/domain/
match_mode.rs1use crate::error::{AppError, AppResult, ErrorKind};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
7#[serde(rename_all = "snake_case")]
8pub enum MatchMode {
9 Exact,
11 #[default]
13 Prefix,
14 Substring,
16}
17
18impl MatchMode {
19 #[must_use]
21 pub fn as_str(self) -> &'static str {
22 match self {
23 Self::Exact => "exact",
24 Self::Prefix => "prefix",
25 Self::Substring => "substring",
26 }
27 }
28
29 pub fn parse(input: &str) -> AppResult<Self> {
35 match input.trim().to_ascii_lowercase().as_str() {
36 "exact" => Ok(Self::Exact),
37 "prefix" => Ok(Self::Prefix),
38 "substring" | "contains" | "substr" => Ok(Self::Substring),
39 other => Err(AppError::new(
40 ErrorKind::InvalidInput,
41 format!("unknown match mode '{other}' (expected exact|prefix|substring)"),
42 )),
43 }
44 }
45
46 #[must_use]
51 pub fn score(self, name: &str, query: impl AsRef<str>) -> Option<u8> {
52 let q = query.as_ref().trim();
53 if q.is_empty() {
54 return Some(0);
55 }
56 let q = q.to_ascii_lowercase();
57 let name_l = name.to_ascii_lowercase();
58 let leaf = name_l.rsplit("::").next().unwrap_or(name_l.as_str());
59 let exact_leaf = leaf == q;
60 let prefix_leaf = leaf.starts_with(&q);
61 let exact_path = name_l == q;
62 let contains = name_l.contains(&q) || leaf.contains(&q);
63 match self {
64 Self::Exact => {
65 if exact_leaf {
66 Some(0)
67 } else if exact_path {
68 Some(1)
69 } else {
70 None
71 }
72 }
73 Self::Prefix => {
74 if exact_leaf {
75 Some(0)
76 } else if prefix_leaf {
77 Some(1)
78 } else if exact_path {
79 Some(2)
80 } else {
81 None
82 }
83 }
84 Self::Substring => {
85 if exact_leaf {
86 Some(0)
87 } else if prefix_leaf {
88 Some(1)
89 } else if exact_path {
90 Some(2)
91 } else if contains {
92 Some(3)
93 } else {
94 None
95 }
96 }
97 }
98 }
99}
100
101impl std::str::FromStr for MatchMode {
102 type Err = AppError;
103 fn from_str(s: &str) -> Result<Self, Self::Err> {
104 Self::parse(s)
105 }
106}