intrex 0.2.0

Intrusive collections with items addressed by indices
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! Intrusive red-black tree with items addressed by indices.
//!
//! # Node Access Traits
//!
//! The tree accessors manipulate nodes through application-provided types
//! (supplied through a `Nodes` generic parameter) implementing *node access
//! traits*.
//!
//! ## Color
//!
//! The following traits provide access to the color field associated with
//! nodes:
//!
//! | Trait           | Receiver         | Read | Write |
//! | --------------- | ---------------- | ---- | ----- |
//! | [`NodesRb`]     | `&self`          | x    |       |
//! | [`NodesRbMut`]  | `&mut self`      |      | x     |
//!
//! They have straightforward forwarding implementations for reference types
//! (`&T`, `&mut T`).
//!
//! ## Links
//!
//! The left/right child fields are accessed via the [`crate::bintree`]
//! module's traits, which this module builds upon.
//!
//! ## Key Comparison
//!
//! This module uses the key comparison traits defined in [`crate::bintree`]
//! to optionally support binary search trees.
//!
//! ## Values
//!
//! This module uses the node value access traits defined in
//! [`crate::node_data`].
//!
//! # Examples
//!
//! ```rust
//! use std::ops::Bound;
//! use intrex::rbtree::{Tree, Link, map_link_cmp_mut};
//!
//! type Node = (i32, Link);
//!
//! let mut nodes: Vec<Node> = Vec::new();
//! let mut tree = Tree::default();
//!
//! let mut callbacks = map_link_cmp_mut(
//!     &mut nodes,
//!     |x: &Node| &x.1,
//!     |x: &mut Node| &mut x.1,
//!     |x: &Node, y: &Node| Ord::cmp(&x.0, &y.0),
//!     |x: &Node, y: &i32| Ord::cmp(&x.0, y),
//! );
//!
//! // Add nodes
//! for value in [3, 4, 5, 2, 1] {
//!     let mut i = callbacks.pool.len();
//!     callbacks.pool.push((value, Link::default()));
//!     tree.write(&mut callbacks).bst_insert_node(i);
//! }
//!
//! // Remove node
//! let i = tree.read(&callbacks).bst_find_index(&2).unwrap();
//! tree.write(&mut callbacks).remove_node(i);
//!
//! // Find nodes
//! assert!(tree.read(&callbacks).bst_find_index(&3).is_some());
//! assert!(tree.read(&callbacks).bst_find_index(&2).is_none());
//!
//! // Enumerate the nodes in order
//! let values: Vec<i32> = tree
//!     .read(&callbacks)
//!     .values()
//!     .map(|node| node.0)
//!     .collect();
//! assert_eq!(values, vec![1, 3, 4, 5]);
//! ```
#![warn(missing_docs)]

pub mod accessor;
pub mod accessor_mut;
mod nodes;

pub use nodes::*;

/// Red-black tree header.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Tree<Index = usize> {
    /// The binary tree header.
    pub raw: crate::bintree::Tree<Index>,
}

impl<Index> Default for Tree<Index> {
    #[inline]
    fn default() -> Self {
        Self {
            raw: <_>::default(),
        }
    }
}

impl<Index> Tree<Index> {
    /// Construct an empty tree header.
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    /// Check if the tree is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.raw.is_empty()
    }
}

/// Node color in a red-black tree.
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Color {
    /// Black node.
    ///
    /// The red-black tree invariants require that every path from the root node
    /// to a leaf node contain the same number of black nodes (black height).
    ///
    /// All `None` nodes are considered black.
    #[default]
    Black,
    /// Red node.
    ///
    /// The red-black tree invariants require that a red node not have
    /// a red node child.
    Red,
}

/// Per-node link data stored in a red-black tree element.
///
/// This struct contains all fields used by
/// [`NodesWithMapLink`][]\[[`Mut`][2]\] to implement
/// [`NodesRb`][]\[[`Mut`][1]\].
///
/// [1]: NodesRbMut
/// [2]: NodesWithMapLinkMut
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Link<Index = usize> {
    /// The index of the parent.
    pub parent: Option<Index>,
    /// The index of the left child.
    pub left: Option<Index>,
    /// The index of the right child.
    pub right: Option<Index>,
    /// The color of this node.
    pub color: Color,
}

impl<Index> Link<Index> {
    /// The default value of `Self`.
    pub const DEFAULT: Self = Self {
        parent: None,
        left: None,
        right: None,
        color: Color::Black,
    };
}

impl<Index> Default for Link<Index> {
    #[inline]
    fn default() -> Self {
        Self::DEFAULT
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        bintree::{NodesCmp, NodesCmpKey, NodesLink, NodesLinkMut},
        node_data::{NodesDataLend, NodesDataLendGat, NodesDataLendMut, NodesDataLendMutGat},
    };

    use super::*;
    use core::cmp::Ordering;
    use proptest::prelude::*;
    use std::{prelude::rust_2024::*, rc::Rc};

    #[derive(Default, Debug, Clone, Copy, PartialEq)]
    pub(crate) struct Node<T> {
        pub value: T,
        pub color: Color,
        pub left: Option<usize>,
        pub right: Option<usize>,
        pub parent: Option<usize>,
    }

    impl<T> NodesLink<usize> for [Node<T>] {
        fn node_parent(&self, node: usize) -> Option<usize> {
            self[node].parent
        }

        fn node_left(&self, node: usize) -> Option<usize> {
            self[node].left
        }

        fn node_right(&self, node: usize) -> Option<usize> {
            self[node].right
        }
    }

    impl<T> NodesLinkMut<usize> for [Node<T>] {
        fn set_node_parent(&mut self, node: usize, parent: Option<usize>) {
            self[node].parent = parent;
        }

        fn set_node_left(&mut self, node: usize, left: Option<usize>) {
            self[node].left = left;
        }

        fn set_node_right(&mut self, node: usize, right: Option<usize>) {
            self[node].right = right;
        }
    }

    impl<T> NodesRb<usize> for [Node<T>]
    where
        T: Ord,
    {
        fn node_color(&self, node: usize) -> Color {
            self[node].color
        }
    }

    impl<T> NodesRbMut<usize> for [Node<T>]
    where
        T: Ord,
    {
        fn set_node_color(&mut self, node: usize, color: Color) {
            self[node].color = color;
        }
    }

    impl<T> NodesCmp<usize> for [Node<T>]
    where
        T: Ord,
    {
        fn cmp_nodes(&self, lhs: usize, rhs: usize) -> core::cmp::Ordering {
            Ord::cmp(&self[lhs].value, &self[rhs].value)
        }
    }

    impl<T: Ord> NodesCmpKey<usize, T> for [Node<T>] {
        fn cmp_node_key(&self, node: usize, key: &T) -> Ordering {
            Ord::cmp(&self[node].value, key)
        }
    }

    impl<'this, T> NodesDataLendGat<'this, usize> for [Node<T>] {
        type Data = &'this T;
    }

    impl<T> NodesDataLend<usize> for [Node<T>] {
        fn node_data_lend(&self, node: usize) -> <Self as NodesDataLendGat<'_, usize>>::Data {
            &self[node].value
        }
    }

    impl<'this, T> NodesDataLendMutGat<'this, usize> for [Node<T>] {
        type Data = &'this mut T;
    }

    impl<T> NodesDataLendMut<usize> for [Node<T>] {
        fn node_data_lend_mut(
            &mut self,
            node: usize,
        ) -> <Self as NodesDataLendMutGat<'_, usize>>::Data {
            &mut self[node].value
        }
    }

    /// Construct a proptest strategy producing random red-black BSTs.
    pub(crate) fn any_rbbst(allow_empty: bool) -> impl Strategy<Value = (Vec<Node<u8>>, Tree)> {
        #[derive(Debug, Default)]
        struct INode {
            color: Color,
            left: Option<Box<INode>>,
            right: Option<Box<INode>>,
        }

        ((!allow_empty) as _..=3)
            .prop_flat_map(|depth| {
                let mut cur = Rc::new(((|| None) as fn() -> Option<INode>).boxed());

                for _ in 0..depth {
                    let child = || cur.clone().prop_map(|c| c.map(Box::new));
                    let root = prop_oneof![
                        prop::array::uniform(child()).prop_map(|[left, right]| Some(INode {
                            color: Color::Black,
                            left,
                            right
                        })),
                        prop::array::uniform(child()).prop_map(|[left1, left2, right]| Some(
                            INode {
                                color: Color::Black,
                                left: Some(Box::new(INode {
                                    color: Color::Red,
                                    left: left1,
                                    right: left2
                                })),
                                right
                            }
                        )),
                        prop::array::uniform(child()).prop_map(|[left, right1, right2]| Some(
                            INode {
                                color: Color::Black,
                                left,
                                right: Some(Box::new(INode {
                                    color: Color::Red,
                                    left: right1,
                                    right: right2
                                })),
                            }
                        )),
                        prop::array::uniform(child()).prop_map(|[left1, left2, right1, right2]| {
                            Some(INode {
                                color: Color::Black,
                                left: Some(Box::new(INode {
                                    color: Color::Red,
                                    left: left1,
                                    right: left2,
                                })),
                                right: Some(Box::new(INode {
                                    color: Color::Red,
                                    left: right1,
                                    right: right2,
                                })),
                            })
                        }),
                    ];
                    cur = Rc::new(root.boxed());
                }

                (cur, any::<bool>())
            })
            .prop_map(|(mut root, make_root_red)| {
                // Paint the root red if `make_root_red == true` and it does
                // not violate the tree invariants
                if let Some(root) = &mut root
                    && make_root_red
                    && root.left.as_ref().is_none_or(|n| n.color == Color::Black)
                    && root.right.as_ref().is_none_or(|n| n.color == Color::Black)
                {
                    root.color = Color::Red;
                }

                struct State {
                    next_value: u8,
                    nodes: Vec<Node<u8>>,
                }

                fn convert_node(state: &mut State, node: Option<&INode>) -> Option<usize> {
                    let node = node?;

                    let left = convert_node(state, node.left.as_deref());

                    let value = state.next_value;
                    state.next_value += 1;

                    let right = convert_node(state, node.right.as_deref());

                    let i = state.nodes.len();
                    state.nodes.push(Node {
                        value,
                        color: node.color,
                        left,
                        right,
                        parent: None,
                    });

                    for k in [left, right].into_iter().flatten() {
                        state.nodes[k].parent = Some(i);
                    }

                    Some(i)
                }

                let mut state = State {
                    next_value: 1,
                    nodes: Vec::new(),
                };
                let tree = Tree {
                    raw: crate::bintree::Tree {
                        root: convert_node(&mut state, root.as_ref()),
                    },
                };

                (state.nodes, tree)
            })
    }

    /// Check that [`any_rbbst`] produces valid trees.
    #[proptest::property_test]
    fn pt_any_rbbst_validate(#[strategy = any_rbbst(true)] (nodes, root): (Vec<Node<u8>>, Tree)) {
        root.read(&nodes[..]).validate().unwrap();
        root.read(&nodes[..])
            .bst_validate(|nodes, i| nodes[i])
            .unwrap();
        assert!(root.read(&nodes[..]).values().is_sorted());
    }
}