]> git.proxmox.com Git - pxar.git/blame - src/binary_tree_array.rs
make the ReadAtImpl enum variants private
[pxar.git] / src / binary_tree_array.rs
CommitLineData
fbddffdc
WB
1//! Helpers to generate a binary search tree stored in an array from a
2//! sorted array.
3//!
4//! Specifically, for any given sorted array 'input' permute the
5//! array so that the following rule holds:
6//!
7//! For each array item with index i, the item at 2i+1 is smaller and
8//! the item 2i+2 is larger.
9//!
10//! This structure permits efficient (meaning: O(log(n)) binary
11//! searches: start with item i=0 (i.e. the root of the BST), compare
12//! the value with the searched item, if smaller proceed at item
13//! 2i+1, if larger proceed at item 2i+2, and repeat, until either
14//! the item is found, or the indexes grow beyond the array size,
15//! which means the entry does not exist.
16//!
17//! Effectively this implements bisection, but instead of jumping
18//! around wildly in the array during a single search we only search
19//! with strictly monotonically increasing indexes.
20//!
21//! Algorithm is from casync (camakebst.c), simplified and optimized
22//! for rust. Permutation function originally by L. Bressel, 2017. We
23//! pass permutation info to user provided callback, which actually
24//! implements the data copy.
25//!
26//! The Wikipedia Artikel for [Binary
27//! Heap](https://en.wikipedia.org/wiki/Binary_heap) gives a short
28//! intro howto store binary trees using an array.
29
30use std::cmp::Ordering;
31
32#[allow(clippy::many_single_char_names)]
33fn copy_inner<F: FnMut(usize, usize)>(
34 copy_func: &mut F,
35 // we work on input array input[o..o+n]
36 n: usize,
37 o: usize,
38 e: usize,
39 i: usize,
40) {
41 let p = 1 << e;
42
43 let t = p + (p >> 1) - 1;
44
45 let m = if n > t {
46 // |...........p.............t....n........(2p)|
47 p - 1
48 } else {
49 // |...........p.....n.......t.............(2p)|
50 p - 1 - (t - n)
51 };
52
53 (copy_func)(o + m, i);
54
55 if m > 0 {
56 copy_inner(copy_func, m, o, e - 1, i * 2 + 1);
57 }
58
59 if (m + 1) < n {
60 copy_inner(copy_func, n - m - 1, o + m + 1, e - 1, i * 2 + 2);
61 }
62}
63
64/// This function calls the provided `copy_func()` with the permutaion information required to
65/// build a binary search tree array.
66///
67/// ```
68/// # use pxar::binary_tree_array;
69/// # let mut i = 0;
70/// # const EXPECTED: &[(usize, usize)] = &[(3, 0), (1, 1), (0, 3), (2, 4), (4, 2)];
71/// binary_tree_array::copy(5, |src, dest| {
72/// # assert_eq!((src, dest), EXPECTED[i]);
73/// # i += 1;
74/// println!("Copy {} to {}", src, dest);
75/// });
76/// ```
77///
78/// This will produce the folowing output:
79///
80/// ```no-compile
81/// Copy 3 to 0
82/// Copy 1 to 1
83/// Copy 0 to 3
84/// Copy 2 to 4
85/// Copy 4 to 2
86/// ```
87///
88/// So this generates the following permuation: `[3,1,4,0,2]`.
89pub fn copy<F>(n: usize, mut copy_func: F)
90where
91 F: FnMut(usize, usize),
92{
93 if n == 0 {
94 return;
95 };
96
97 let e = (64 - n.leading_zeros() - 1) as usize; // fast log2(n)
98
99 copy_inner(&mut copy_func, n, 0, e, 0);
100}
101
102/// This function searches for the index where the comparison by the provided
103/// `compare()` function returns `Ordering::Equal`.
104/// The order of the comparison matters (noncommutative) and should be search
105/// value compared to value at given index as shown in the examples.
106/// The parameter `skip` defines the number of matches to ignore while
107/// searching before returning the index in order to lookup duplicate entries in
108/// the tree.
109///
110/// ```
111/// # use pxar::binary_tree_array;
112/// let mut vals = vec![0,1,2,2,2,3,4,5,6,6,7,8,8,8];
113///
114/// let clone = vals.clone();
115/// binary_tree_array::copy(vals.len(), |s, d| {
116/// vals[d] = clone[s];
117/// });
118/// let should_be = vec![5,2,8,1,3,6,8,0,2,2,4,6,7,8];
119/// assert_eq!(vals, should_be);
120///
121/// let find = 8;
122/// let skip = 0;
123/// let idx = binary_tree_array::search_by(&vals, 0, skip, |el| find.cmp(el));
124/// assert_eq!(idx, Some(2));
125///
126/// let find = 8;
127/// let skip = 1;
128/// let idx = binary_tree_array::search_by(&vals, 2, skip, |el| find.cmp(el));
129/// assert_eq!(idx, Some(6));
130///
131/// let find = 8;
132/// let skip = 1;
133/// let idx = binary_tree_array::search_by(&vals, 6, skip, |el| find.cmp(el));
134/// assert_eq!(idx, Some(13));
135///
136/// let find = 5;
137/// let skip = 1;
138/// let idx = binary_tree_array::search_by(&vals, 0, skip, |el| find.cmp(el));
139/// assert!(idx.is_none());
140///
141/// let find = 5;
142/// let skip = 0;
143/// // if start index is equal to the array length, `None` is returned.
144/// let idx = binary_tree_array::search_by(&vals, vals.len(), skip, |el| find.cmp(el));
145/// assert!(idx.is_none());
146///
147/// // if start index is larger than length, `None` is returned.
148/// let idx = binary_tree_array::search_by(&vals, vals.len() + 1, skip, |el| find.cmp(el));
149/// assert!(idx.is_none());
150/// ```
151pub fn search_by<F, T>(tree: &[T], start: usize, skip: usize, f: F) -> Option<usize>
152where
153 F: Copy + Fn(&T) -> Ordering,
154{
155 let mut i = start;
156
157 while i < tree.len() {
158 match f(&tree[i]) {
159 Ordering::Less => i = 2 * i + 1,
160 Ordering::Greater => i = 2 * i + 2,
161 Ordering::Equal if skip == 0 => return Some(i),
162 Ordering::Equal => {
163 i = 2 * i + 1;
164 return search_by(tree, i, skip - 1, f)
165 .or_else(move || search_by(tree, i + 1, skip - 1, f));
166 }
167 }
168 }
169
170 None
171}
172
173#[test]
174fn test_binary_search_tree() {
175 fn run_test(len: usize) -> Vec<usize> {
176 const MARKER: usize = 0xfffffff;
177 let mut output = vec![];
178 for _i in 0..len {
179 output.push(MARKER);
180 }
181 copy(len, |s, d| {
182 assert!(output[d] == MARKER);
183 output[d] = s;
184 });
185 if len < 32 {
186 println!("GOT:{}:{:?}", len, output);
187 }
188 for i in 0..len {
189 assert!(output[i] != MARKER);
190 }
191 output
192 }
193
194 assert!(run_test(0).len() == 0);
195 assert!(run_test(1) == [0]);
196 assert!(run_test(2) == [1, 0]);
197 assert!(run_test(3) == [1, 0, 2]);
198 assert!(run_test(4) == [2, 1, 3, 0]);
199 assert!(run_test(5) == [3, 1, 4, 0, 2]);
200 assert!(run_test(6) == [3, 1, 5, 0, 2, 4]);
201 assert!(run_test(7) == [3, 1, 5, 0, 2, 4, 6]);
202 assert!(run_test(8) == [4, 2, 6, 1, 3, 5, 7, 0]);
203 assert!(run_test(9) == [5, 3, 7, 1, 4, 6, 8, 0, 2]);
204 assert!(run_test(10) == [6, 3, 8, 1, 5, 7, 9, 0, 2, 4]);
205 assert!(run_test(11) == [7, 3, 9, 1, 5, 8, 10, 0, 2, 4, 6]);
206 assert!(run_test(12) == [7, 3, 10, 1, 5, 9, 11, 0, 2, 4, 6, 8]);
207 assert!(run_test(13) == [7, 3, 11, 1, 5, 9, 12, 0, 2, 4, 6, 8, 10]);
208 assert!(run_test(14) == [7, 3, 11, 1, 5, 9, 13, 0, 2, 4, 6, 8, 10, 12]);
209 assert!(run_test(15) == [7, 3, 11, 1, 5, 9, 13, 0, 2, 4, 6, 8, 10, 12, 14]);
210 assert!(run_test(16) == [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15, 0]);
211 assert!(run_test(17) == [9, 5, 13, 3, 7, 11, 15, 1, 4, 6, 8, 10, 12, 14, 16, 0, 2]);
212
213 for len in 18..1000 {
214 run_test(len);
215 }
216}