| 2366 | // A |
| 2367 | #[test] |
| 2368 | fn test_apply_and_visit_references() -> Result<()> { |
| 2369 | let node_a = TestTreeNode::new_leaf("a".to_string()); |
| 2370 | let node_b = TestTreeNode::new_leaf("b".to_string()); |
| 2371 | let node_d = TestTreeNode::new(vec![node_a], "d".to_string()); |
| 2372 | let node_c = TestTreeNode::new(vec![node_b, node_d], "c".to_string()); |
| 2373 | let node_e = TestTreeNode::new(vec![node_c], "e".to_string()); |
| 2374 | let node_a_2 = TestTreeNode::new_leaf("a".to_string()); |
| 2375 | let node_b_2 = TestTreeNode::new_leaf("b".to_string()); |
| 2376 | let node_d_2 = TestTreeNode::new(vec![node_a_2], "d".to_string()); |
| 2377 | let node_c_2 = TestTreeNode::new(vec![node_b_2, node_d_2], "c".to_string()); |
| 2378 | let node_a_3 = TestTreeNode::new_leaf("a".to_string()); |
| 2379 | let tree = TestTreeNode::new(vec![node_e, node_c_2, node_a_3], "f".to_string()); |
| 2380 | |
| 2381 | let node_f_ref = &tree; |
| 2382 | let node_e_ref = &node_f_ref.children[0]; |
| 2383 | let node_c_ref = &node_e_ref.children[0]; |
| 2384 | let node_b_ref = &node_c_ref.children[0]; |
| 2385 | let node_d_ref = &node_c_ref.children[1]; |
| 2386 | let node_a_ref = &node_d_ref.children[0]; |
| 2387 | |
| 2388 | let mut m: HashMap<&TestTreeNode<String>, usize> = HashMap::new(); |
| 2389 | tree.apply(|e| { |
| 2390 | *m.entry(e).or_insert(0) += 1; |
| 2391 | Ok(TreeNodeRecursion::Continue) |
| 2392 | })?; |
| 2393 | |
| 2394 | let expected = HashMap::from([ |
| 2395 | (node_f_ref, 1), |
| 2396 | (node_e_ref, 1), |
| 2397 | (node_c_ref, 2), |
| 2398 | (node_d_ref, 2), |
| 2399 | (node_b_ref, 2), |
| 2400 | (node_a_ref, 3), |
| 2401 | ]); |
| 2402 | assert_eq!(m, expected); |
| 2403 | |
| 2404 | struct TestVisitor<'n> { |
| 2405 | m: HashMap<&'n TestTreeNode<String>, (usize, usize)>, |
| 2406 | } |
| 2407 | |
| 2408 | impl<'n> TreeNodeVisitor<'n> for TestVisitor<'n> { |
| 2409 | type Node = TestTreeNode<String>; |
| 2410 | |
| 2411 | fn f_down(&mut self, node: &'n Self::Node) -> Result<TreeNodeRecursion> { |
| 2412 | let (down_count, _) = self.m.entry(node).or_insert((0, 0)); |
| 2413 | *down_count += 1; |
| 2414 | Ok(TreeNodeRecursion::Continue) |
| 2415 | } |
| 2416 | |
| 2417 | fn f_up(&mut self, node: &'n Self::Node) -> Result<TreeNodeRecursion> { |
| 2418 | let (_, up_count) = self.m.entry(node).or_insert((0, 0)); |
| 2419 | *up_count += 1; |
| 2420 | Ok(TreeNodeRecursion::Continue) |
| 2421 | } |
| 2422 | } |
| 2423 | |
| 2424 | let mut visitor = TestVisitor { m: HashMap::new() }; |
| 2425 | tree.visit(&mut visitor)?; |