docsrs_cli/domain/
match_mode.rs1use crate::error::{AppError, AppResult, ErrorDetail};
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::of(ErrorDetail::UnknownMatchMode {
40 value: other.to_string(),
41 })),
42 }
43 }
44
45 #[must_use]
50 pub fn score(self, name: &str, query: impl AsRef<str>) -> Option<u8> {
51 let q = query.as_ref().trim();
52 if q.is_empty() {
53 return Some(0);
54 }
55 let q = q.to_ascii_lowercase();
56 let name_l = name.to_ascii_lowercase();
57 let leaf = name_l.rsplit("::").next().unwrap_or(name_l.as_str());
58 let exact_leaf = leaf == q;
59 let prefix_leaf = leaf.starts_with(&q);
60 let exact_path = name_l == q;
61 let contains = name_l.contains(&q) || leaf.contains(&q);
62 match self {
63 Self::Exact => {
64 if exact_leaf {
65 Some(0)
66 } else if exact_path {
67 Some(1)
68 } else {
69 None
70 }
71 }
72 Self::Prefix => {
73 if exact_leaf {
74 Some(0)
75 } else if prefix_leaf {
76 Some(1)
77 } else if exact_path {
78 Some(2)
79 } else {
80 None
81 }
82 }
83 Self::Substring => {
84 if exact_leaf {
85 Some(0)
86 } else if prefix_leaf {
87 Some(1)
88 } else if exact_path {
89 Some(2)
90 } else if contains {
91 Some(3)
92 } else {
93 None
94 }
95 }
96 }
97 }
98}
99
100impl std::str::FromStr for MatchMode {
101 type Err = AppError;
102 fn from_str(s: &str) -> Result<Self, Self::Err> {
103 Self::parse(s)
104 }
105}