use std::fmt;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct NodeId(u64);
impl NodeId {
pub const fn index(self) -> u64 {
self.0
}
pub const fn from_index(index: u64) -> Self {
Self(index)
}
}
impl fmt::Display for NodeId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}", self.0)
}
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct HistoryNode<S> {
pub id: NodeId,
pub parent: Option<NodeId>,
pub children: Vec<NodeId>,
pub label: String,
pub state: S,
pub group: Option<u64>,
pub timestamp: f64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct GroupId(u64);
impl GroupId {
pub const fn index(self) -> u64 {
self.0
}
}
impl fmt::Display for GroupId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}", self.0)
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum HistoryError {
#[error("unknown history node {0}")]
UnknownNode(NodeId),
#[error("the history is empty")]
Empty,
#[error("group {0} is already open")]
GroupAlreadyOpen(GroupId),
#[error("no group is open")]
NoGroup,
}
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "HistoryRepr<S>"))]
pub struct History<S> {
nodes: Vec<HistoryNode<S>>,
current: NodeId,
next_id: u64,
next_group: u64,
active_group: Option<GroupId>,
#[cfg_attr(feature = "serde", serde(skip))]
redo_to: Option<NodeId>,
}
#[cfg(feature = "serde")]
#[derive(serde::Deserialize)]
struct HistoryRepr<S> {
nodes: Vec<HistoryNode<S>>,
current: NodeId,
#[serde(default)]
next_id: u64,
#[serde(default)]
next_group: u64,
#[serde(default)]
active_group: Option<GroupId>,
}
#[cfg(feature = "serde")]
impl<S> TryFrom<HistoryRepr<S>> for History<S> {
type Error = String;
fn try_from(repr: HistoryRepr<S>) -> Result<Self, Self::Error> {
if repr.nodes.is_empty() {
return Err("a history needs at least one node".to_owned());
}
if repr.nodes.len() > 100_000 {
return Err("the history has too many nodes".to_owned());
}
let len = repr.nodes.len();
for (index, node) in repr.nodes.iter().enumerate() {
if node.id.0 != index as u64 {
return Err("history node ids must be dense and in order".to_owned());
}
if let Some(parent) = node.parent
&& (parent.0 as usize >= len || parent.0 as usize == index)
{
return Err("a history parent points outside the tree".to_owned());
}
if node.children.iter().any(|child| child.0 as usize >= len) {
return Err("a history child points outside the tree".to_owned());
}
}
let current = repr.current.0 as usize;
if current >= len {
return Err("the current history node does not exist".to_owned());
}
for node in &repr.nodes {
let mut seen = 0usize;
let mut cursor = node.parent;
while let Some(parent) = cursor {
seen += 1;
if seen > len {
return Err("the history parent chain contains a cycle".to_owned());
}
cursor = repr.nodes.get(parent.0 as usize).and_then(|node| node.parent);
}
}
let next_id = repr.next_id.max(len as u64);
let next_group = repr
.next_group
.max(repr.nodes.iter().filter_map(|node| node.group).max().unwrap_or(0) + 1);
Ok(Self {
nodes: repr.nodes,
current: repr.current,
next_id,
next_group,
active_group: repr.active_group,
redo_to: None,
})
}
}
const MAX_NODES: usize = 50_000;
impl<S> History<S> {
pub fn new(initial: S) -> Self {
Self {
nodes: vec![HistoryNode {
id: NodeId(0),
parent: None,
children: Vec::new(),
label: "Initial".to_owned(),
state: initial,
group: None,
timestamp: 0.0,
}],
current: NodeId(0),
next_id: 1,
next_group: 1,
active_group: None,
redo_to: None,
}
}
pub fn current(&self) -> NodeId {
self.current
}
#[allow(clippy::indexing_slicing)]
pub fn state(&self) -> &S {
&self.nodes[self.current.0 as usize].state
}
#[allow(clippy::indexing_slicing)]
pub fn current_node(&self) -> &HistoryNode<S> {
&self.nodes[self.current.0 as usize]
}
pub fn node(&self, id: NodeId) -> Option<&HistoryNode<S>> {
self.nodes.iter().find(|node| node.id == id)
}
pub fn nodes(&self) -> &[HistoryNode<S>] {
&self.nodes
}
pub fn len(&self) -> usize {
self.nodes.len()
}
pub fn is_empty(&self) -> bool {
self.nodes.len() <= 1
}
#[allow(clippy::indexing_slicing)]
pub fn can_undo(&self) -> bool {
self.nodes[self.current.0 as usize].parent.is_some()
}
#[allow(clippy::indexing_slicing)]
pub fn can_redo(&self) -> bool {
!self.nodes[self.current.0 as usize].children.is_empty()
}
pub fn group(&self) -> Option<GroupId> {
self.active_group
}
pub fn begin_group(&mut self, _label: &str) -> Result<GroupId, HistoryError> {
if let Some(group) = self.active_group {
return Err(HistoryError::GroupAlreadyOpen(group));
}
let group = GroupId(self.next_group);
self.next_group += 1;
self.active_group = Some(group);
Ok(group)
}
pub fn end_group(&mut self) -> Result<(), HistoryError> {
if self.active_group.take().is_none() {
return Err(HistoryError::NoGroup);
}
Ok(())
}
pub fn path(&self) -> Vec<NodeId> {
let mut path = Vec::new();
let mut node = Some(self.current);
while let Some(id) = node {
path.push(id);
node = self.node(id).and_then(|node| node.parent);
}
path.reverse();
path
}
#[allow(clippy::indexing_slicing)]
pub fn undo(&mut self) -> Option<&S> {
let parent = self.nodes[self.current.0 as usize].parent?;
self.redo_to = Some(self.current);
self.active_group = None;
self.current = parent;
Some(self.state())
}
#[allow(clippy::indexing_slicing)]
pub fn redo(&mut self) -> Option<&S> {
let remembered = self
.redo_to
.filter(|id| self.nodes[self.current.0 as usize].children.contains(id));
let child = match remembered {
Some(id) => id,
None => *self.nodes[self.current.0 as usize].children.last()?,
};
self.redo_to = None;
self.active_group = None;
self.current = child;
Some(self.state())
}
pub fn jump_to(&mut self, id: NodeId) -> Result<&S, HistoryError> {
if self.node(id).is_none() {
return Err(HistoryError::UnknownNode(id));
}
self.redo_to = None;
self.active_group = None;
self.current = id;
Ok(self.state())
}
}
impl<S: Clone + PartialEq> History<S> {
#[allow(clippy::indexing_slicing)]
pub fn record(&mut self, label: impl Into<String>, state: S) -> NodeId {
self.redo_to = None;
let label = label.into();
if let Some(group) = self.active_group
&& self.current != NodeId(0)
&& self.current_node().group == Some(group.index())
{
let node = &mut self.nodes[self.current.0 as usize];
node.state = state;
node.label = label;
return node.id;
}
if self.state() == &state {
return self.current;
}
self.record_with_group(label, state, self.active_group.map(GroupId::index), 0.0)
}
pub fn record_at(&mut self, label: impl Into<String>, state: S, timestamp: f64) -> NodeId {
self.record_with_group(label.into(), state, self.active_group.map(GroupId::index), timestamp)
}
#[allow(clippy::indexing_slicing)]
fn record_with_group(&mut self, label: String, state: S, group: Option<u64>, timestamp: f64) -> NodeId {
if self.nodes.len() >= MAX_NODES {
return self.current;
}
let id = NodeId(self.next_id);
self.next_id += 1;
self.nodes.push(HistoryNode {
id,
parent: Some(self.current),
children: Vec::new(),
label,
state,
group,
timestamp,
});
self.nodes[self.current.0 as usize].children.push(id);
self.current = id;
id
}
}
#[cfg(test)]
mod tests;