From d9db6a84b70d182c11c1a657d363c914eb3921d1 Mon Sep 17 00:00:00 2001 From: andreistan26 <48967297+andreistan26@users.noreply.github.com> Date: Sun, 21 Jan 2024 05:25:02 +0200 Subject: [PATCH] Fix panic when history size set to 0 (#653) * Fix file based history when capacity is set to zero Signed-off-by: Andrei Stan * Fix CI Signed-off-by: Andrei Stan --------- Signed-off-by: Andrei Stan --- src/history/base.rs | 13 +++++++++++++ src/history/file_backed.rs | 5 ++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/history/base.rs b/src/history/base.rs index 26d4da05..2fcbe4ac 100644 --- a/src/history/base.rs +++ b/src/history/base.rs @@ -427,4 +427,17 @@ mod test { Ok(()) } + + #[cfg(not(any(feature = "sqlite", feature = "sqlite-dynlib")))] + #[test] + fn history_size_zero() -> Result<()> { + let mut history = crate::FileBackedHistory::new(0); + history.save(create_item(1, "/home/me", "cd ~/Downloads", 0))?; + assert_eq!(history.count_all()?, 0); + let _ = history.sync(); + history.clear()?; + drop(history); + + Ok(()) + } } diff --git a/src/history/file_backed.rs b/src/history/file_backed.rs index 28b437f7..ec70501f 100644 --- a/src/history/file_backed.rs +++ b/src/history/file_backed.rs @@ -60,6 +60,7 @@ impl History for FileBackedHistory { .back() .map_or(true, |previous| previous != &entry) && !entry.is_empty() + && self.capacity > 0 { if self.entries.len() == self.capacity { // History is "full", so we delete the oldest entry first, @@ -234,7 +235,9 @@ impl History for FileBackedHistory { .collect::>>()?; if from_file.len() + own_entries.len() > self.capacity { ( - from_file.split_off(from_file.len() - (self.capacity - own_entries.len())), + from_file.split_off( + from_file.len() - (self.capacity.saturating_sub(own_entries.len())), + ), true, ) } else {