Skip to content

Commit

Permalink
Add next_branch_head and prev_branch_head methods to history
Browse files Browse the repository at this point in the history
  • Loading branch information
evenorog committed Sep 29, 2023
1 parent c93c741 commit 441229c
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,28 @@ impl<E, S> History<E, S> {
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<At> {
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<At> {
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.
Expand Down
23 changes: 23 additions & 0 deletions tests/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

0 comments on commit 441229c

Please sign in to comment.