1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//! Search engine: Where the fuzzy matching magic happens
//!
//! This task will collect all the input from STDIN and search over them on new queries.
//! Once a search is done all the results will be sent to the screen.

use crate::common::{Result, Text, TextBuilder};
use crate::config::Config;
use crate::events::Event;
use crate::fuzzy;
use async_std::channel::{Receiver, Sender};
use async_std::prelude::*;
use std::collections::VecDeque;

const BUFFER_LIMIT: usize = 5000;

/// Run the search engine task
pub async fn task(
    config: Config,
    mut input_recv: Receiver<Event>,
    output_sender: Sender<Event>,
) -> Result<()> {
    log::trace!("starting search engine");

    let pool_size = config.advanced.pool_size();
    let mut pool: VecDeque<Text> = VecDeque::new();
    let mut count = 0;
    let mut query = String::from("");

    while let Some(event) = input_recv.next().await {
        match event {
            Event::NewLine(s) => {
                log::trace!("line: {:?}", s);

                // Push the new line into the main pool
                pool.push_back(TextBuilder::build(&s));
                count += 1;

                // The pool might be full (too many lines in memory)
                // so we drop the first line
                if pool.len() > pool_size {
                    log::trace!("pool limit ({:?}) exceeded, dropping first line", pool_size);
                    let _f = pool.pop_front();
                }

                // We've got enough lines to refresh the search and send it
                // to the screen
                if count > BUFFER_LIMIT {
                    count = 0;
                    let matches = fuzzy::search(&query, &pool, config.preserve_order);
                    output_sender
                        .send(Event::Flush((matches, pool.len())))
                        .await?;
                }
            }
            Event::EOF => {
                log::trace!("all input data done");
                let matches = fuzzy::search(&query, &pool, config.preserve_order);
                output_sender
                    .send(Event::Flush((matches, pool.len())))
                    .await?;
            }
            Event::Search(prompt) => {
                query = prompt.as_string();
                log::trace!("performing new search: '{}'", query);

                let matches = fuzzy::search(&query, &pool, config.preserve_order);
                let results = Event::SearchDone((matches, pool.len(), prompt.timestamp()));

                output_sender.send(results).await?;
            }
            Event::Done | Event::Exit => break,
            _ => (),
        };
    }

    log::trace!("search engine done");

    Ok(())
}