graphity_controlflow/loops.rs
1use graphity_core::{BiAdjacentGraph, NONE, SortedIntView, csr};
2
3use crate::dfs_preorder::DfsPreorder;
4use crate::error::check_index;
5use crate::growth;
6
7/// The loop nesting forest of a control-flow graph: its loops, how they nest and where each of them
8/// is entered, irreducible loops included.
9///
10/// A loop has a header, through which it is normally entered, and a body: the header, the other nodes
11/// of the loop and those of the loops nested in it. [`Loops::of`] finds the loops from the entry of
12/// the graph - here, the loop of a method `load` around its block `then`, from its control flow `cfg`
13/// and its entry block `entry`:
14///
15/// <!-- example: analyzing_control_flow.rs#loops -->
16/// ```
17/// # use graphity_core::BiAdjacentGraph;
18/// # use graphity_controlflow::Loops;
19/// # let cfg = graphity_core::Graph::of(&[0, 1, 3, 5, 6, 7, 7], &[1, 2, 5, 3, 4, 4, 1]).unwrap();
20/// # let (entry, then) = (0, 3);
21/// // The basic blocks of load are the nodes 0 to 5 of cfg: entry, header, body, then,
22/// // next, exit.
23///
24/// // Find the loops of load, from its entry block.
25/// let loops = Loops::of(&BiAdjacentGraph::of(&cfg), entry);
26///
27/// // Find the loop around the block then, with its header and its body.
28///
29/// // 0 - the for loop, the only loop
30/// let loop_id = loops.innermost_loop_of(then).unwrap();
31/// let header = loops.header_of(loop_id); // 1 - the block header
32/// let blocks = loops.body_of(loop_id); // [1, 2, 3, 4] - header, body, then and next
33/// # assert_eq!(loops.loop_count(), 1);
34/// # assert_eq!((loop_id, header), (0, 1));
35/// # assert_eq!(blocks, [1, 2, 3, 4]);
36/// ```
37///
38/// The forest is defined on every graph, reducible or not, over the nodes that the entries reach:
39///
40/// - The outermost loops are the [strongly connected components](graphity_core::Sccs) that contain
41/// at least one edge.
42/// - The header of a loop is the node of its component that a depth-first search from the entries
43/// reaches first. The search takes the entries in list order and the out-nodes of a node in
44/// ascending order.
45/// - Without the edges that lead into the header from inside the component, the rest of it breaks up
46/// into the nested loops, by the same rule.
47///
48/// Uses Havlak's algorithm, without recursion. On a reducible graph, the loops are the natural loops.
49/// An irreducible loop is a cycle that can be entered at more than one node, as `goto`, bytecode or
50/// generated state machines produce it. It is one loop with several [entries](Self::entries_of), and
51/// which of them is the header depends on the order of the search. An entry of the graph that lies in
52/// a loop is an entry of that loop. A node with a self-loop is the header of a loop of its own, unless
53/// it already is the header of a larger one. Nodes that no entry reaches are in no loop.
54///
55/// Loops have IDs `0..loop_count()`, in preorder of the forest: a loop has a smaller ID than the
56/// loops nested in it, which follow it as one range of IDs. Going through the IDs downwards visits the
57/// inner loops first.
58///
59/// Like [`Dominators`](graphity_core::Dominators), the analysis follows edges against their direction
60/// and so takes a [`BiAdjacentGraph`]; the same graph serves both. Instances are immutable and safe to
61/// share between threads (`Send` and `Sync`).
62///
63/// **Memory:** 4 x node_count bytes, plus 4 bytes per node in a loop, 24 bytes per loop and 4 bytes
64/// per entry of a loop.
65#[derive(Debug, Clone)]
66pub struct Loops {
67 /// Innermost loop of each node, [`NONE`] outside every loop.
68 innermost_loop: Box<[u32]>,
69 /// Header node of each loop.
70 header: Box<[u32]>,
71 /// Enclosing loop of each loop, [`NONE`] at the top level.
72 parent: Box<[u32]>,
73 /// One past the last loop nested in each loop: the loops in `L` are `[L, subtree_end[L])`.
74 subtree_end: Box<[u32]>,
75 /// Number of loops containing each loop, itself included.
76 depth: Box<[u32]>,
77 /// Start of each loop's own nodes in `bodies`; the body of `L` with its nested loops is
78 /// `[body_start[L], body_start[subtree_end[L]])`.
79 body_start: Box<[u32]>,
80 /// All loop bodies in loop-ID order, each loop's own nodes header first, then ascending.
81 bodies: Box<[u32]>,
82 /// Entries of each loop as CSR offsets into `entries`, each list ascending.
83 entry_start: Box<[u32]>,
84 entries: Box<[u32]>,
85 reducible: bool,
86}
87
88impl Loops {
89 /// Returns the loop nesting forest of `graph` with one entry. Equivalent to
90 /// [`of_entries(graph, &[entry])`](Self::of_entries) - Java's overload `of(BiAdjacentGraph, int)`.
91 ///
92 /// **Time:** as for [`of_entries`](Self::of_entries).
93 /// **Memory:** as for [`of_entries`](Self::of_entries).
94 ///
95 /// # Panics
96 /// With an `index out of bounds` message if `entry` is not in `0..node_count`; with an
97 /// `invalid argument` message if `graph` has more than `2^30 - 6` nodes.
98 #[track_caller]
99 pub fn of(graph: &BiAdjacentGraph, entry: u32) -> Loops {
100 Self::of_entries(graph, &[entry])
101 }
102
103 /// Returns the loop nesting forest of `graph` with the given entries - Java's overload
104 /// `of(BiAdjacentGraph, IntList)`.
105 ///
106 /// The entries work as in [`Dominators::of_entries`](graphity_core::Dominators::of_entries): an entry
107 /// given twice counts once, and with no entries, no node is reachable, so there is no loop. Their
108 /// order matters here: it decides which node of an irreducible loop the search reaches first, and so
109 /// which node is its header.
110 ///
111 /// **Time:** O(entries.len() + (node_count + edge_count) log node_count) on a reducible graph. On an
112 /// irreducible graph, an edge costs one more step for every loop it enters other than through the
113 /// header.
114 /// **Memory:** the result, as given in the type documentation; while it runs, about
115 /// 45 x node_count + 4 x edge_count bytes more, plus 28 bytes per loop and 12 bytes per entry of a
116 /// loop.
117 ///
118 /// # Panics
119 /// With an `index out of bounds` message if an entry is not in `0..node_count`; with an
120 /// `invalid argument` message if `graph` has more than `2^30 - 6` nodes.
121 #[track_caller]
122 pub fn of_entries(graph: &BiAdjacentGraph, entries: &[u32]) -> Loops {
123 let n = graph.node_count() as usize;
124 let dfs = DfsPreorder::of(graph, entries, "Loops");
125 let size = dfs.reached_count as usize + 1;
126 let order = &dfs.order;
127 let number = &dfs.preorder_number;
128
129 // 1) Last preorder number in each search subtree: v's subtree is [v, last[v]].
130 let mut last: Vec<u32> = (0..size as u32).collect();
131 for v in (1..size).rev() {
132 let p = dfs.parent[v] as usize;
133 if p > 0 && last[v] > last[p] {
134 last[p] = last[v];
135 }
136 }
137
138 // Predecessors from the in-adjacency over node IDs, translated per edge through `number`
139 // (0 = unreachable).
140 let pred_start = csr::in_adjacency_start(graph);
141 let preds = csr::in_adjacency(graph);
142
143 // 2) Headers in reverse preorder, inner before outer. The body of w is the part of its
144 // search subtree that reaches w inside that subtree. Union-find collapses finished
145 // loops into their header; the edges that enter a collapsed region from outside wait in
146 // a linked list per region, so an enclosing header scans each of them once instead of
147 // rescanning every predecessor of every node inside.
148 let mut uf: Vec<u32> = (0..size as u32).collect();
149 let mut enclosing = vec![0u32; size];
150 let mut mark = vec![0u32; size];
151 let mut pending = PendingLists::new(size, preds.len());
152 let mut stack = vec![0u32; size];
153 let mut body = vec![0u32; size];
154 let mut is_header = vec![false; size];
155 let mut loop_count = 0usize;
156
157 for w in (1..size).rev() {
158 let w32 = w as u32;
159 let last_w = last[w];
160 let mut self_loop = false;
161 let mut top = 0usize;
162 let node = order[w] as usize;
163 for i in pred_start[node] as usize..pred_start[node + 1] as usize {
164 let v = number[preds[i] as usize];
165 if v == 0 {
166 continue;
167 }
168 if v >= w32 && v <= last_w {
169 if v == w32 {
170 self_loop = true;
171 } else {
172 let r = find(&mut uf, v);
173 if mark[r as usize] != w32 {
174 mark[r as usize] = w32;
175 stack[top] = r;
176 top += 1;
177 }
178 }
179 } else {
180 pending.append(w, i as u32);
181 }
182 }
183 if top == 0 && !self_loop {
184 continue;
185 }
186
187 is_header[w] = true;
188 loop_count += 1;
189 let mut body_count = 0usize;
190 while top > 0 {
191 top -= 1;
192 let x = stack[top] as usize;
193 body[body_count] = x as u32;
194 body_count += 1;
195 let mut i = pending.take(x);
196 while i != NONE {
197 let next = pending.next[i as usize];
198 let r = find(&mut uf, number[preds[i as usize] as usize]);
199 if r >= w32 && r <= last_w {
200 if r != w32 && mark[r as usize] != w32 {
201 mark[r as usize] = w32;
202 stack[top] = r;
203 top += 1;
204 }
205 } else {
206 pending.append(w, i);
207 }
208 i = next;
209 }
210 }
211 for &b in &body[..body_count] {
212 uf[b as usize] = w32;
213 enclosing[b as usize] = w32;
214 }
215 }
216
217 // 3) Loop IDs in preorder of the forest; siblings by the preorder of their headers.
218 // The child lists and the walk are parent_forest::group_counted and parent_forest::preorder
219 // of the core, which this crate cannot call; change them together.
220 // mark and stack are free now: mark maps each header to its index, stack walks the forest.
221 let mut loop_index = mark;
222 loop_index.fill(NONE);
223 let mut index_header = vec![0u32; loop_count];
224 let mut k = 0usize;
225 for v in 1..size {
226 if is_header[v] {
227 loop_index[v] = k as u32;
228 index_header[k] = v as u32;
229 k += 1;
230 }
231 }
232 let mut child_start = vec![0u32; loop_count + 1];
233 let mut index_parent = vec![NONE; loop_count];
234 for i in 0..loop_count {
235 let e = enclosing[index_header[i] as usize];
236 if e != 0 {
237 index_parent[i] = loop_index[e as usize];
238 child_start[index_parent[i] as usize] += 1;
239 }
240 }
241 let mut next_child_start = 0u32;
242 for start in &mut child_start[..loop_count] {
243 let count = *start;
244 *start = next_child_start;
245 next_child_start += count;
246 }
247 child_start[loop_count] = next_child_start;
248 let mut children = vec![0u32; next_child_start as usize];
249 // child_start[p] doubles as write pointer and is shifted back afterwards.
250 for (i, &p) in index_parent.iter().enumerate() {
251 if p != NONE {
252 children[child_start[p as usize] as usize] = i as u32;
253 child_start[p as usize] += 1;
254 }
255 }
256 child_start.copy_within(0..loop_count, 1);
257 child_start[0] = 0;
258
259 let mut id_of_index = vec![0u32; loop_count];
260 let mut header = vec![0u32; loop_count];
261 let mut parent = vec![NONE; loop_count];
262 let mut depth = vec![0u32; loop_count];
263 let mut subtree_end = vec![0u32; loop_count];
264 let mut id = 0usize;
265 let mut top = 0usize;
266 for i in (0..loop_count).rev() {
267 if index_parent[i] == NONE {
268 stack[top] = i as u32;
269 top += 1;
270 }
271 }
272 while top > 0 {
273 top -= 1;
274 let i = stack[top] as usize;
275 id_of_index[i] = id as u32;
276 header[id] = order[index_header[i] as usize];
277 if index_parent[i] != NONE {
278 parent[id] = id_of_index[index_parent[i] as usize];
279 }
280 depth[id] = if parent[id] == NONE {
281 1
282 } else {
283 depth[parent[id] as usize] + 1
284 };
285 id += 1;
286 for c in (child_start[i] as usize..child_start[i + 1] as usize).rev() {
287 stack[top] = children[c];
288 top += 1;
289 }
290 }
291 for (l, end) in subtree_end.iter_mut().enumerate() {
292 *end = l as u32 + 1;
293 }
294 for l in (0..loop_count).rev() {
295 let p = parent[l];
296 if p != NONE && subtree_end[l] > subtree_end[p as usize] {
297 subtree_end[p as usize] = subtree_end[l];
298 }
299 }
300
301 // 4) Innermost loop per node: its own loop for a header, else the loop that collapsed it.
302 let mut innermost_loop = vec![NONE; n];
303 for v in 1..size {
304 let h = if is_header[v] { v as u32 } else { enclosing[v] };
305 if h != 0 {
306 innermost_loop[order[v] as usize] = id_of_index[loop_index[h as usize] as usize];
307 }
308 }
309
310 // 5) Bodies: each loop's own nodes, header first, then ascending; loops in ID order, so
311 // the nested loops of L follow its own nodes and the whole body is one slice.
312 let mut body_start = vec![0u32; loop_count + 1];
313 for &l in &innermost_loop {
314 if l != NONE {
315 body_start[l as usize] += 1;
316 }
317 }
318 let mut next_body_start = 0u32;
319 for start in &mut body_start[..loop_count] {
320 let count = *start;
321 *start = next_body_start;
322 next_body_start += count;
323 }
324 body_start[loop_count] = next_body_start;
325 let mut bodies = vec![0u32; next_body_start as usize];
326 let mut body_write_pos = body_start[..loop_count].to_vec();
327 for (l, &h) in header.iter().enumerate() {
328 bodies[body_write_pos[l] as usize] = h;
329 body_write_pos[l] += 1;
330 }
331 for (node, &l) in innermost_loop.iter().enumerate() {
332 if l != NONE && header[l as usize] != node as u32 {
333 bodies[body_write_pos[l as usize] as usize] = node as u32;
334 body_write_pos[l as usize] += 1;
335 }
336 }
337
338 // 6) Entries: x enters every loop that contains x but not one of its predecessors - a
339 // chain from the innermost loop of x upwards. Walking each chain only above the part
340 // already marked keeps this proportional to the result. A graph entry has the virtual
341 // root as predecessor, which no loop contains.
342 let mut entry_loops: Vec<u32> = Vec::new();
343 let mut entry_nodes: Vec<u32> = Vec::new();
344 for x in 0..n {
345 let lx = innermost_loop[x];
346 if lx == NONE {
347 continue;
348 }
349 let v = number[x];
350 let mut marked = NONE;
351 if dfs.is_entry(v) {
352 let mut l = lx;
353 while l != NONE {
354 growth::push(&mut entry_loops, l);
355 growth::push(&mut entry_nodes, x as u32);
356 l = parent[l as usize];
357 }
358 continue;
359 }
360 for &y in &preds[pred_start[x] as usize..pred_start[x + 1] as usize] {
361 if number[y as usize] == 0 {
362 continue;
363 }
364 let ly = innermost_loop[y as usize];
365 let mut l = if marked == NONE {
366 lx
367 } else if contains(&subtree_end, marked, ly) {
368 continue;
369 } else {
370 parent[marked as usize]
371 };
372 while l != NONE && !contains(&subtree_end, l, ly) {
373 growth::push(&mut entry_loops, l);
374 growth::push(&mut entry_nodes, x as u32);
375 marked = l;
376 l = parent[l as usize];
377 }
378 }
379 }
380 let mut entry_start = vec![0u32; loop_count + 1];
381 for &l in &entry_loops {
382 entry_start[l as usize] += 1;
383 }
384 let mut next_entry_start = 0u32;
385 let mut reducible = true;
386 for start in &mut entry_start[..loop_count] {
387 let count = *start;
388 if count != 1 {
389 reducible = false;
390 }
391 *start = next_entry_start;
392 next_entry_start += count;
393 }
394 entry_start[loop_count] = next_entry_start;
395 let mut loop_entries = vec![0u32; next_entry_start as usize];
396 let mut entry_write_pos = entry_start[..loop_count].to_vec();
397 for (&l, &x) in entry_loops.iter().zip(&entry_nodes) {
398 loop_entries[entry_write_pos[l as usize] as usize] = x;
399 entry_write_pos[l as usize] += 1;
400 }
401
402 Loops {
403 innermost_loop: innermost_loop.into(),
404 header: header.into(),
405 parent: parent.into(),
406 subtree_end: subtree_end.into(),
407 depth: depth.into(),
408 body_start: body_start.into(),
409 bodies: bodies.into(),
410 entry_start: entry_start.into(),
411 entries: loop_entries.into(),
412 reducible,
413 }
414 }
415
416 /// Returns the number of loops.
417 ///
418 /// **Time:** O(1).
419 #[inline]
420 pub fn loop_count(&self) -> u32 {
421 self.header.len() as u32
422 }
423
424 /// Returns whether the graph is reducible: whether every loop has its header as its only entry.
425 ///
426 /// The loops of a reducible graph are its natural loops. A node counts only if the entries reach it.
427 ///
428 /// **Time:** O(1).
429 #[inline]
430 pub fn is_reducible(&self) -> bool {
431 self.reducible
432 }
433
434 /// Returns the innermost loop that contains `node`, or `None` if it lies in no loop - Java's `-1`.
435 ///
436 /// **Time:** O(1).
437 ///
438 /// # Panics
439 /// With an `index out of bounds` message if `node` is not in `0..node_count`.
440 #[inline]
441 #[track_caller]
442 pub fn innermost_loop_of(&self, node: u32) -> Option<u32> {
443 check_index(node, self.innermost_loop.len());
444 let l = self.innermost_loop[node as usize];
445 (l != NONE).then_some(l)
446 }
447
448 /// Returns the loop depth of `node`: the number of loops that contain it. A node in no loop has loop
449 /// depth `0`.
450 ///
451 /// **Time:** O(1).
452 ///
453 /// # Panics
454 /// With an `index out of bounds` message if `node` is not in `0..node_count`.
455 #[inline]
456 #[track_caller]
457 pub fn loop_depth_of(&self, node: u32) -> u32 {
458 check_index(node, self.innermost_loop.len());
459 let l = self.innermost_loop[node as usize];
460 if l == NONE { 0 } else { self.depth[l as usize] }
461 }
462
463 /// Returns whether `node` lies in loop `loop_id`, directly or in a loop nested in it. The parameter is
464 /// Java's `loop`, which is a keyword in Rust.
465 ///
466 /// **Time:** O(1).
467 ///
468 /// # Panics
469 /// With an `index out of bounds` message if `node` is not in `0..node_count` or `loop_id` not in
470 /// `0..loop_count()`.
471 #[inline]
472 #[track_caller]
473 pub fn is_in_loop(&self, node: u32, loop_id: u32) -> bool {
474 check_index(node, self.innermost_loop.len());
475 check_index(loop_id, self.header.len());
476 contains(
477 &self.subtree_end,
478 loop_id,
479 self.innermost_loop[node as usize],
480 )
481 }
482
483 /// Returns the header of loop `loop_id`.
484 ///
485 /// **Time:** O(1).
486 ///
487 /// # Panics
488 /// With an `index out of bounds` message if `loop_id` is not in `0..loop_count()`.
489 #[inline]
490 #[track_caller]
491 pub fn header_of(&self, loop_id: u32) -> u32 {
492 check_index(loop_id, self.header.len());
493 self.header[loop_id as usize]
494 }
495
496 /// Returns the entries of loop `loop_id`, in ascending order.
497 ///
498 /// These are the nodes of the loop with an in-node outside the loop, and the entries of the graph that
499 /// lie in the loop. An in-node counts only if the entries of the graph reach it. A loop that can only
500 /// be entered through its header has the header as its only entry.
501 ///
502 /// The result is a view of this forest's own array, not a copy.
503 ///
504 /// **Time:** O(entries_of(loop_id).len()).
505 ///
506 /// # Panics
507 /// With an `index out of bounds` message if `loop_id` is not in `0..loop_count()`.
508 #[track_caller]
509 pub fn entries_of(&self, loop_id: u32) -> SortedIntView<'_> {
510 check_index(loop_id, self.header.len());
511 let l = loop_id as usize;
512 SortedIntView::view_of(
513 &self.entries,
514 self.entry_start[l] as usize,
515 self.entry_start[l + 1] as usize,
516 )
517 .expect("the entries of a loop are strictly ascending")
518 }
519
520 /// Returns the loop that immediately encloses loop `loop_id`, or `None` for an outermost loop - Java's
521 /// `-1`.
522 ///
523 /// **Time:** O(1).
524 ///
525 /// # Panics
526 /// With an `index out of bounds` message if `loop_id` is not in `0..loop_count()`.
527 #[inline]
528 #[track_caller]
529 pub fn parent_of(&self, loop_id: u32) -> Option<u32> {
530 check_index(loop_id, self.header.len());
531 let p = self.parent[loop_id as usize];
532 (p != NONE).then_some(p)
533 }
534
535 /// Returns the body of loop `loop_id`: its nodes and those of the loops nested in it.
536 ///
537 /// The nodes come in this order: first the header, then, in ascending order, the other nodes whose
538 /// innermost loop is `loop_id`, then the nodes of the nested loops in the same form, loop after loop
539 /// in ID order.
540 ///
541 /// The result is a view of this forest's own array, not a copy, and cannot be written - Java returns
542 /// an unmodifiable `IntList` view. All bodies share the array, so a node is stored once, however
543 /// deeply its loop is nested.
544 ///
545 /// ```compile_fail
546 /// # use graphity_core::{BiAdjacentGraph, GraphBuilder};
547 /// # use graphity_controlflow::Loops;
548 /// # let mut b = GraphBuilder::new();
549 /// # b.add_nodes(3);
550 /// # b.add_edge_pairs(&[0, 1, 1, 2, 2, 1]);
551 /// let loops = Loops::of(&BiAdjacentGraph::of(&b.build()), 0);
552 /// loops.body_of(0)[0] = 1; // a shared slice cannot be written
553 /// ```
554 ///
555 /// **Time:** O(1).
556 ///
557 /// # Panics
558 /// With an `index out of bounds` message if `loop_id` is not in `0..loop_count()`.
559 #[inline]
560 #[track_caller]
561 pub fn body_of(&self, loop_id: u32) -> &[u32] {
562 check_index(loop_id, self.header.len());
563 let l = loop_id as usize;
564 let end = self.subtree_end[l] as usize;
565 &self.bodies[self.body_start[l] as usize..self.body_start[end] as usize]
566 }
567}
568
569/// Whether the loop `inner`, [`NONE`] for none, is `loop_id` or nested in it. [`NONE`] lies above
570/// every `subtree_end`, so it is in no loop, as `-1` is below every loop ID in Java.
571#[inline]
572fn contains(subtree_end: &[u32], loop_id: u32, inner: u32) -> bool {
573 inner >= loop_id && inner < subtree_end[loop_id as usize]
574}
575
576/// Union-find root of `x`, with full path compression in a second pass.
577fn find(uf: &mut [u32], mut x: u32) -> u32 {
578 let mut root = x;
579 while uf[root as usize] != root {
580 root = uf[root as usize];
581 }
582 while uf[x as usize] != root {
583 let up = uf[x as usize];
584 uf[x as usize] = root;
585 x = up;
586 }
587 root
588}
589
590/// The edges that wait for an enclosing header, as singly linked lists over in-adjacency
591/// positions: one list per preorder number, with head and tail, [`NONE`] for none.
592struct PendingLists {
593 head: Vec<u32>,
594 tail: Vec<u32>,
595 next: Vec<u32>,
596}
597
598impl PendingLists {
599 fn new(lists: usize, items: usize) -> Self {
600 Self {
601 head: vec![NONE; lists],
602 tail: vec![NONE; lists],
603 next: vec![0; items],
604 }
605 }
606
607 /// Appends `item` to the list `list`.
608 #[inline]
609 fn append(&mut self, list: usize, item: u32) {
610 self.next[item as usize] = NONE;
611 match self.tail[list] {
612 NONE => self.head[list] = item,
613 tail => self.next[tail as usize] = item,
614 }
615 self.tail[list] = item;
616 }
617
618 /// Empties the list `list` and returns its first item, from which `next` leads through the
619 /// rest.
620 #[inline]
621 fn take(&mut self, list: usize) -> u32 {
622 let first = self.head[list];
623 self.head[list] = NONE;
624 self.tail[list] = NONE;
625 first
626 }
627}
628
629#[cfg(test)]
630mod tests {
631 use super::*;
632
633 #[test]
634 fn find_compresses_the_whole_path() {
635 let mut uf = vec![0, 0, 1, 2, 3];
636 assert_eq!(find(&mut uf, 4), 0);
637 assert_eq!(uf, [0, 0, 0, 0, 0]);
638 }
639
640 #[test]
641 fn pending_lists_keep_their_order_and_empty_on_take() {
642 let mut lists = PendingLists::new(2, 4);
643 lists.append(1, 2);
644 lists.append(1, 0);
645 lists.append(0, 3);
646 lists.append(1, 1);
647 let mut items = Vec::new();
648 let mut i = lists.take(1);
649 while i != NONE {
650 items.push(i);
651 i = lists.next[i as usize];
652 }
653 assert_eq!(items, [2, 0, 1]);
654 assert_eq!(lists.take(1), NONE);
655 assert_eq!(lists.take(0), 3);
656 }
657
658 #[test]
659 fn contains_is_a_range_test_that_rejects_none() {
660 // Loop 0 encloses 1 and 2, loop 3 stands alone.
661 let subtree_end = [3, 2, 3, 4];
662 assert!(contains(&subtree_end, 0, 0));
663 assert!(contains(&subtree_end, 0, 2));
664 assert!(!contains(&subtree_end, 0, 3));
665 assert!(!contains(&subtree_end, 1, 2));
666 assert!(!contains(&subtree_end, 0, NONE));
667 }
668}