diff --git a/src/history.rs b/src/history.rs index 2b13978..16cb3d2 100644 --- a/src/history.rs +++ b/src/history.rs @@ -145,6 +145,28 @@ impl History { At::new(self.root, self.record.index) } + /// Returns the head of the next branch in the history. + /// + /// This will be the first edit that was stored in the branch. + /// This can be used in combination with [`History::go_to`] to go to the next branch. + pub fn next_branch_head(&self) -> Option { + self.branches + .range(self.root + 1..) + .next() + .map(|(&id, branch)| At::new(id, branch.parent.index + 1)) + } + + /// Returns the head of the previous branch in the history. + /// + /// This will be the first edit that was stored in the branch. + /// This can be used in combination with [`History::go_to`] to go to the previous branch. + pub fn prev_branch_head(&self) -> Option { + self.branches + .range(..self.root) + .next_back() + .map(|(&id, branch)| At::new(id, branch.parent.index + 1)) + } + /// Returns the entry at the index in the current root branch. /// /// Use [History::get_branch] if you want to get entry from other branches. diff --git a/tests/history.rs b/tests/history.rs index 5b33966..d6a2b5c 100644 --- a/tests/history.rs +++ b/tests/history.rs @@ -121,3 +121,26 @@ fn checkpoint() { checkpoint.cancel(&mut target); assert_eq!(target, ""); } + +#[test] +fn next_and_prev() { + let mut target = String::new(); + let mut history = History::new(); + history.edit(&mut target, A); + history.edit(&mut target, B); + history.edit(&mut target, C); + assert_eq!(history.next_branch_head(), None); + assert_eq!(history.prev_branch_head(), None); + + history.undo(&mut target).unwrap(); + history.undo(&mut target).unwrap(); + history.edit(&mut target, D); + history.edit(&mut target, E); + assert_eq!(history.next_branch_head(), None); + let prev_head = history.prev_branch_head().unwrap(); + assert_eq!(prev_head, At::new(0, 2)); + + history.go_to(&mut target, prev_head); + assert_eq!(history.next_branch_head(), Some(At::new(1, 2))); + assert_eq!(history.prev_branch_head(), None); +}