Skip to main content

glass_dev/development/
search.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4#[serde(rename_all = "camelCase")]
5pub enum SearchKind {
6    File,
7    BrowserEntity,
8    Process,
9    Event,
10    Command,
11}
12
13#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
14#[serde(rename_all = "camelCase")]
15pub struct SearchHit {
16    pub kind: SearchKind,
17    pub label: String,
18    pub detail: String,
19    pub score: u32,
20}
21
22pub fn fuzzy_score(query: &str, candidate: &str) -> Option<u32> {
23    let query = query.to_ascii_lowercase();
24    let candidate = candidate.to_ascii_lowercase();
25    if query.is_empty() {
26        return None;
27    }
28    if let Some(index) = candidate.find(&query) {
29        return Some(10_000_u32.saturating_sub(index as u32 * 10 + candidate.len() as u32));
30    }
31    let mut position = 0;
32    let mut gaps = 0_u32;
33    for character in query.chars() {
34        let offset = candidate[position..].find(character)?;
35        gaps = gaps.saturating_add(offset as u32);
36        position += offset + character.len_utf8();
37    }
38    Some(5_000_u32.saturating_sub(gaps * 10 + candidate.len() as u32))
39}
40
41pub fn rank(mut hits: Vec<SearchHit>, limit: usize) -> Vec<SearchHit> {
42    hits.sort_by(|left, right| {
43        right
44            .score
45            .cmp(&left.score)
46            .then_with(|| left.label.cmp(&right.label))
47    });
48    hits.truncate(limit.min(256));
49    hits
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn fuzzy_search_prefers_contiguous_matches() {
58        assert!(
59            fuzzy_score("checkout", "src/checkout/page.tsx").unwrap()
60                > fuzzy_score("checkout", "components/check_out.tsx").unwrap()
61        );
62        assert!(fuzzy_score("missing", "src/app.rs").is_none());
63    }
64}