From 9cc5d909d52b09f95429f872cc3f862cac6ac75d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Nerma?= Date: Thu, 7 Dec 2023 17:08:42 +0100 Subject: [PATCH] Fix: ID generation --- src/history/cursor.rs | 5 +++++ src/history/file_backed.rs | 12 +++++++----- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/history/cursor.rs b/src/history/cursor.rs index c6b99a0a..43c68508 100644 --- a/src/history/cursor.rs +++ b/src/history/cursor.rs @@ -549,12 +549,17 @@ mod tests { { let (mut hist_a, _) = create_history_at(capacity, &histfile); + assert_eq!(get_all_entry_texts(hist_a.as_ref()), initial_entries); + { let (mut hist_b, _) = create_history_at(capacity, &histfile); + assert_eq!(get_all_entry_texts(hist_b.as_ref()), initial_entries); + add_text_entries(hist_b.as_mut(), &entries_b); // As `hist` goes out of scope and get's dropped, its contents are flushed to disk } + add_text_entries(hist_a.as_mut(), &entries_a); // As `hist` goes out of scope and get's dropped, its contents are flushed to disk } diff --git a/src/history/file_backed.rs b/src/history/file_backed.rs index ee35d44c..52bfc47b 100644 --- a/src/history/file_backed.rs +++ b/src/history/file_backed.rs @@ -1,4 +1,5 @@ use indexmap::IndexMap; +use rand::{rngs::SmallRng, RngCore, SeedableRng}; use super::{ base::CommandLineSearch, History, HistoryItem, HistoryItemId, SearchDirection, SearchQuery, @@ -32,6 +33,7 @@ pub struct FileBackedHistory { file: Option, last_on_disk: Option, session: Option, + rng: SmallRng, } impl Default for FileBackedHistory { @@ -63,7 +65,7 @@ fn decode_entry(s: &str) -> std::result::Result<(HistoryItemId, String), &'stati impl History for FileBackedHistory { fn generate_id(&mut self) -> HistoryItemId { - HistoryItemId((self.entries.len() + 1) as i64) + HistoryItemId(self.rng.next_u64() as i64) } /// only saves a value if it's different than the last value @@ -280,10 +282,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())), - true, - ) + let start = from_file.len() + own_entries.len() - self.capacity; + + (from_file.split_off(start), true) } else { (from_file, false) } @@ -361,6 +362,7 @@ impl FileBackedHistory { file: None, last_on_disk: None, session: None, + rng: SmallRng::from_entropy(), } }