use std::fmt;
use std::sync::Arc;
use crate::error::{DataError, StructureError};
use crate::text::Run;
use crate::value::{Meta, Value, compare};
pub(crate) use sealed::Measure;
pub(crate) const CHUNK: usize = 8;
pub trait Element: Clone + fmt::Debug + sealed::Sealed {}
impl Element for Value {}
impl Element for (Value, Value) {}
impl Element for Member {}
impl Element for Run {}
#[derive(Clone, Debug)]
pub struct Member(Value);
impl Member {
pub fn new(value: Value) -> Member {
Member(value)
}
pub fn value(&self) -> &Value {
&self.0
}
pub(crate) fn value_mut(&mut self) -> &mut Value {
&mut self.0
}
}
pub trait Keyed: Element + sealed::Sealed<Key = Value, Measure = Meta> {
fn sort_key(&self) -> &Value {
sealed::Sealed::key(self)
}
}
impl Keyed for (Value, Value) {}
impl Keyed for Member {}
mod sealed {
use std::fmt;
use super::{CHUNK, Member};
use crate::text::{Run, Span};
use crate::value::{Meta, Value};
pub trait Measure: Copy + PartialEq + fmt::Debug {
const EMPTY: Self;
#[must_use]
fn join(self, other: Self) -> Self;
}
pub trait Sealed {
type Key: Clone + fmt::Debug;
type Measure: Measure;
const LEAF: usize;
fn key(&self) -> &Self::Key;
fn measure(&self) -> Self::Measure;
}
impl Sealed for Value {
type Key = ();
type Measure = Meta;
const LEAF: usize = CHUNK;
fn key(&self) -> &() {
&()
}
fn measure(&self) -> Meta {
Meta::EMPTY.with(self)
}
}
impl Sealed for (Value, Value) {
type Key = Value;
type Measure = Meta;
const LEAF: usize = CHUNK;
fn key(&self) -> &Value {
&self.0
}
fn measure(&self) -> Meta {
Meta::EMPTY.with(&self.0).with(&self.1)
}
}
impl Sealed for Member {
type Key = Value;
type Measure = Meta;
const LEAF: usize = CHUNK;
fn key(&self) -> &Value {
&self.0
}
fn measure(&self) -> Meta {
Meta::EMPTY.with(&self.0)
}
}
impl Sealed for Run {
type Key = ();
type Measure = Span;
const LEAF: usize = 1;
fn key(&self) -> &() {
&()
}
fn measure(&self) -> Span {
self.span()
}
}
}
#[derive(Debug)]
pub struct Node<T: Element = Value>(Arc<Inner<T>>);
impl<T: Element> Clone for Node<T> {
fn clone(&self) -> Self {
Node(Arc::clone(&self.0))
}
}
pub(crate) type Tree<T = Value> = Node<T>;
#[derive(Clone, Debug)]
enum Inner<T: Element> {
Leaf(Vec<T>, T::Measure),
Branch(Branch<T>),
}
#[derive(Clone, Debug)]
struct Branch<T: Element> {
left: Tree<T>,
right: Tree<T>,
len: usize,
height: u8,
measure: T::Measure,
first: T::Key,
}
#[derive(Debug)]
pub enum Shape<'a, T: Element> {
Leaf(&'a [T]),
Branch(&'a Node<T>, &'a Node<T>),
}
impl<T: Element> Node<T> {
pub fn leaf(items: Vec<T>) -> Result<Self, StructureError> {
if (1..=T::LEAF).contains(&items.len()) {
Ok(leaf(items))
} else {
Err(StructureError::Leaf)
}
}
pub fn branch(left: Self, right: Self) -> Self {
if left.level().abs_diff(right.level()) <= 1 {
branch(left, right)
} else {
join(left, right)
}
}
pub fn id(&self) -> usize {
Arc::as_ptr(&self.0).addr()
}
pub fn len(&self) -> usize {
match &*self.0 {
Inner::Leaf(items, _) => items.len(),
Inner::Branch(branch) => branch.len,
}
}
pub fn is_empty(&self) -> bool {
false
}
pub fn window(&self, skip: usize, count: usize) -> Result<Self, StructureError> {
let fits = count > 0 && skip.checked_add(count).is_some_and(|end| end <= self.len());
if !fits {
return Err(StructureError::Window);
}
range(self.clone(), skip, count).ok_or(StructureError::Window)
}
pub fn height(&self) -> usize {
usize::from(self.level())
}
pub fn shape(&self) -> Shape<'_, T> {
match &*self.0 {
Inner::Leaf(items, _) => Shape::Leaf(items),
Inner::Branch(branch) => Shape::Branch(&branch.left, &branch.right),
}
}
fn level(&self) -> u8 {
match &*self.0 {
Inner::Leaf(..) => 0,
Inner::Branch(branch) => branch.height,
}
}
pub(crate) fn measure(&self) -> T::Measure {
match &*self.0 {
Inner::Leaf(_, measure) => *measure,
Inner::Branch(branch) => branch.measure,
}
}
fn first(&self) -> T::Key {
match &*self.0 {
Inner::Leaf(items, _) => sealed::Sealed::key(&items[0]).clone(),
Inner::Branch(branch) => branch.first.clone(),
}
}
}
pub(crate) fn range_measure<T: Element>(tree: &Tree<T>, start: usize, len: usize) -> T::Measure {
if len == 0 {
return Measure::EMPTY;
}
if start == 0 && len == tree.len() {
return tree.measure();
}
match &*tree.0 {
Inner::Leaf(items, _) => measure(&items[start..start + len]),
Inner::Branch(branch) => {
let before = branch.left.len();
let in_left = before.saturating_sub(start).min(len);
let left = range_measure(&branch.left, start.min(before), in_left);
let right = range_measure(&branch.right, start.saturating_sub(before), len - in_left);
left.join(right)
}
}
}
fn measure<T: Element>(items: &[T]) -> T::Measure {
items
.iter()
.map(sealed::Sealed::measure)
.fold(Measure::EMPTY, Measure::join)
}
pub(crate) fn leaf<T: Element>(items: Vec<T>) -> Tree<T> {
let measure = measure(&items);
Node(Arc::new(Inner::Leaf(items, measure)))
}
fn branch<T: Element>(left: Tree<T>, right: Tree<T>) -> Tree<T> {
Node(Arc::new(Inner::Branch(Branch {
len: left.len() + right.len(),
height: left.level().max(right.level()) + 1,
measure: left.measure().join(right.measure()),
first: left.first(),
left,
right,
})))
}
fn children<T: Element>(tree: Tree<T>) -> (Tree<T>, Tree<T>) {
let Inner::Branch(branch) = Arc::unwrap_or_clone(tree.0) else {
unreachable!("a leaf has no subtrees")
};
(branch.left, branch.right)
}
pub(crate) fn build<T: Element>(items: impl IntoIterator<Item = T>) -> Option<Tree<T>> {
let mut items = items.into_iter();
let first: Vec<T> = items.by_ref().take(T::LEAF).collect();
if first.len() < T::LEAF {
return (!first.is_empty()).then(|| leaf(first));
}
let mut leaves = vec![leaf(first)];
loop {
let chunk: Vec<T> = items.by_ref().take(T::LEAF).collect();
if chunk.is_empty() {
break;
}
leaves.push(leaf(chunk));
}
let count = leaves.len();
Some(balanced(&mut leaves.into_iter(), count))
}
fn balanced<T: Element>(leaves: &mut impl Iterator<Item = Tree<T>>, count: usize) -> Tree<T> {
if count == 1 {
return leaves.next().expect("one leaf is left for each count");
}
let left = balanced(leaves, count / 2);
let right = balanced(leaves, count - count / 2);
branch(left, right)
}
pub(crate) fn join<T: Element>(left: Tree<T>, right: Tree<T>) -> Tree<T> {
join_with(left, right, &|_, _| None)
}
pub(crate) fn join_with<T: Element>(
left: Tree<T>,
right: Tree<T>,
fuse: &impl Fn(&Tree<T>, &Tree<T>) -> Option<Tree<T>>,
) -> Tree<T> {
if let Some(fused) = fuse(&left, &right) {
return fused;
}
let (low, high) = (left.level(), right.level());
if low > high + 1 {
let (outer, inner) = children(left);
let joined = join_with(inner, right, fuse);
if outer.level().abs_diff(joined.level()) <= 2 {
balance(outer, joined)
} else {
join(outer, joined)
}
} else if high > low + 1 {
let (inner, outer) = children(right);
let joined = join_with(left, inner, fuse);
if outer.level().abs_diff(joined.level()) <= 2 {
balance(joined, outer)
} else {
join(joined, outer)
}
} else {
branch(left, right)
}
}
fn balance<T: Element>(left: Tree<T>, right: Tree<T>) -> Tree<T> {
let (low, high) = (left.level(), right.level());
if high > low + 1 {
let (inner, outer) = children(right);
if inner.level() > outer.level() {
let (a, b) = children(inner);
branch(branch(left, a), branch(b, outer))
} else {
branch(branch(left, inner), outer)
}
} else if low > high + 1 {
let (outer, inner) = children(left);
if inner.level() > outer.level() {
let (a, b) = children(inner);
branch(branch(outer, a), branch(b, right))
} else {
branch(outer, branch(inner, right))
}
} else {
branch(left, right)
}
}
fn join_either<T: Element>(left: Option<Tree<T>>, right: Option<Tree<T>>) -> Option<Tree<T>> {
match (left, right) {
(Some(left), Some(right)) => Some(join(left, right)),
(left, right) => left.or(right),
}
}
pub(crate) trait Along<T: Element> {
fn node(&self, tree: &Tree<T>) -> usize;
fn item(&self, item: &T) -> usize;
fn cut(&self, item: &T, at: usize) -> Option<(T, T)>;
}
struct Count;
impl<T: Element> Along<T> for Count {
fn node(&self, tree: &Tree<T>) -> usize {
tree.len()
}
fn item(&self, _: &T) -> usize {
1
}
fn cut(&self, _: &T, _: usize) -> Option<(T, T)> {
unreachable!("a position counted by element lies between two")
}
}
pub(crate) type Halves<T> = (Option<Tree<T>>, Option<Tree<T>>);
pub(crate) fn split<T: Element>(tree: Tree<T>, at: usize) -> Halves<T> {
cut(tree, at, &Count).expect("a position counted by element lies between two")
}
pub(crate) fn cut<T: Element>(
tree: Tree<T>,
at: usize,
along: &impl Along<T>,
) -> Option<Halves<T>> {
if at == 0 {
return Some((None, Some(tree)));
}
if at >= along.node(&tree) {
return Some((Some(tree), None));
}
if let Inner::Leaf(items, _) = &*tree.0 {
let mut before = 0;
let mut index = 0;
while before + along.item(&items[index]) <= at {
before += along.item(&items[index]);
index += 1;
}
let mut head = items[..index].to_vec();
let mut rest = items[index..].to_vec();
if at > before {
let (first, second) = along.cut(&items[index], at - before)?;
head.push(first);
rest[0] = second;
}
return Some((Some(leaf(head)), Some(leaf(rest))));
}
let (left, right) = children(tree);
let before = along.node(&left);
Some(if at <= before {
let (first, rest) = cut(left, at, along)?;
(first, join_either(rest, Some(right)))
} else {
let (first, rest) = cut(right, at - before, along)?;
(join_either(Some(left), first), rest)
})
}
pub(crate) fn range<T: Element>(tree: Tree<T>, start: usize, len: usize) -> Option<Tree<T>> {
let (_, rest) = split(tree, start);
split(rest?, len).0
}
pub(crate) fn push_back<T: Element>(mut tree: Tree<T>, item: T) -> Tree<T> {
match add_at_back(&mut tree, item) {
None => tree,
Some(item) => join(tree, leaf(vec![item])),
}
}
fn add_at_back<T: Element>(tree: &mut Tree<T>, item: T) -> Option<T> {
if let Inner::Leaf(items, _) = &*tree.0
&& items.len() == T::LEAF
{
return Some(item);
}
match Arc::make_mut(&mut tree.0) {
Inner::Leaf(items, measure) => {
*measure = measure.join(sealed::Sealed::measure(&item));
items.push(item);
}
Inner::Branch(branch) => {
let full = add_at_back(&mut branch.right, item);
if full.is_none() {
branch.len += 1;
branch.measure = branch.left.measure().join(branch.right.measure());
}
return full;
}
}
None
}
pub(crate) fn insert<T: Element>(tree: Tree<T>, at: usize, item: T) -> Tree<T> {
match Arc::unwrap_or_clone(tree.0) {
Inner::Leaf(mut items, _) => {
items.insert(at, item);
if items.len() <= T::LEAF {
leaf(items)
} else {
let rest = items.split_off(items.len() / 2);
branch(leaf(items), leaf(rest))
}
}
Inner::Branch(Branch { left, right, .. }) => {
let before = left.len();
if at <= before {
balance(insert(left, at, item), right)
} else {
balance(left, insert(right, at - before, item))
}
}
}
}
pub(crate) fn replace<T: Element>(mut tree: Tree<T>, at: usize, item: T) -> Tree<T> {
fn set<T: Element>(tree: &mut Tree<T>, at: usize, item: T) {
match Arc::make_mut(&mut tree.0) {
Inner::Leaf(items, recorded) => {
items[at] = item;
*recorded = measure(items);
}
Inner::Branch(branch) => {
let before = branch.left.len();
if at < before {
set(&mut branch.left, at, item);
} else {
set(&mut branch.right, at - before, item);
}
branch.measure = branch.left.measure().join(branch.right.measure());
if at == 0 {
branch.first = branch.left.first();
}
}
}
}
set(&mut tree, at, item);
tree
}
pub(crate) fn remove<T: Element>(tree: Tree<T>, at: usize) -> Option<Tree<T>> {
match Arc::unwrap_or_clone(tree.0) {
Inner::Leaf(mut items, _) => {
items.remove(at);
(!items.is_empty()).then(|| leaf(items))
}
Inner::Branch(Branch { left, right, .. }) => {
let before = left.len();
Some(if at < before {
match remove(left, at) {
Some(left) => balance(left, right),
None => right,
}
} else {
match remove(right, at - before) {
Some(right) => balance(left, right),
None => left,
}
})
}
}
}
pub(crate) fn concat<T: Element>(left: Tree<T>, right: Tree<T>) -> Tree<T> {
if right.len() <= T::LEAF {
Iter::new(Some(&right), 0, right.len())
.cloned()
.fold(left, push_back)
} else {
join(left, right)
}
}
#[cfg(test)]
thread_local! {
pub(crate) static VISITED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
fn visited() {
#[cfg(test)]
VISITED.with(|visited| visited.set(visited.get() + 1));
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Side {
Left,
Right,
}
fn chunk<T: Element>(tree: &Node<T>, index: usize) -> (&[T], usize) {
chunk_passing(tree, index, |_, _| {})
}
fn chunk_passing<'a, T: Element>(
mut tree: &'a Node<T>,
mut index: usize,
mut passed: impl FnMut(Side, &'a Node<T>),
) -> (&'a [T], usize) {
loop {
visited();
match &*tree.0 {
Inner::Leaf(items, _) => return (items, index),
Inner::Branch(branch) => {
let before = branch.left.len();
if index < before {
passed(Side::Right, &branch.right);
tree = &branch.left;
} else {
index -= before;
passed(Side::Left, &branch.left);
tree = &branch.right;
}
}
}
}
}
#[inline]
pub(crate) fn get<T: Element>(tree: &Node<T>, index: usize) -> &T {
let (items, at) = chunk(tree, index);
&items[at]
}
pub(crate) fn unshared<T: Element>(tree: &mut Tree<T>) -> impl Iterator<Item = &mut T> {
let mut first = None;
let mut leaves: Vec<&mut Vec<T>> = Vec::new();
let mut pending: Vec<&mut Tree<T>> = Vec::new();
let mut next = Some(tree);
while let Some(node) = next.take().or_else(|| pending.pop()) {
match Arc::get_mut(&mut node.0) {
Some(Inner::Leaf(items, _)) => match first {
None => first = Some(items),
Some(_) => leaves.push(items),
},
Some(Inner::Branch(branch)) => {
pending.push(&mut branch.right);
next = Some(&mut branch.left);
}
None => {}
}
}
first.into_iter().chain(leaves).flatten()
}
#[derive(Clone, Debug)]
pub(crate) struct Iter<'a, T: Element = Value> {
tree: Option<&'a Node<T>>,
front: usize,
back: usize,
head: std::slice::Iter<'a, T>,
tail: std::slice::Iter<'a, T>,
ahead: Option<Vec<&'a Node<T>>>,
behind: Option<Vec<&'a Node<T>>>,
}
impl<'a, T: Element> Iter<'a, T> {
pub(crate) fn new(tree: Option<&'a Node<T>>, start: usize, len: usize) -> Self {
Iter {
tree,
front: start,
back: start + len,
head: [].iter(),
tail: [].iter(),
ahead: None,
behind: None,
}
}
}
impl<'a, T: Element> Iter<'a, T> {
#[cold]
fn enter_head(&mut self) -> Option<&'a T> {
let (node, index) = match self.ahead.as_mut().map(Vec::pop) {
Some(next) => (next?, 0),
None => (self.tree?, self.front - 1),
};
let ahead = self.ahead.get_or_insert_with(Vec::new);
let (items, at) = chunk_passing(node, index, |side, node| {
if side == Side::Right {
ahead.push(node);
}
});
let end = items.len().min(at + 1 + (self.back - self.front));
self.head = items[at + 1..end].iter();
items.get(at)
}
#[cold]
fn enter_tail(&mut self) -> Option<&'a T> {
let (node, index) = match self.behind.as_mut().map(Vec::pop) {
Some(next) => {
let next = next?;
(next, next.len() - 1)
}
None => (self.tree?, self.back),
};
let behind = self.behind.get_or_insert_with(Vec::new);
let (items, at) = chunk_passing(node, index, |side, node| {
if side == Side::Left {
behind.push(node);
}
});
let start = at.saturating_sub(self.back - self.front);
self.tail = items[start..at].iter();
items.get(at)
}
}
impl<'a, T: Element> Iterator for Iter<'a, T> {
type Item = &'a T;
#[inline]
fn next(&mut self) -> Option<&'a T> {
if self.front == self.back {
return None;
}
self.front += 1;
self.head.next().or_else(|| self.enter_head())
}
fn nth(&mut self, n: usize) -> Option<&'a T> {
if n >= self.back - self.front {
self.front = self.back;
return None;
}
self.front += n + 1;
self.ahead = None;
self.enter_head()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let left = self.back - self.front;
(left, Some(left))
}
}
impl<'a, T: Element> DoubleEndedIterator for Iter<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<&'a T> {
if self.front == self.back {
return None;
}
self.back -= 1;
self.tail.next_back().or_else(|| self.enter_tail())
}
fn nth_back(&mut self, n: usize) -> Option<&'a T> {
if n >= self.back - self.front {
self.back = self.front;
return None;
}
self.back -= n + 1;
self.behind = None;
self.enter_tail()
}
}
impl<T: Element> ExactSizeIterator for Iter<'_, T> {}
pub(crate) type Found<'a, T> = Result<(usize, &'a T), usize>;
pub(crate) fn find<'a, T: Keyed>(
mut tree: &'a Node<T>,
key: &Value,
) -> Result<Found<'a, T>, DataError> {
let mut before = 0;
loop {
match &*tree.0 {
Inner::Branch(branch) => {
let first = match &*branch.right.0 {
Inner::Leaf(items, _) => items[0].sort_key(),
Inner::Branch(right) => &right.first,
};
if compare(key, first)?.is_lt() {
tree = &branch.left;
} else {
before += branch.left.len();
tree = &branch.right;
}
}
Inner::Leaf(items, _) => {
let mut failure = None;
let found = items.binary_search_by(|candidate| {
compare(candidate.sort_key(), key).unwrap_or_else(|error| {
failure = Some(error);
std::cmp::Ordering::Equal
})
});
if let Some(error) = failure {
return Err(error);
}
return Ok(match found {
Ok(at) => Ok((before + at, &items[at])),
Err(at) => Err(before + at),
});
}
}
}
}
#[cfg(test)]
pub(crate) fn check<T: Element>(tree: &Node<T>) -> u8 {
match &*tree.0 {
Inner::Leaf(items, _) => {
assert!(
(1..=T::LEAF).contains(&items.len()),
"a leaf holds 1 to LEAF elements"
);
0
}
Inner::Branch(branch) => {
let (left, right) = (check(&branch.left), check(&branch.right));
assert!(left.abs_diff(right) <= 1, "subtrees differ by at most one");
assert_eq!(branch.height, left.max(right) + 1, "height is recorded");
assert_eq!(
branch.len,
branch.left.len() + branch.right.len(),
"length is recorded"
);
assert_eq!(
branch.measure,
branch.left.measure().join(branch.right.measure()),
"measure is recorded"
);
branch.height
}
}
}
#[cfg(test)]
pub(crate) fn check_keys<T: Keyed>(tree: &Node<T>) {
if let Inner::Branch(branch) = &*tree.0 {
let mut leftmost = &branch.left;
while let Inner::Branch(next) = &*leftmost.0 {
leftmost = &next.left;
}
let Inner::Leaf(items, _) = &*leftmost.0 else {
unreachable!("the walk ends at a leaf")
};
assert_eq!(
compare(&branch.first, items[0].sort_key()),
Ok(std::cmp::Ordering::Equal),
"a branch keeps its first key"
);
check_keys(&branch.left);
check_keys(&branch.right);
}
}
#[cfg(test)]
pub(crate) fn leaves<T: Element>(tree: &Tree<T>, out: &mut Vec<usize>) {
match &*tree.0 {
Inner::Leaf(..) => out.push(tree.id()),
Inner::Branch(branch) => {
leaves(&branch.left, out);
leaves(&branch.right, out);
}
}
}