Skip to main content

music21/tree/
core.rs

1//! music21's `tree.core`: the self-balancing AVL tree its element, offset
2//! and timespan trees are built on.
3//!
4//! The steps -- placing a node, rotating and rebalancing, finding the node
5//! at, after or before a position, taking one out, building a balanced tree
6//! from a sorted list, counting the elements under each node -- are written
7//! once over [`AvlNodes`], so they work on nodes however they are stored.
8//! [`AvlTree`] keeps its nodes in a list; the Python package's nodes are
9//! Python objects music21's code can reach into.
10//!
11//! ```
12//! use music21::tree::core::AvlTree;
13//!
14//! let mut tree = AvlTree::new();
15//! for position in [20, 10, 5, 30] {
16//!     tree.insert(position, position * 2);
17//! }
18//! assert_eq!(tree.root_position(), Some(&10));
19//! assert_eq!(tree.height(), Some(2));
20//! assert_eq!(tree.position_after(&10), Some(&20));
21//! assert_eq!(tree.position_before(&10), Some(&5));
22//! assert_eq!(tree.get(&30), Some(&60));
23//! ```
24
25use std::fmt;
26
27/// How a node's position stands to a position given: `node.position <op>
28/// position`, as music21 asks it.
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
30pub enum Compare {
31    /// `<`
32    Less,
33    /// `<=`
34    LessOrEqual,
35    /// `==`
36    Equal,
37    /// `>`
38    Greater,
39}
40
41/// What went wrong in a tree whose nodes were linked by hand.
42#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
43pub enum TreeError {
44    /// A rotation needs a child the node does not have.
45    MissingChild,
46    /// A node is still out of balance after rebalancing.
47    Unbalanced,
48}
49
50impl fmt::Display for TreeError {
51    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
52        match self {
53            Self::MissingChild => formatter.write_str("the rotation needs a child the node lacks"),
54            Self::Unbalanced => formatter.write_str(
55                "Somehow Nodes are still not balanced. node.balance must be between -1 and 1",
56            ),
57        }
58    }
59}
60
61impl std::error::Error for TreeError {}
62
63/// A node's height and balance: music21's `height` and `balance`.
64#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
65pub struct Shape {
66    /// The height of the subtree rooted on the node; a leaf's is 0.
67    pub height: i64,
68    /// The right subtree's height less the left's.
69    pub balance: i64,
70}
71
72/// Where the elements under a node stand in the tree's order, as slice
73/// bounds: music21's `subtreeElementsStartIndex`, its payload's start and
74/// stop, and `subtreeElementsStopIndex`.
75#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
76pub struct Indices {
77    /// The first element of the subtree.
78    pub subtree_start: usize,
79    /// The first element of the node's own payload.
80    pub payload_start: usize,
81    /// One past its payload's last.
82    pub payload_stop: usize,
83    /// One past the subtree's last.
84    pub subtree_stop: usize,
85}
86
87/// One node of a balanced tree being built from a sorted list: the item at
88/// `middle` of the items `start..stop`.
89#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
90pub struct Placement {
91    /// The item the node holds.
92    pub middle: usize,
93    /// The first item of its subtree.
94    pub start: usize,
95    /// One past the last.
96    pub stop: usize,
97}
98
99/// The nodes of an AVL tree, however they are stored: what the steps of
100/// this module read and write of them.
101pub trait AvlNodes {
102    /// A handle on one node.
103    type Node: Clone;
104    /// Where a node stands.
105    type Position;
106    /// What reading or writing a node can fail with.
107    type Error: From<TreeError>;
108
109    /// The node's left child.
110    fn left(&self, node: &Self::Node) -> Result<Option<Self::Node>, Self::Error>;
111
112    /// Its right child.
113    fn right(&self, node: &Self::Node) -> Result<Option<Self::Node>, Self::Error>;
114
115    /// Sets its left child.
116    fn set_left(&mut self, node: &Self::Node, child: Option<Self::Node>)
117    -> Result<(), Self::Error>;
118
119    /// Sets its right child.
120    fn set_right(
121        &mut self,
122        node: &Self::Node,
123        child: Option<Self::Node>,
124    ) -> Result<(), Self::Error>;
125
126    /// Its height and balance as last updated.
127    fn shape(&self, node: &Self::Node) -> Result<Shape, Self::Error>;
128
129    /// Sets its height and balance.
130    fn set_shape(&mut self, node: &Self::Node, shape: Shape) -> Result<(), Self::Error>;
131
132    /// Its position.
133    fn position(&self, node: &Self::Node) -> Result<Self::Position, Self::Error>;
134
135    /// Whether `node.position <compare> position`.
136    fn holds(
137        &self,
138        node: &Self::Node,
139        compare: Compare,
140        position: &Self::Position,
141    ) -> Result<bool, Self::Error>;
142
143    /// A new node at a position, holding nothing.
144    fn create(&mut self, position: &Self::Position) -> Result<Self::Node, Self::Error>;
145
146    /// Moves what one node holds -- its position and payload, not its
147    /// links or shape -- onto another: music21's `moveAttributes`.
148    fn move_attributes(&mut self, from: &Self::Node, to: &Self::Node) -> Result<(), Self::Error>;
149}
150
151/// Nodes that count the elements they hold, for [`update_indices`].
152pub trait CountedNodes: AvlNodes {
153    /// How many elements the node's own payload holds.
154    fn payload_count(&self, node: &Self::Node) -> Result<usize, Self::Error>;
155
156    /// Stores where its elements and its subtree's stand.
157    fn set_indices(&mut self, node: &Self::Node, indices: Indices) -> Result<(), Self::Error>;
158}
159
160/// Sets a node's height and balance from its children's: music21's
161/// `AVLNode.update`.
162pub fn update<N: AvlNodes>(nodes: &mut N, node: &N::Node) -> Result<(), N::Error> {
163    let left = child_height(nodes, nodes.left(node)?)?;
164    let right = child_height(nodes, nodes.right(node)?)?;
165    let shape = Shape {
166        height: left.max(right) + 1,
167        balance: right - left,
168    };
169    nodes.set_shape(node, shape)
170}
171
172/// A child's height, -1 for none.
173fn child_height<N: AvlNodes>(nodes: &N, child: Option<N::Node>) -> Result<i64, N::Error> {
174    match child {
175        Some(child) => Ok(nodes.shape(&child)?.height),
176        None => Ok(-1),
177    }
178}
179
180/// A child a rotation needs.
181fn needed<N: AvlNodes>(child: Option<N::Node>) -> Result<N::Node, N::Error> {
182    child.ok_or_else(|| TreeError::MissingChild.into())
183}
184
185/// Makes the left child the centre, the node its right child: music21's
186/// `rotateLeftLeft`. Answers the new centre.
187pub fn rotate_left_left<N: AvlNodes>(nodes: &mut N, node: &N::Node) -> Result<N::Node, N::Error> {
188    let next = needed::<N>(nodes.left(node)?)?;
189    let inner = nodes.right(&next)?;
190    nodes.set_left(node, inner)?;
191    update(nodes, node)?;
192    nodes.set_right(&next, Some(node.clone()))?;
193    update(nodes, &next)?;
194    Ok(next)
195}
196
197/// The mirror of [`rotate_left_left`]: music21's `rotateRightRight`.
198pub fn rotate_right_right<N: AvlNodes>(nodes: &mut N, node: &N::Node) -> Result<N::Node, N::Error> {
199    let next = needed::<N>(nodes.right(node)?)?;
200    let inner = nodes.left(&next)?;
201    nodes.set_right(node, inner)?;
202    update(nodes, node)?;
203    nodes.set_left(&next, Some(node.clone()))?;
204    update(nodes, &next)?;
205    Ok(next)
206}
207
208/// The left child rotated right, then the node left: music21's
209/// `rotateLeftRight`.
210pub fn rotate_left_right<N: AvlNodes>(nodes: &mut N, node: &N::Node) -> Result<N::Node, N::Error> {
211    let left = needed::<N>(nodes.left(node)?)?;
212    let rotated = rotate_right_right(nodes, &left)?;
213    nodes.set_left(node, Some(rotated))?;
214    update(nodes, node)?;
215    rotate_left_left(nodes, node)
216}
217
218/// The right child rotated left, then the node right: music21's
219/// `rotateRightLeft`.
220pub fn rotate_right_left<N: AvlNodes>(nodes: &mut N, node: &N::Node) -> Result<N::Node, N::Error> {
221    let right = needed::<N>(nodes.right(node)?)?;
222    let rotated = rotate_left_left(nodes, &right)?;
223    nodes.set_right(node, Some(rotated))?;
224    update(nodes, node)?;
225    rotate_right_right(nodes, node)
226}
227
228/// Rebalances the subtree rooted on a node, answering its new centre:
229/// music21's `rebalance`.
230pub fn rebalance<N: AvlNodes>(nodes: &mut N, node: &N::Node) -> Result<N::Node, N::Error> {
231    let balance = nodes.shape(node)?.balance;
232    let centre = if balance > 1 {
233        let right = needed::<N>(nodes.right(node)?)?;
234        if nodes.shape(&right)?.balance >= 0 {
235            rotate_right_right(nodes, node)?
236        } else {
237            rotate_right_left(nodes, node)?
238        }
239    } else if balance < -1 {
240        let left = needed::<N>(nodes.left(node)?)?;
241        if nodes.shape(&left)?.balance <= 0 {
242            rotate_left_left(nodes, node)?
243        } else {
244            rotate_left_right(nodes, node)?
245        }
246    } else {
247        node.clone()
248    };
249
250    let balance = nodes.shape(&centre)?.balance;
251    if !(-1..=1).contains(&balance) {
252        return Err(TreeError::Unbalanced.into());
253    }
254    Ok(centre)
255}
256
257/// Places a node at a position under `root` unless one is there, answering
258/// the new root: music21's `createNodeAtPosition`.
259pub fn insert<N: AvlNodes>(
260    nodes: &mut N,
261    root: Option<N::Node>,
262    position: &N::Position,
263) -> Result<N::Node, N::Error> {
264    let Some(node) = root else {
265        return nodes.create(position);
266    };
267
268    // Down to where the position belongs, rebalancing on the way back up.
269    if nodes.holds(&node, Compare::Greater, position)? {
270        let left = nodes.left(&node)?;
271        let placed = insert(nodes, left, position)?;
272        nodes.set_left(&node, Some(placed))?;
273        update(nodes, &node)?;
274    } else if nodes.holds(&node, Compare::Less, position)? {
275        let right = nodes.right(&node)?;
276        let placed = insert(nodes, right, position)?;
277        nodes.set_right(&node, Some(placed))?;
278        update(nodes, &node)?;
279    }
280    rebalance(nodes, &node)
281}
282
283/// The node at a position: music21's `getNodeByPosition`.
284pub fn find<N: AvlNodes>(
285    nodes: &N,
286    root: Option<N::Node>,
287    position: &N::Position,
288) -> Result<Option<N::Node>, N::Error> {
289    let mut current = root;
290    while let Some(node) = current {
291        if nodes.holds(&node, Compare::Equal, position)? {
292            return Ok(Some(node));
293        }
294        let left = nodes.left(&node)?;
295        if left.is_some() && nodes.holds(&node, Compare::Greater, position)? {
296            current = left;
297            continue;
298        }
299        let right = nodes.right(&node)?;
300        if right.is_some() && nodes.holds(&node, Compare::Less, position)? {
301            current = right;
302            continue;
303        }
304        return Ok(None);
305    }
306    Ok(None)
307}
308
309/// The first node after a position: music21's `getNodeAfter`.
310pub fn node_after<N: AvlNodes>(
311    nodes: &N,
312    root: Option<N::Node>,
313    position: &N::Position,
314) -> Result<Option<N::Node>, N::Error> {
315    let Some(node) = root else {
316        return Ok(None);
317    };
318    let right = nodes.right(&node)?;
319    if right.is_some() && nodes.holds(&node, Compare::LessOrEqual, position)? {
320        return node_after(nodes, right, position);
321    }
322    if nodes.holds(&node, Compare::Greater, position)? {
323        let left = nodes.left(&node)?;
324        return Ok(node_after(nodes, left, position)?.or(Some(node)));
325    }
326    Ok(None)
327}
328
329/// The last node before a position: music21's `getNodeBefore`.
330pub fn node_before<N: AvlNodes>(
331    nodes: &N,
332    root: Option<N::Node>,
333    position: &N::Position,
334) -> Result<Option<N::Node>, N::Error> {
335    let Some(node) = root else {
336        return Ok(None);
337    };
338    if nodes.holds(&node, Compare::Less, position)? {
339        let right = nodes.right(&node)?;
340        return Ok(node_before(nodes, right, position)?.or(Some(node)));
341    }
342    let left = nodes.left(&node)?;
343    if left.is_some() {
344        return node_before(nodes, left, position);
345    }
346    Ok(None)
347}
348
349/// Takes out the node at a position, answering the new root: music21's
350/// `removeNode`. A node with two children takes on what the leftmost node
351/// of its right subtree holds, and that node goes instead.
352pub fn remove<N: AvlNodes>(
353    nodes: &mut N,
354    root: Option<N::Node>,
355    position: &N::Position,
356) -> Result<Option<N::Node>, N::Error> {
357    let Some(node) = root else {
358        return Ok(None);
359    };
360    let left = nodes.left(&node)?;
361    let right = nodes.right(&node)?;
362
363    let kept = if nodes.holds(&node, Compare::Equal, position)? {
364        match (left, right) {
365            (Some(_), Some(right)) => {
366                let mut next = right.clone();
367                while let Some(further) = nodes.left(&next)? {
368                    next = further;
369                }
370                nodes.move_attributes(&next, &node)?;
371                let moved = nodes.position(&next)?;
372                let rest = remove(nodes, Some(right), &moved)?;
373                nodes.set_right(&node, rest)?;
374                update(nodes, &node)?;
375                Some(node)
376            }
377            (left, right) => left.or(right),
378        }
379    } else if nodes.holds(&node, Compare::Greater, position)? {
380        let rest = remove(nodes, left, position)?;
381        nodes.set_left(&node, rest)?;
382        update(nodes, &node)?;
383        Some(node)
384    } else if nodes.holds(&node, Compare::Less, position)? {
385        let rest = remove(nodes, right, position)?;
386        nodes.set_right(&node, rest)?;
387        update(nodes, &node)?;
388        Some(node)
389    } else {
390        Some(node)
391    };
392
393    match kept {
394        Some(node) => Ok(Some(rebalance(nodes, &node)?)),
395        None => Ok(None),
396    }
397}
398
399/// Every node under `root`, left to right.
400pub fn in_order<N: AvlNodes>(nodes: &N, root: Option<N::Node>) -> Result<Vec<N::Node>, N::Error> {
401    let mut found = Vec::new();
402    let mut pending = Vec::new();
403    let mut current = root;
404    loop {
405        while let Some(node) = current {
406            current = nodes.left(&node)?;
407            pending.push(node);
408        }
409        let Some(node) = pending.pop() else {
410            return Ok(found);
411        };
412        current = nodes.right(&node)?;
413        found.push(node);
414    }
415}
416
417/// A balanced tree of `count` sorted items, each node made by `make` from
418/// where its item stands: music21's `populateFromSortedList`. Answers the
419/// root.
420pub fn build_sorted<N, F>(
421    nodes: &mut N,
422    count: usize,
423    make: &mut F,
424) -> Result<Option<N::Node>, N::Error>
425where
426    N: AvlNodes,
427    F: FnMut(&mut N, Placement) -> Result<N::Node, N::Error>,
428{
429    build_range(nodes, 0, count, make)
430}
431
432/// The balanced subtree of the items `start..stop`.
433fn build_range<N, F>(
434    nodes: &mut N,
435    start: usize,
436    stop: usize,
437    make: &mut F,
438) -> Result<Option<N::Node>, N::Error>
439where
440    N: AvlNodes,
441    F: FnMut(&mut N, Placement) -> Result<N::Node, N::Error>,
442{
443    if start >= stop {
444        return Ok(None);
445    }
446    let middle = start + (stop - start) / 2;
447    let node = make(
448        nodes,
449        Placement {
450            middle,
451            start,
452            stop,
453        },
454    )?;
455    let left = build_range(nodes, start, middle, make)?;
456    nodes.set_left(&node, left)?;
457    let right = build_range(nodes, middle + 1, stop, make)?;
458    nodes.set_right(&node, right)?;
459    update(nodes, &node)?;
460    Ok(Some(node))
461}
462
463/// Counts the elements under each node from `node` down and stores where
464/// each node's stand: music21's `updateIndices`. `parent_stop` is where the
465/// elements before the subtree end, if any come before it.
466pub fn update_indices<N: CountedNodes>(
467    nodes: &mut N,
468    node: &N::Node,
469    parent_stop: Option<usize>,
470) -> Result<Indices, N::Error> {
471    let (subtree_start, payload_start) = match nodes.left(node)? {
472        Some(left) => {
473            let below = update_indices(nodes, &left, parent_stop)?;
474            (below.subtree_start, below.subtree_stop)
475        }
476        None => {
477            let start = parent_stop.unwrap_or(0);
478            (start, start)
479        }
480    };
481    let payload_stop = payload_start + nodes.payload_count(node)?;
482    let subtree_stop = match nodes.right(node)? {
483        Some(right) => update_indices(nodes, &right, Some(payload_stop))?.subtree_stop,
484        None => payload_stop,
485    };
486
487    let indices = Indices {
488        subtree_start,
489        payload_start,
490        payload_stop,
491        subtree_stop,
492    };
493    nodes.set_indices(node, indices)?;
494    Ok(indices)
495}
496
497/// One node of an [`AvlTree`].
498#[derive(Clone, Debug)]
499struct Slot<P, T> {
500    position: P,
501    payload: Option<T>,
502    shape: Shape,
503    left: Option<usize>,
504    right: Option<usize>,
505}
506
507/// An AVL tree of payloads by position, its nodes kept in a list.
508///
509/// A node can stand at a position without a payload, as music21's
510/// `createNodeAtPosition` leaves one.
511#[derive(Clone, Debug)]
512pub struct AvlTree<P, T> {
513    slots: Vec<Slot<P, T>>,
514    root: Option<usize>,
515}
516
517impl<P, T> Default for AvlTree<P, T> {
518    fn default() -> Self {
519        Self {
520            slots: Vec::new(),
521            root: None,
522        }
523    }
524}
525
526impl<P: PartialOrd + Clone, T> AvlNodes for AvlTree<P, T> {
527    type Node = usize;
528    type Position = P;
529    type Error = TreeError;
530
531    fn left(&self, node: &usize) -> Result<Option<usize>, TreeError> {
532        Ok(self.slots[*node].left)
533    }
534
535    fn right(&self, node: &usize) -> Result<Option<usize>, TreeError> {
536        Ok(self.slots[*node].right)
537    }
538
539    fn set_left(&mut self, node: &usize, child: Option<usize>) -> Result<(), TreeError> {
540        self.slots[*node].left = child;
541        Ok(())
542    }
543
544    fn set_right(&mut self, node: &usize, child: Option<usize>) -> Result<(), TreeError> {
545        self.slots[*node].right = child;
546        Ok(())
547    }
548
549    fn shape(&self, node: &usize) -> Result<Shape, TreeError> {
550        Ok(self.slots[*node].shape)
551    }
552
553    fn set_shape(&mut self, node: &usize, shape: Shape) -> Result<(), TreeError> {
554        self.slots[*node].shape = shape;
555        Ok(())
556    }
557
558    fn position(&self, node: &usize) -> Result<P, TreeError> {
559        Ok(self.slots[*node].position.clone())
560    }
561
562    fn holds(&self, node: &usize, compare: Compare, position: &P) -> Result<bool, TreeError> {
563        let held = &self.slots[*node].position;
564        Ok(match compare {
565            Compare::Less => held < position,
566            Compare::LessOrEqual => held <= position,
567            Compare::Equal => held == position,
568            Compare::Greater => held > position,
569        })
570    }
571
572    fn create(&mut self, position: &P) -> Result<usize, TreeError> {
573        self.slots.push(Slot {
574            position: position.clone(),
575            payload: None,
576            shape: Shape::default(),
577            left: None,
578            right: None,
579        });
580        Ok(self.slots.len() - 1)
581    }
582
583    fn move_attributes(&mut self, from: &usize, to: &usize) -> Result<(), TreeError> {
584        let position = self.slots[*from].position.clone();
585        let payload = self.slots[*from].payload.take();
586        let target = &mut self.slots[*to];
587        target.position = position;
588        target.payload = payload;
589        Ok(())
590    }
591}
592
593impl<P: PartialOrd + Clone, T> AvlTree<P, T> {
594    /// An empty tree.
595    pub fn new() -> Self {
596        Self::default()
597    }
598
599    /// A balanced tree of items sorted by strictly rising position.
600    pub fn from_sorted(items: Vec<(P, T)>) -> Self {
601        let mut tree = Self::new();
602        let count = items.len();
603        let mut items: Vec<Option<(P, T)>> = items.into_iter().map(Some).collect();
604        let mut make = |tree: &mut Self, placed: Placement| {
605            let (position, payload) = items[placed.middle].take().ok_or(TreeError::MissingChild)?;
606            let node = tree.create(&position)?;
607            tree.slots[node].payload = Some(payload);
608            Ok(node)
609        };
610        tree.root = build_sorted(&mut tree, count, &mut make).unwrap_or_default();
611        tree
612    }
613
614    /// Puts a payload at a position, replacing what was there.
615    pub fn insert(&mut self, position: P, payload: T) {
616        // Every step on a tree built only through these methods holds.
617        if let Ok(root) = insert(self, self.root, &position) {
618            self.root = Some(root);
619        }
620        if let Ok(Some(node)) = find(self, self.root, &position) {
621            self.slots[node].payload = Some(payload);
622        }
623    }
624
625    /// The payload at a position.
626    pub fn get(&self, position: &P) -> Option<&T> {
627        let node = find(self, self.root, position).ok()??;
628        self.slots[node].payload.as_ref()
629    }
630
631    /// Takes out the node at a position.
632    pub fn remove(&mut self, position: &P) {
633        if let Ok(root) = remove(self, self.root, position) {
634            self.root = root;
635        }
636    }
637
638    /// The first position after one given.
639    pub fn position_after(&self, position: &P) -> Option<&P> {
640        let node = node_after(self, self.root, position).ok()??;
641        Some(&self.slots[node].position)
642    }
643
644    /// The last position before one given.
645    pub fn position_before(&self, position: &P) -> Option<&P> {
646        let node = node_before(self, self.root, position).ok()??;
647        Some(&self.slots[node].position)
648    }
649
650    /// The root's position.
651    pub fn root_position(&self) -> Option<&P> {
652        self.root.map(|root| &self.slots[root].position)
653    }
654
655    /// The root's height; none for an empty tree.
656    pub fn height(&self) -> Option<i64> {
657        self.root.map(|root| self.slots[root].shape.height)
658    }
659
660    /// Every position and payload, left to right.
661    pub fn iter(&self) -> impl Iterator<Item = (&P, Option<&T>)> {
662        in_order(self, self.root)
663            .unwrap_or_default()
664            .into_iter()
665            .map(|node| {
666                (
667                    &self.slots[node].position,
668                    self.slots[node].payload.as_ref(),
669                )
670            })
671    }
672}
673
674#[cfg(test)]
675mod tests {
676    use super::*;
677
678    /// The positions of a tree left to right, with each node's height.
679    fn shapes(tree: &AvlTree<i32, ()>) -> Vec<(i32, i64)> {
680        in_order(tree, tree.root)
681            .unwrap_or_default()
682            .into_iter()
683            .map(|node| (tree.slots[node].position, tree.slots[node].shape.height))
684            .collect()
685    }
686
687    #[test]
688    fn placing_nodes_keeps_the_tree_balanced() {
689        let mut tree = AvlTree::new();
690        for position in [0, 2, 4, 6, 8, 10, 12] {
691            tree.insert(position, ());
692        }
693        assert_eq!(
694            shapes(&tree),
695            [(0, 0), (2, 1), (4, 0), (6, 2), (8, 0), (10, 1), (12, 0)]
696        );
697    }
698
699    #[test]
700    fn taking_out_a_node_with_two_children_moves_its_successor_up() {
701        let mut tree = AvlTree::new();
702        for position in [20, 10, 5, 30] {
703            tree.insert(position, position);
704        }
705        tree.remove(&30);
706        assert_eq!(tree.root_position(), Some(&10));
707        assert_eq!(tree.height(), Some(1));
708        tree.remove(&10);
709        assert_eq!(tree.root_position(), Some(&20));
710        assert_eq!(tree.get(&20), Some(&20));
711        tree.remove(&9);
712        assert_eq!(tree.height(), Some(1));
713    }
714
715    #[test]
716    fn a_sorted_list_is_built_balanced() {
717        let tree = AvlTree::from_sorted((0..1000).map(|i| (i, i)).collect());
718        assert_eq!(tree.root_position(), Some(&500));
719        assert_eq!(tree.height(), Some(9));
720        assert_eq!(tree.iter().count(), 1000);
721    }
722
723    #[test]
724    fn positions_after_and_before_skip_the_one_given() {
725        let tree = AvlTree::from_sorted(vec![(1, ()), (3, ()), (5, ())]);
726        assert_eq!(tree.position_after(&3), Some(&5));
727        assert_eq!(tree.position_after(&5), None);
728        assert_eq!(tree.position_before(&1), None);
729        assert_eq!(tree.position_before(&4), Some(&3));
730    }
731
732    /// Counts one element per node, as music21's `ElementNode` does.
733    struct Counted {
734        tree: AvlTree<i32, ()>,
735        indices: Vec<Indices>,
736    }
737
738    impl AvlNodes for Counted {
739        type Node = usize;
740        type Position = i32;
741        type Error = TreeError;
742
743        fn left(&self, node: &usize) -> Result<Option<usize>, TreeError> {
744            self.tree.left(node)
745        }
746        fn right(&self, node: &usize) -> Result<Option<usize>, TreeError> {
747            self.tree.right(node)
748        }
749        fn set_left(&mut self, node: &usize, child: Option<usize>) -> Result<(), TreeError> {
750            self.tree.set_left(node, child)
751        }
752        fn set_right(&mut self, node: &usize, child: Option<usize>) -> Result<(), TreeError> {
753            self.tree.set_right(node, child)
754        }
755        fn shape(&self, node: &usize) -> Result<Shape, TreeError> {
756            self.tree.shape(node)
757        }
758        fn set_shape(&mut self, node: &usize, shape: Shape) -> Result<(), TreeError> {
759            self.tree.set_shape(node, shape)
760        }
761        fn position(&self, node: &usize) -> Result<i32, TreeError> {
762            self.tree.position(node)
763        }
764        fn holds(&self, node: &usize, compare: Compare, position: &i32) -> Result<bool, TreeError> {
765            self.tree.holds(node, compare, position)
766        }
767        fn create(&mut self, position: &i32) -> Result<usize, TreeError> {
768            self.tree.create(position)
769        }
770        fn move_attributes(&mut self, from: &usize, to: &usize) -> Result<(), TreeError> {
771            self.tree.move_attributes(from, to)
772        }
773    }
774
775    impl CountedNodes for Counted {
776        fn payload_count(&self, _node: &usize) -> Result<usize, TreeError> {
777            Ok(1)
778        }
779        fn set_indices(&mut self, node: &usize, indices: Indices) -> Result<(), TreeError> {
780            self.indices[*node] = indices;
781            Ok(())
782        }
783    }
784
785    #[test]
786    fn indices_count_the_elements_under_each_node() -> Result<(), TreeError> {
787        let tree = AvlTree::from_sorted(vec![(0, ()), (4, ()), (6, ())]);
788        let root = tree.root.ok_or(TreeError::MissingChild)?;
789        let count = tree.slots.len();
790        let mut counted = Counted {
791            tree,
792            indices: vec![Indices::default(); count],
793        };
794        let top = update_indices(&mut counted, &root, None)?;
795        assert_eq!(
796            top,
797            Indices {
798                subtree_start: 0,
799                payload_start: 1,
800                payload_stop: 2,
801                subtree_stop: 3,
802            }
803        );
804        let right = counted.right(&root)?.ok_or(TreeError::MissingChild)?;
805        assert_eq!(counted.indices[right].payload_start, 2);
806        Ok(())
807    }
808
809    #[test]
810    fn rotating_without_the_child_needed_is_an_error() {
811        let mut tree: AvlTree<i32, ()> = AvlTree::new();
812        tree.insert(1, ());
813        let root = tree.root.unwrap_or_default();
814        assert_eq!(
815            rotate_left_left(&mut tree, &root),
816            Err(TreeError::MissingChild)
817        );
818    }
819}