aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/history.rs51
1 files changed, 41 insertions, 10 deletions
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<u8> = 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<u8> {
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<u8> = 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<ContentChange>),
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());
+ }
+ }
+}