#![no_std]
#![forbid(non_ascii_idents)]
#![warn(missing_docs)]
#![warn(let_underscore)]
#![warn(clippy::pedantic)]
#![warn(clippy::cargo)]
#![allow(clippy::multiple_crate_versions, reason = "Unresolvable")]
#![warn(clippy::nursery)]
#![warn(clippy::restriction)]
#![allow(clippy::blanket_clippy_restriction_lints, reason = "Conflicting lint")]
#![allow(clippy::allow_attributes, reason = "Conflicting lint")]
#![allow(clippy::pattern_type_mismatch, reason = "Conflicting lint")]
#![allow(clippy::separated_literal_suffix, reason = "Conflicting lint")]
#![allow(
clippy::field_scoped_visibility_modifiers,
reason = "Used by IndependentWeave::from()"
)]
#![allow(
clippy::missing_inline_in_public_items,
reason = "Reasonable candidates have already been inlined"
)]
#![allow(clippy::exhaustive_enums, reason = "API")]
#![allow(clippy::exhaustive_structs, reason = "API")]
#![allow(clippy::little_endian_bytes, reason = "API")]
#![allow(clippy::partial_pub_fields, reason = "API")]
#![allow(clippy::pub_use, reason = "API")]
#![allow(clippy::arbitrary_source_item_ordering, reason = "Readability")]
#![allow(clippy::question_mark_used, reason = "Readability")]
#![allow(clippy::single_call_fn, reason = "Readability")]
#![allow(clippy::single_char_lifetime_names, reason = "Readability")]
#![allow(clippy::else_if_without_else, reason = "Style")]
#![allow(clippy::if_then_some_else_none, reason = "Style")]
#![allow(clippy::implicit_return, reason = "Style")]
#![allow(clippy::min_ident_chars, reason = "Style")]
#![allow(clippy::mod_module_files, reason = "Style")]
#![allow(clippy::module_name_repetitions, reason = "Style")]
#![allow(clippy::multiple_inherent_impl, reason = "Style")]
#![allow(clippy::try_err, reason = "Style")]
#![allow(clippy::allow_attributes_without_reason)] #![allow(clippy::indexing_slicing)] #![allow(clippy::unwrap_in_result)] #![allow(clippy::unwrap_used)] #![allow(clippy::missing_docs_in_private_items)] #![allow(clippy::shadow_unrelated)] #![allow(clippy::shadow_reuse)]
mod contract;
pub mod dependent;
pub mod independent;
pub mod wrappers;
#[cfg(feature = "rkyv")]
pub mod versioning;
pub use contracts;
pub use hashbrown;
pub use indexmap;
#[cfg(feature = "rkyv")]
pub use rkyv;
#[cfg(feature = "loro")]
pub use loro;
extern crate alloc;
use alloc::{collections::vec_deque::VecDeque, vec::Vec};
use core::{
cmp::{Ordering, Reverse},
hash::{BuildHasher, Hash},
};
use hashbrown::{HashMap, HashSet, hash_map::Entry};
#[cfg(feature = "serde")]
pub use serde;
#[must_use]
pub trait Node<K, T>
where
K: Hash + Copy + Eq + Ord,
{
type From;
type To;
#[must_use]
fn id(&self) -> K;
#[must_use]
fn from(&self) -> &Self::From;
#[must_use]
fn to(&self) -> &Self::To;
#[must_use]
fn is_active(&self) -> bool;
#[must_use]
fn contents(&self) -> &T;
}
pub trait DiscreteContents: Sized {
fn split(self, at: usize) -> DiscreteContentResult<Self>;
fn merge(self, value: Self) -> DiscreteContentResult<Self>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[allow(missing_docs, reason = "Enum items are self-explanatory")]
#[must_use]
pub enum DiscreteContentResult<T> {
One(T),
Two(T, T),
}
pub trait IndependentContents {}
pub trait DeduplicatableContents {
#[must_use]
fn is_duplicate_of(&self, other: &Self) -> bool;
}
#[must_use]
pub trait Weave<K, N, T>
where
K: Hash + Copy + Eq + Ord,
N: Node<K, T>,
{
type Nodes;
type Roots;
#[must_use]
fn len(&self) -> usize;
#[must_use]
fn is_empty(&self) -> bool;
#[must_use]
fn nodes(&self) -> &Self::Nodes;
#[must_use]
fn roots(&self) -> &Self::Roots;
#[must_use]
fn contains(&self, id: &K) -> bool;
#[must_use]
fn contains_active(&self, id: &K) -> bool;
#[must_use]
fn get_node(&self, id: &K) -> Option<&N>;
fn get_ordered_node_identifiers(&mut self, output: &mut Vec<K>);
fn get_ordered_node_identifiers_from(&mut self, id: &K, output: &mut Vec<K>);
fn get_active_path(&mut self, output: &mut Vec<K>);
fn get_path_from(&mut self, id: &K, output: &mut Vec<K>);
fn add_node(&mut self, node: N) -> bool;
fn set_node_active_status(&mut self, id: &K, value: bool) -> bool;
fn remove_node(&mut self, id: &K) -> Option<N>;
fn remove_node_tracked(&mut self, id: &K, on_removal: impl FnMut(N)) -> bool;
fn remove_all_nodes(&mut self);
}
pub trait MetadataWeave<K, N, T, M>: Weave<K, N, T>
where
K: Hash + Copy + Eq + Ord,
N: Node<K, T>,
{
#[must_use]
fn metadata(&self) -> &M;
fn metadata_mut<O>(&mut self, callback: impl FnOnce(&mut M) -> O) -> O;
}
pub trait BookmarkableWeave<K, N, T>: Weave<K, N, T>
where
K: Hash + Copy + Eq + Ord,
N: Node<K, T>,
{
type Bookmarks;
#[must_use]
fn bookmarks(&self) -> &Self::Bookmarks;
#[must_use]
fn contains_bookmark(&self, id: &K) -> bool;
fn set_node_bookmarked_status(&mut self, id: &K, value: bool) -> bool;
}
pub trait SortableWeave<K, N, T>: Weave<K, N, T>
where
K: Hash + Copy + Eq + Ord,
N: Node<K, T>,
{
fn get_ordered_node_identifiers_mirrored(&mut self, output: &mut Vec<K>);
fn get_ordered_node_identifiers_mirrored_from(&mut self, id: &K, output: &mut Vec<K>);
fn sort_node_children_by(&mut self, id: &K, cmp: impl FnMut(&N, &N) -> Ordering) -> bool;
fn sort_node_children_by_id(&mut self, id: &K, cmp: impl FnMut(&K, &K) -> Ordering) -> bool;
fn sort_roots_by(&mut self, cmp: impl FnMut(&N, &N) -> Ordering);
fn sort_roots_by_id(&mut self, cmp: impl FnMut(&K, &K) -> Ordering);
}
pub trait SortableBookmarkableWeave<K, N, T>:
BookmarkableWeave<K, N, T> + SortableWeave<K, N, T>
where
K: Hash + Copy + Eq + Ord,
N: Node<K, T>,
{
fn sort_bookmarks_by(&mut self, cmp: impl FnMut(&N, &N) -> Ordering);
fn sort_bookmarks_by_id(&mut self, cmp: impl FnMut(&K, &K) -> Ordering);
}
pub trait ActiveSingularWeave<K, N, T>: Weave<K, N, T>
where
K: Hash + Copy + Eq + Ord,
N: Node<K, T>,
{
#[must_use]
fn active(&self) -> Option<K>;
}
pub trait ActivePathWeave<K, N, T>: Weave<K, N, T>
where
K: Hash + Copy + Eq + Ord,
N: Node<K, T>,
{
type Active;
#[must_use]
fn active(&self) -> &Self::Active;
fn set_active_path(&mut self, active: impl Iterator<Item = K>);
}
pub trait IndependentWeave<K, N, T>: Weave<K, N, T> + SemiIndependentWeave<K, N, T>
where
K: Hash + Copy + Eq + Ord,
N: Node<K, T>,
T: IndependentContents,
{
fn move_node(&mut self, id: &K, new_parents: &[K]) -> bool;
}
pub trait SemiIndependentWeave<K, N, T>: Weave<K, N, T>
where
K: Hash + Copy + Eq + Ord,
N: Node<K, T>,
T: IndependentContents,
{
fn get_contents_mut<O>(&mut self, id: &K, callback: impl FnOnce(&mut T) -> O) -> Option<O>;
}
pub trait DiscreteWeave<K, N, T>: Weave<K, N, T>
where
K: Hash + Copy + Eq + Ord,
N: Node<K, T>,
T: DiscreteContents,
{
fn split_node(&mut self, id: &K, at: usize, new_id: K) -> bool;
fn merge_with_parent(&mut self, id: &K) -> Option<K>;
}
pub trait DeduplicatableWeave<K, N, T>: Weave<K, N, T>
where
K: Hash + Copy + Eq + Ord,
N: Node<K, T>,
T: DeduplicatableContents,
{
#[must_use]
fn find_duplicates(&self, id: &K) -> impl Iterator<Item = K>;
}
#[must_use]
pub trait ImmutableWeave<K, N, T>
where
K: Hash + Copy + Eq + Ord,
N: Node<K, T>,
{
type Nodes;
type Roots;
#[must_use]
fn len(&self) -> usize;
#[must_use]
fn is_empty(&self) -> bool;
#[must_use]
fn nodes(&self) -> &Self::Nodes;
#[must_use]
fn roots(&self) -> &Self::Roots;
#[must_use]
fn contains(&self, id: &K) -> bool;
#[must_use]
fn contains_active(&self, id: &K) -> bool;
#[must_use]
fn get_node(&self, id: &K) -> Option<&N>;
fn get_ordered_node_identifiers(&self, output: &mut Vec<K>);
fn get_ordered_node_identifiers_from(&self, id: &K, output: &mut Vec<K>);
fn get_active_path(&self, output: &mut Vec<K>);
fn get_path_from(&self, id: &K, output: &mut Vec<K>);
}
pub trait ImmutableMetadataWeave<K, N, T, M>: ImmutableWeave<K, N, T>
where
K: Hash + Copy + Eq + Ord,
N: Node<K, T>,
{
#[must_use]
fn metadata(&self) -> &M;
}
pub trait ImmutableBookmarkableWeave<K, N, T>: ImmutableWeave<K, N, T>
where
K: Hash + Copy + Eq + Ord,
N: Node<K, T>,
{
type Bookmarks;
#[must_use]
fn bookmarks(&self) -> &Self::Bookmarks;
#[must_use]
fn contains_bookmark(&self, id: &K) -> bool;
}
pub trait ImmutableSortableWeave<K, N, T>: ImmutableWeave<K, N, T>
where
K: Hash + Copy + Eq + Ord,
N: Node<K, T>,
{
fn get_ordered_node_identifiers_mirrored(&self, output: &mut Vec<K>);
fn get_ordered_node_identifiers_mirrored_from(&self, id: &K, output: &mut Vec<K>);
}
pub trait ImmutableActiveSingularWeave<K, N, T>: ImmutableWeave<K, N, T>
where
K: Hash + Copy + Eq + Ord,
N: Node<K, T>,
{
#[must_use]
fn active(&self) -> Option<K>;
}
pub trait ImmutableActivePathWeave<K, N, T>: ImmutableWeave<K, N, T>
where
K: Hash + Copy + Eq + Ord,
N: Node<K, T>,
{
type Active;
#[must_use]
fn active(&self) -> &Self::Active;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Step<A, B> {
Enter(A),
Exit(B),
}
fn topological_sort<'a, K, N, T, S>(
nodes: &'a HashMap<K, N, S>,
id: &'a K,
scratchpad: &mut Vec<K>,
identifiers: &mut Vec<K>,
identifier_set: &mut HashSet<K, S>,
identifier_map: &mut HashMap<K, usize, S>,
) where
K: Hash + Copy + Eq + Ord + 'a,
N: Node<K, T> + 'a,
<N as Node<K, T>>::From: 'a,
<N as Node<K, T>>::To: 'a,
&'a N::From: IntoIterator<Item = &'a K, IntoIter: DoubleEndedIterator + ExactSizeIterator>,
&'a N::To: IntoIterator<Item = &'a K, IntoIter: DoubleEndedIterator>,
S: BuildHasher + Default + Clone,
{
scratchpad.push(*id);
while let Some(id) = scratchpad.pop() {
let node = &nodes[&id];
if identifier_set.contains(&id)
|| identifier_map
.get(&id)
.copied()
.unwrap_or_else(|| node.from().into_iter().len())
!= 0
{
continue;
}
identifiers.push(id);
identifier_set.insert(id);
for child in node.to().into_iter().rev().copied() {
let remaining = identifier_map
.entry(child)
.or_insert_with(|| nodes[&child].from().into_iter().len());
*remaining = remaining.strict_sub(1);
scratchpad.push(child);
}
}
}
fn topological_sort_subgraph<'a, K, N, T, S>(
nodes: &'a HashMap<K, N, S>,
filter: &impl Fn(&K) -> bool,
id: &'a K,
scratchpad: &mut Vec<K>,
identifiers: &mut Vec<K>,
identifier_set: &mut HashSet<K, S>,
identifier_map: &mut HashMap<K, usize, S>,
) where
K: Hash + Copy + Eq + Ord + 'a,
N: Node<K, T> + 'a,
<N as Node<K, T>>::From: 'a,
<N as Node<K, T>>::To: 'a,
&'a N::From: IntoIterator<Item = &'a K, IntoIter: DoubleEndedIterator>,
&'a N::To: IntoIterator<Item = &'a K, IntoIter: DoubleEndedIterator>,
S: BuildHasher + Default + Clone,
{
scratchpad.push(*id);
while let Some(id) = scratchpad.pop() {
let node = &nodes[&id];
if !filter(&id)
|| identifier_set.contains(&id)
|| identifier_map.get(&id).copied().unwrap_or_else(|| {
node.from()
.into_iter()
.filter(|&parent| filter(parent))
.count()
}) != 0
{
continue;
}
identifiers.push(id);
identifier_set.insert(id);
for child in node.to().into_iter().rev().copied() {
let remaining = identifier_map.entry(child).or_insert_with(|| {
nodes[&child]
.from()
.into_iter()
.filter(|&parent| filter(parent))
.count()
});
*remaining = remaining.strict_sub(1);
scratchpad.push(child);
}
}
}
fn topological_sort_subgraph_mirrored<'a, K, N, T, S>(
nodes: &'a HashMap<K, N, S>,
filter: &impl Fn(&K) -> bool,
id: &'a K,
scratchpad: &mut Vec<K>,
identifiers: &mut Vec<K>,
identifier_set: &mut HashSet<K, S>,
identifier_map: &mut HashMap<K, usize, S>,
) where
K: Hash + Copy + Eq + Ord + 'a,
N: Node<K, T> + 'a,
<N as Node<K, T>>::From: 'a,
<N as Node<K, T>>::To: 'a,
&'a N::From: IntoIterator<Item = &'a K, IntoIter: DoubleEndedIterator>,
&'a N::To: IntoIterator<Item = &'a K, IntoIter: DoubleEndedIterator>,
S: BuildHasher + Default + Clone,
{
scratchpad.push(*id);
while let Some(id) = scratchpad.pop() {
let node = &nodes[&id];
if !filter(&id)
|| identifier_set.contains(&id)
|| identifier_map.get(&id).copied().unwrap_or_else(|| {
node.from()
.into_iter()
.filter(|&parent| filter(parent))
.count()
}) != 0
{
continue;
}
identifiers.push(id);
identifier_set.insert(id);
for child in node.to().into_iter().copied() {
let remaining = identifier_map.entry(child).or_insert_with(|| {
nodes[&child]
.from()
.into_iter()
.filter(|&parent| filter(parent))
.count()
});
*remaining = remaining.strict_sub(1);
scratchpad.push(child);
}
}
}
fn topological_sort_mirrored<'a, K, N, T, S>(
nodes: &'a HashMap<K, N, S>,
id: &'a K,
scratchpad: &mut Vec<K>,
identifiers: &mut Vec<K>,
identifier_set: &mut HashSet<K, S>,
identifier_map: &mut HashMap<K, usize, S>,
) where
K: Hash + Copy + Eq + Ord + 'a,
N: Node<K, T> + 'a,
<N as Node<K, T>>::From: 'a,
<N as Node<K, T>>::To: 'a,
&'a N::From: IntoIterator<Item = &'a K, IntoIter: DoubleEndedIterator + ExactSizeIterator>,
&'a N::To: IntoIterator<Item = &'a K, IntoIter: DoubleEndedIterator>,
S: BuildHasher + Default + Clone,
{
scratchpad.push(*id);
while let Some(id) = scratchpad.pop() {
let node = &nodes[&id];
if identifier_set.contains(&id)
|| identifier_map
.get(&id)
.copied()
.unwrap_or_else(|| node.from().into_iter().len())
!= 0
{
continue;
}
identifiers.push(id);
identifier_set.insert(id);
for child in node.to().into_iter().copied() {
let remaining = identifier_map
.entry(child)
.or_insert_with(|| nodes[&child].from().into_iter().len());
*remaining = remaining.strict_sub(1);
scratchpad.push(child);
}
}
}
fn detect_cycles<'a, K, N, T, S>(
nodes: &'a HashMap<K, N, S>,
roots: impl Iterator<Item = K>,
scratchpad: &mut Vec<Step<K, K>>,
scratchpad_map: &mut HashMap<K, bool, S>,
) -> bool
where
K: Hash + Copy + Eq + Ord + 'a,
N: Node<K, T> + 'a,
<N as Node<K, T>>::From: 'a,
<N as Node<K, T>>::To: 'a,
&'a N::From: IntoIterator<Item = &'a K, IntoIter: DoubleEndedIterator>,
&'a N::To: IntoIterator<Item = &'a K, IntoIter: DoubleEndedIterator + ExactSizeIterator>,
S: BuildHasher + Default + Clone,
{
for root in roots {
if scratchpad_map.contains_key(&root) {
continue;
}
scratchpad.push(Step::Enter(root));
while let Some(step) = scratchpad.pop() {
match step {
Step::Enter(id) => {
scratchpad.push(Step::Exit(id));
match scratchpad_map.entry(id) {
Entry::Occupied(entry) => {
if !entry.get() {
return true;
}
}
Entry::Vacant(entry) => {
entry.insert_entry(false);
scratchpad.extend(
nodes[&id].to().into_iter().rev().copied().map(Step::Enter),
);
}
}
}
Step::Exit(id) => {
scratchpad_map.insert(id, true);
}
}
}
}
scratchpad_map.len() != nodes.len()
}
fn shortest_path_to_ancestor<'a, K, N, T, S>(
nodes: &'a HashMap<K, N, S>,
id: &'a K,
target: &impl Fn(&'a N) -> bool,
scratchpad: &mut VecDeque<K>,
scratchpad_map: &mut HashMap<K, K, S>,
scratchpad_set: &mut HashSet<K, S>,
path: &mut Vec<K>,
) where
K: Hash + Copy + Eq + Ord + 'a,
N: Node<K, T> + 'a,
<N as Node<K, T>>::From: 'a,
<N as Node<K, T>>::To: 'a,
&'a N::From: IntoIterator<Item = &'a K, IntoIter: DoubleEndedIterator>,
&'a N::To: IntoIterator<Item = &'a K, IntoIter: DoubleEndedIterator>,
S: BuildHasher + Default + Clone,
{
scratchpad.push_front(*id);
scratchpad_set.insert(*id);
while let Some(id) = scratchpad.pop_back() {
let node = &nodes[&id];
if target(node) {
scratchpad.clear();
path.push(id);
while let Some(child) = scratchpad_map.remove(path.last().unwrap()) {
path.push(child);
}
return;
}
for parent in node.from().into_iter().copied() {
if scratchpad_set.insert(parent) {
scratchpad.push_front(parent);
scratchpad_map.insert(parent, id);
}
}
}
}
fn longest_candidate_path_to_root<'a, K, N, T, S>(
nodes: &'a HashMap<K, N, S>,
topological_order: &[K],
is_candidate: &impl Fn(&K) -> bool,
scratchpad_map: &mut HashMap<K, usize, S>,
reversed_path: &mut Vec<K>,
) where
K: Hash + Copy + Eq + Ord + 'a,
N: Node<K, T> + 'a,
<N as Node<K, T>>::From: 'a,
<N as Node<K, T>>::To: 'a,
&'a N::From: IntoIterator<Item = &'a K, IntoIter: DoubleEndedIterator>,
&'a N::To: IntoIterator<Item = &'a K, IntoIter: DoubleEndedIterator>,
S: BuildHasher + Default + Clone,
{
let mut longest_distance = None;
for id in topological_order {
if !is_candidate(id) {
continue;
}
let node = &nodes[id];
let distance = if node.from().into_iter().next().is_none() {
Some(0)
} else {
node.from()
.into_iter()
.filter_map(|parent| scratchpad_map.get(parent).copied())
.max()
.map(|l| l.strict_add(1))
};
if let Some(distance) = distance {
scratchpad_map.insert(*id, distance);
if longest_distance.is_none_or(|(value, _)| distance > value) {
longest_distance = Some((distance, id));
}
}
}
let mut current = longest_distance.map(|(_, id)| id);
while let Some(id) = current {
reversed_path.push(*id);
current = nodes[id]
.from()
.into_iter()
.filter(|id| scratchpad_map.contains_key(*id))
.min_by_key(|id| Reverse(scratchpad_map[*id]));
}
}
fn ancestor_subgraph<'a, K, N, T, S>(
nodes: &'a HashMap<K, N, S>,
id: K,
scratchpad: &mut Vec<K>,
identifiers: &mut HashSet<K, S>,
) where
K: Hash + Copy + Eq + Ord + 'a,
N: Node<K, T>,
<N as Node<K, T>>::From: 'a,
<N as Node<K, T>>::To: 'a,
&'a N::From: IntoIterator<Item = &'a K, IntoIter: DoubleEndedIterator>,
&'a N::To: IntoIterator<Item = &'a K, IntoIter: DoubleEndedIterator>,
S: BuildHasher + Default + Clone,
{
scratchpad.push(id);
while let Some(id) = scratchpad.pop() {
if identifiers.insert(id) {
scratchpad.extend(nodes[&id].from().into_iter().rev().copied());
}
}
}
fn descendant_subgraph<'a, K, N, T, S>(
nodes: &'a HashMap<K, N, S>,
id: K,
scratchpad: &mut Vec<K>,
identifiers: &mut HashSet<K, S>,
) where
K: Hash + Copy + Eq + Ord + 'a,
N: Node<K, T>,
<N as Node<K, T>>::From: 'a,
<N as Node<K, T>>::To: 'a,
&'a N::From: IntoIterator<Item = &'a K, IntoIter: DoubleEndedIterator>,
&'a N::To: IntoIterator<Item = &'a K, IntoIter: DoubleEndedIterator>,
S: BuildHasher + Default + Clone,
{
scratchpad.push(id);
while let Some(id) = scratchpad.pop() {
if identifiers.insert(id) {
scratchpad.extend(nodes[&id].to().into_iter().rev().copied());
}
}
}