Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #209 from Garbaz/master
Provide a basic default implementation of `History`
- Loading branch information
Showing
5 changed files
with
128 additions
and
32 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
use dialoguer::{theme::ColorfulTheme, History, Input}; | ||
use std::{collections::VecDeque, process}; | ||
|
||
fn main() { | ||
println!("Use 'exit' to quit the prompt"); | ||
println!("In this example, history is limited to 4 entries"); | ||
println!("Use the Up/Down arrows to scroll through history"); | ||
println!(); | ||
|
||
let mut history = MyHistory::default(); | ||
|
||
loop { | ||
if let Ok(cmd) = Input::<String>::with_theme(&ColorfulTheme::default()) | ||
.with_prompt("dialoguer") | ||
.history_with(&mut history) | ||
.interact_text() | ||
{ | ||
if cmd == "exit" { | ||
process::exit(0); | ||
} | ||
println!("Entered {}", cmd); | ||
} | ||
} | ||
} | ||
|
||
struct MyHistory { | ||
max: usize, | ||
history: VecDeque<String>, | ||
} | ||
|
||
impl Default for MyHistory { | ||
fn default() -> Self { | ||
MyHistory { | ||
max: 4, | ||
history: VecDeque::new(), | ||
} | ||
} | ||
} | ||
|
||
impl<T: ToString> History<T> for MyHistory { | ||
fn read(&self, pos: usize) -> Option<String> { | ||
self.history.get(pos).cloned() | ||
} | ||
|
||
fn write(&mut self, val: &T) { | ||
if self.history.len() == self.max { | ||
self.history.pop_back(); | ||
} | ||
self.history.push_front(val.to_string()); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters