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

View file

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