From af13d8589cfd356df715b7e1748a2bddebb41c92 Mon Sep 17 00:00:00 2001 From: Mel Date: Tue, 21 Sep 2021 23:51:46 +0200 Subject: Fix getting content of history --- src/history.rs | 51 +++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 41 insertions(+), 10 deletions(-) (limited to 'src/history.rs') diff --git a/src/history.rs b/src/history.rs index a032eaa..ce5ae26 100644 --- a/src/history.rs +++ b/src/history.rs @@ -25,6 +25,14 @@ impl FileHistory { Ok(file_history.context("Corrupted file history.")?) } + pub fn write_to_file(&self, file: &mut File) -> anyhow::Result<()> { + let encoded: Vec = serde_json::to_vec(self)?; + file.rewind()?; + file.set_len(0)?; + file.write_all(encoded.as_ref())?; + Ok(()) + } + pub fn cursor(&self) -> usize { self.cursor } @@ -41,7 +49,7 @@ impl FileHistory { pub fn get_content(&self) -> Vec { let mut buffer = Vec::new(); - for file_change in self.changes.iter().take(self.cursor) { + for file_change in self.changes.iter().take(self.cursor + 1) { if let FileChange::Updated(ref updated) = file_change { for change in updated.iter() { change.apply(&mut buffer) @@ -53,14 +61,6 @@ impl FileHistory { buffer } - pub fn write_to_file(&self, file: &mut File) -> anyhow::Result<()> { - let encoded: Vec = serde_json::to_vec(self)?; - file.rewind()?; - file.set_len(0)?; - file.write_all(encoded.as_ref())?; - Ok(()) - } - pub fn set_cursor(&mut self, new_cursor: usize) { if new_cursor < self.changes.len() { self.cursor = new_cursor; @@ -68,7 +68,7 @@ impl FileHistory { panic!( "Out-of-bounds cursor for file history: {}, can be at most {}", new_cursor, - self.changes.len() + self.changes.len() - 1 ); } } @@ -92,3 +92,34 @@ pub enum FileChange { Updated(Vec), Deleted, } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_get_content() { + let stages = &[ + "", + "hiii!", + "yes hii? this is a test.", + "yes bye! this is not a test.", + ]; + + let mut history = FileHistory::default(); + history.add_change(FileChange::Updated(Vec::new())); + + for old_index in 0..stages.len() - 1 { + let old = stages[old_index].as_bytes(); + let new = stages[old_index + 1].as_bytes(); + + let stage_difference = ContentChange::diff(old, new); + history.add_change(FileChange::Updated(stage_difference)); + } + + for index in 0..stages.len() { + history.set_cursor(index); + assert_eq!(stages[index].as_bytes(), history.get_content()); + } + } +} -- cgit 1.4.1