history_custom/
history_custom.rs

1use dialoguer::{theme::ColorfulTheme, History, Input};
2use std::{collections::VecDeque, process};
3
4fn main() {
5    println!("Use 'exit' to quit the prompt");
6    println!("In this example, history is limited to 4 entries");
7    println!("Use the Up/Down arrows to scroll through history");
8    println!();
9
10    let mut history = MyHistory::default();
11
12    loop {
13        if let Ok(cmd) = Input::<String>::with_theme(&ColorfulTheme::default())
14            .with_prompt("dialoguer")
15            .history_with(&mut history)
16            .interact_text()
17        {
18            if cmd == "exit" {
19                process::exit(0);
20            }
21            println!("Entered {}", cmd);
22        }
23    }
24}
25
26struct MyHistory {
27    max: usize,
28    history: VecDeque<String>,
29}
30
31impl Default for MyHistory {
32    fn default() -> Self {
33        MyHistory {
34            max: 4,
35            history: VecDeque::new(),
36        }
37    }
38}
39
40impl<T: ToString> History<T> for MyHistory {
41    fn read(&self, pos: usize) -> Option<String> {
42        self.history.get(pos).cloned()
43    }
44
45    fn write(&mut self, val: &T) {
46        if self.history.len() == self.max {
47            self.history.pop_back();
48        }
49        self.history.push_front(val.to_string());
50    }
51}