From 94cc80944ea5f11b64c4112fb9b21b0ef55da94d Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Tue, 2 May 2023 14:43:25 +0900 Subject: [PATCH] history iterator --- shrs_line/src/history.rs | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/shrs_line/src/history.rs b/shrs_line/src/history.rs index 2981c518..08b7fc09 100644 --- a/shrs_line/src/history.rs +++ b/shrs_line/src/history.rs @@ -17,13 +17,23 @@ pub trait History { fn add(&mut self, cmd: Self::HistoryItem); /// Remove all history entries fn clear(&mut self); - // fn iter(&self) -> impl Iterator; /// Query for a history entry fn search(&self, query: &str) -> Option<&Self::HistoryItem>; /// Get number of history entries fn len(&self) -> usize; /// Get a history entry by index fn get(&self, i: usize) -> Option<&Self::HistoryItem>; + fn iter(&self) -> HistoryIter; +} + +pub struct HistoryIter<'a, It>(Box>); + +impl<'a, It> Iterator for HistoryIter<'a, It> { + type Item = &'a It; + + fn next(&mut self) -> Option { + self.0.next() + } } /// Default implementation of [History] that saves history in process memory @@ -48,10 +58,6 @@ impl History for DefaultHistory { self.hist.clear(); } - // fn iter(&self) -> impl Iterator { - // todo!() - // } - fn search(&self, _query: &str) -> Option<&Self::HistoryItem> { todo!() } @@ -64,6 +70,10 @@ impl History for DefaultHistory { fn get(&self, i: usize) -> Option<&Self::HistoryItem> { self.hist.get(i) } + + fn iter(&self) -> HistoryIter { + HistoryIter(Box::new(self.hist.iter())) + } } /// Store the history persistantly in a file on disk @@ -124,10 +134,6 @@ impl History for FileBackedHistory { self.flush().unwrap(); } - // fn iter(&self) -> impl Iterator { - // todo!() - // } - fn search(&self, _query: &str) -> Option<&Self::HistoryItem> { todo!() } @@ -139,6 +145,10 @@ impl History for FileBackedHistory { fn get(&self, i: usize) -> Option<&Self::HistoryItem> { self.hist.get(i) } + + fn iter(&self) -> HistoryIter { + HistoryIter(Box::new(self.hist.iter())) + } } fn parse_history_file(hist_file: PathBuf) -> Result, FileBackedHistoryError> {