fix the case of trying to retrieve shell history when none exists

fortunately rust handles this with a panic because it has strict
bounds checking, so this cleans up that panic.
This commit is contained in:
bunnie 2025-05-23 10:55:38 +08:00
parent 4c1933414c
commit d12bdf1494
2 changed files with 17 additions and 8 deletions

View file

@ -55,11 +55,18 @@ impl Repl {
// An index of -1 gives the most recent command.
// -2 would give the second most recent command
pub(crate) fn get_history(&mut self, index: isize) -> &str {
&self.history[(self.history.len() as isize + index)
.max(0)
.min(self.history.len().saturating_sub(1) as isize) as usize]
.text
pub(crate) fn get_history(&mut self, index: isize) -> Option<&str> {
if self.history.len() != 0 {
Some(
&self.history[(self.history.len() as isize + index)
.max(0)
.min(self.history.len().saturating_sub(1) as isize)
as usize]
.text,
)
} else {
None
}
}
/// update the loop, in response to various inputs

View file

@ -69,9 +69,11 @@ fn shell() {
print!("\r{}", spaces);
}
input.clear();
input.push_str(repl.get_history(history_index));
// print the new input
println!("{}", &input);
if let Some(s) = repl.get_history(history_index) {
input.push_str(s);
// print the new input
println!("{}", &input);
}
} else if k != '\u{0000}' && k != '\n' && k != '\r' {
input.push(k);
} else if k == '\n' || k == '\r' {