data_tree/
lib.rs

1//
2// Libraries
3//
4use std::collections::HashMap;
5use std::fmt::Debug;
6use std::ptr::eq;
7
8use serde::{Deserialize, Serialize};
9//
10// Tests
11//
12#[cfg(test)]
13mod test {
14    use super::*;
15    use std::ptr::eq;
16
17    struct ExampleTree {}
18    impl ExampleTree {
19        pub fn get_node_root_of_tree_new() -> Node {
20            let mut node_root = Node::new();
21
22            let slice_of_paths: [Box<[&str]>; 7] = [
23                Box::new(["a0"]),
24                Box::new(["b0", "b1", "b2", "b3"]),
25                Box::new(["c0", "ca1", "ca2", "ca3", "ca4", "ca5"]),
26                Box::new(["c0", "cb1", "cb2", "cb3", "cc4", "cd5"]),
27                Box::new([
28                    "d0", "da1", "da2", "da3", "da4", "da5", "da6", "da7", "da8", "da9",
29                ]),
30                Box::new([
31                    "d0", "da1", "da2", "db3", "db4", "db5", "db6", "db7", "db8", "db9",
32                ]),
33                Box::new([
34                    "d0", "da1", "da2", "db3", "db4", "db5", "dc6", "dc7", "dd8", "dd9",
35                ]),
36            ];
37
38            for item_path in slice_of_paths {
39                let mut item_node_child = Node::new();
40
41                let item_string_data = ExampleTree::get_string_test_data_via_path(&item_path);
42
43                item_node_child.field_string_data = item_string_data;
44
45                match node_root.insert_node_at_path(&item_path, item_node_child) {
46                    Ok(()) => {}
47                    Err(err) => panic!("{}", err),
48                };
49            }
50            node_root
51        }
52
53        /*
54        // Returns a vec of known paths within the generic complex tree
55        pub fn get_vec_of_paths_expected() -> Vec<Vec<String>> {
56            let slice_of_paths: [Box<[&str]>; 37] = [
57                Box::new( [ "a0" ] ),
58                Box::new( [ "b0" ] ),
59                Box::new( [ "b0", "b1" ] ),
60                Box::new( [ "b0", "b1", "b2" ] ),
61                Box::new( [ "b0", "b1", "b2", "b3" ] ),
62                Box::new( [ "c0" ] ),
63                Box::new( [ "c0", "ca1" ] ),
64                Box::new( [ "c0", "ca1", "ca2" ] ),
65                Box::new( [ "c0", "ca1", "ca2", "ca3" ] ),
66                Box::new( [ "c0", "ca1", "ca2", "ca3", "ca4" ] ),
67                Box::new( [ "c0", "ca1", "ca2", "ca3", "ca4", "ca5" ] ),
68                Box::new( [ "c0", "cb1" ] ),
69                Box::new( [ "c0", "cb1", "cb2" ] ),
70                Box::new( [ "c0", "cb1", "cb2", "cb3" ] ),
71                Box::new( [ "c0", "cb1", "cb2", "cb3", "cc4" ] ),
72                Box::new( [ "c0", "cb1", "cb2", "cb3", "cc4", "cd5" ] ),
73                Box::new( [ "d0" ] ),
74                Box::new( [ "d0", "da1" ] ),
75                Box::new( [ "d0", "da1", "da2" ] ),
76                Box::new( [ "d0", "da1", "da2", "da3" ] ),
77                Box::new( [ "d0", "da1", "da2", "da3", "da4" ] ),
78                Box::new( [ "d0", "da1", "da2", "da3", "da4", "da5" ] ),
79                Box::new( [ "d0", "da1", "da2", "da3", "da4", "da5", "da6" ] ),
80                Box::new( [ "d0", "da1", "da2", "da3", "da4", "da5", "da6", "da7" ] ),
81                Box::new( [ "d0", "da1", "da2", "da3", "da4", "da5", "da6", "da7", "da8" ] ),
82                Box::new( [ "d0", "da1", "da2", "da3", "da4", "da5", "da6", "da7", "da8", "da9" ] ),
83                Box::new( [ "d0", "da1", "da2", "db3" ] ),
84                Box::new( [ "d0", "da1", "da2", "db3", "db4" ] ),
85                Box::new( [ "d0", "da1", "da2", "db3", "db4", "db5" ] ),
86                Box::new( [ "d0", "da1", "da2", "db3", "db4", "db5", "db6" ] ),
87                Box::new( [ "d0", "da1", "da2", "db3", "db4", "db5", "db6", "db7" ] ),
88                Box::new( [ "d0", "da1", "da2", "db3", "db4", "db5", "db6", "db7", "db8" ] ),
89                Box::new( [ "d0", "da1", "da2", "db3", "db4", "db5", "db6", "db7", "db8", "db9" ] ),
90                Box::new( [ "d0", "da1", "da2", "db3", "db4", "db5", "dc6" ] ),
91                Box::new( [ "d0", "da1", "da2", "db3", "db4", "db5", "dc6", "dc7" ] ),
92                Box::new( [ "d0", "da1", "da2", "db3", "db4", "db5", "dc6", "dc7", "dd8" ] ),
93                Box::new( [ "d0", "da1", "da2", "db3", "db4", "db5", "dc6", "dc7", "dd8", "dd9" ] ),
94            ];
95            slice_of_paths.iter().map(|item| {item.iter().map(|item|{item.to_string()}).collect::<Vec<String>>()}).collect()
96        }
97        */
98        //
99        // Public - get - path
100        //
101        // Returns a path generated from a given node's expected test data
102        pub fn get_path_from_test_data(arg_string_test_data: &str) -> Vec<String> {
103            arg_string_test_data[ExampleTree::get_string_prefix_test_data().len()..]
104                .split("_")
105                .map(|item| item.to_string())
106                .collect()
107        }
108        //
109        // Public - get - string
110        //
111        // This provides a hard-coded prefix for consistency across all functions that depend on it
112        fn get_string_prefix_test_data() -> String {
113            "test_data_".to_string()
114        }
115
116        // Returns test data without the prefix
117        //pub fn get_string_test_data_without_prefix( arg_string: &str ) -> String { arg_string[ ExampleTree::get_string_prefix_test_data().len().. ].to_string() }
118
119        // Returns test data compiled from the path argument
120        pub fn get_string_test_data_via_path(arg_path: &[&str]) -> String {
121            [
122                ExampleTree::get_string_prefix_test_data(),
123                arg_path.join("_"),
124            ]
125            .join("")
126        }
127        //
128        // Public - get - vec
129        //
130        //
131        // This is a convenience function for writing out a 'quick' slice of boxed paths that
132        // won't trigger an error due to each path being a different size.
133        // I'm leaving this here for the sanity of anyone who wants to setup custom tests.
134        /*
135            // Example output:
136            let slice_of_paths: [Box<[&str]>; 5] = [
137                Box::new( [ "a0" ] ),
138                Box::new( [ "b0" ] ),
139                Box::new( [ "b0", "b1" ] ),
140                Box::new( [ "b0", "b1", "b2" ] ),
141                Box::new( [ "b0", "b1", "b2", "b3" ] ),
142            ];
143        */
144        /*
145        pub fn get_string_of_rust_code_to_support_rapid_creation_of_test_cases( arg_vec_of_paths: &Vec<Vec<String>> ) -> String {
146            let mut vec_to_return = vec![ format!( "let slice_of_paths: [Box<[&str]>; {}] = [", arg_vec_of_paths.len(), ) ];
147            for item_path in arg_vec_of_paths {
148                let item_path_string = format!( "    Box::new( [ \"{}\" ] ),", item_path.join( "\", \"" ) );
149                vec_to_return.push( item_path_string )
150            }
151            vec_to_return.push( "];".to_string() );
152            vec_to_return.join( "\n" )
153        }
154        */
155    }
156    //
157    // Test - get
158    //
159    #[test]
160    fn test_get_count_of_node_children() {
161        let mut node_root = Node::new();
162        for item_key in ["a", "b", "c"] {
163            match node_root.insert_node_at_key(item_key, Node::new()) {
164                Ok(()) => {}
165                Err(err) => panic!("{}", err),
166            };
167        }
168        assert_eq!(node_root.get_count_of_node_children(), 3 as usize);
169    }
170
171    #[test]
172    fn test_get_count_of_leaves() {
173        let node_root = ExampleTree::get_node_root_of_tree_new();
174        assert_eq!(node_root.get_count_of_leaves(), 7)
175    }
176
177    #[test]
178    fn test_get_key_to_node() {
179        let mut node_root = Node::new();
180
181        let slice_of_keys = ["a", "b", "c"];
182
183        for item_key in slice_of_keys {
184            let mut item_node_child = Node::new();
185            let item_test_data = ["test", item_key].join("_");
186            item_node_child.field_string_data = item_test_data;
187            match node_root.insert_node_at_key(item_key, item_node_child) {
188                Ok(()) => {}
189                Err(err) => panic!("{}", err),
190            }
191        }
192
193        let node_target = match node_root.get_node_at_key("b") {
194            Some(result) => result,
195            None => panic!("Failed to get node."),
196        };
197
198        let key_result = match node_root.get_key_to_node(&node_target) {
199            Some(result) => result,
200            None => panic!("Failed to get key."),
201        };
202
203        assert_eq!(key_result, "b".to_string())
204    }
205
206    #[test]
207    fn test_get_node_mute_at_key() {
208        let mut node_root = Node::new();
209        let node_child = Node::new();
210        match node_root.insert_node_at_key("a", node_child) {
211            Ok(()) => {}
212            Err(err) => panic!("{}", err),
213        };
214
215        let node_mut = match node_root.get_node_mut_at_key("a") {
216            Some(result) => result,
217            None => panic!("Failed to get node at key"),
218        };
219
220        assert_eq!(node_mut.field_string_data, "".to_string());
221
222        let data_expected_after_update = "TEST";
223        node_mut.field_string_data = data_expected_after_update.to_string();
224        assert_eq!(node_mut.field_string_data, data_expected_after_update);
225    }
226
227    #[test]
228    fn test_get_node_parent() {
229        let node_root = ExampleTree::get_node_root_of_tree_new();
230
231        let path = ["b0", "b1", "b2", "b3"];
232
233        let node_child_of_parent = match node_root.get_node_at_path_or_error(&path) {
234            Ok(result) => result,
235            Err(err) => panic!("{}", err),
236        };
237
238        let node_parent_result = match node_root.get_node_parent(&node_child_of_parent) {
239            Some(result) => result,
240            None => panic!("Failed to get node parent."),
241        };
242
243        let path_to_parent = &path[0..path.len() - 1];
244
245        let node_parent_expected = match node_root.get_node_at_path_or_error(&path_to_parent) {
246            Ok(result) => result,
247            Err(err) => panic!("{}", err),
248        };
249
250        assert!(eq(node_parent_result, node_parent_expected))
251    }
252
253    #[test]
254    fn test_get_path_to_node() {
255        let node_root = ExampleTree::get_node_root_of_tree_new();
256
257        let path_expected = ["c0", "ca1", "ca2", "ca3", "ca4", "ca5"];
258
259        let node_child = match node_root.get_node_at_path_or_error(&path_expected) {
260            Ok(result) => result,
261            Err(err) => panic!("{}", err),
262        };
263
264        let path_to_node = match node_root.get_path_to_node(&node_child) {
265            Some(result) => result,
266            None => panic!("Failed to get node"),
267        };
268
269        println!("path = {:?}", path_to_node);
270
271        assert_eq!(
272            path_to_node,
273            path_expected
274                .iter()
275                .map(|item| { item.to_string() })
276                .collect::<Vec<String>>()
277        )
278    }
279
280    #[test]
281    fn test_get_vec_of_data_along_path() {
282        let path = ["a", "b", "c"];
283        let data = "test";
284
285        let mut node_root = Node::new();
286
287        let mut node_child = Node::new();
288        node_child.field_string_data = data.to_string();
289
290        match node_root.insert_node_at_path(&path, node_child) {
291            Ok(()) => {}
292            Err(err) => panic!("{}", err),
293        };
294
295        let vec_result = match node_root.get_vec_of_nodes_along_path(&path) {
296            Some(result) => result,
297            None => panic!("Failed to return vec of data with correct path."),
298        }
299        .iter()
300        .map(|item_node| item_node.field_string_data.clone())
301        .collect::<Vec<String>>();
302
303        assert_eq!(
304            vec_result,
305            ["", "", data]
306                .iter()
307                .map(|item| { item.to_string() })
308                .collect::<Vec<String>>()
309        );
310    }
311
312    #[test]
313    fn test_get_vec_of_node_leaves() {
314        let mut node_root = Node::new();
315
316        let mut node_child = Node::new();
317        let string_data = "node_leaf";
318
319        node_child.field_string_data = string_data.to_string();
320
321        match node_root.insert_node_at_path(&["1", "2", "3"], node_child) {
322            Ok(()) => {}
323            Err(err) => panic!("{}", err),
324        };
325
326        let vec_of_node_leaves = node_root.get_vec_of_node_leaves();
327
328        let node_referenced = match vec_of_node_leaves.get(0) {
329            Some(result) => result,
330            None => panic!("No node leaves detected."),
331        };
332        assert_eq!(node_referenced.field_string_data, string_data)
333    }
334
335    #[test]
336    fn test_get_vec_of_nodes_satisfying_callback() {
337        let node_root = ExampleTree::get_node_root_of_tree_new();
338
339        let string_test_data_expected = "test_data_b0_b1_b2_b3";
340
341        let vec_of_nodes = node_root.get_vec_of_nodes_satisfying_callback(|arg_node| {
342            arg_node.field_string_data == string_test_data_expected.to_string()
343        });
344
345        assert_eq!(vec_of_nodes.len(), 1);
346
347        let node_result = match vec_of_nodes.get(0) {
348            Some(result) => result,
349            None => panic!("Error: Failed to get path."),
350        };
351
352        assert_eq!(node_result.field_string_data, string_test_data_expected)
353    }
354
355    #[test]
356    fn test_get_vec_of_pairs_paths_and_nodes_with_data_satisfying_callback_sorted() {
357        let node_root = ExampleTree::get_node_root_of_tree_new();
358
359        let string_test_data_expected = "test_data_b0_b1_b2_b3";
360
361        let vec_of_pairs_paths_and_nodes = node_root
362            .get_vec_of_pairs_paths_and_nodes_with_data_satisfying_callback_sorted(|arg_node| {
363                arg_node.field_string_data == string_test_data_expected.to_string()
364            });
365
366        assert_eq!(vec_of_pairs_paths_and_nodes.len(), 1);
367
368        let (path_result, _node_result) = match vec_of_pairs_paths_and_nodes.get(0) {
369            Some(result) => result,
370            None => panic!("Error: Failed to get path."),
371        };
372
373        let path_expected = ExampleTree::get_path_from_test_data(&string_test_data_expected);
374
375        assert_eq!(path_result.to_vec(), path_expected)
376    }
377
378    #[test]
379    fn test_get_vec_of_paths_to_nodes_satisfying_callback_sorted() {
380        let node_root = ExampleTree::get_node_root_of_tree_new();
381
382        let string_test_data_expected = "test_data_b0_b1_b2_b3";
383
384        let vec_of_paths =
385            node_root.get_vec_of_paths_to_nodes_satisfying_callback_sorted(|arg_node| {
386                arg_node.field_string_data == string_test_data_expected.to_string()
387            });
388
389        assert_eq!(vec_of_paths.len(), 1);
390
391        let path_result = match vec_of_paths.get(0) {
392            Some(result) => result,
393            None => panic!("Error: Failed to get path."),
394        };
395
396        let path_expected = ExampleTree::get_path_from_test_data(&string_test_data_expected);
397
398        assert_eq!(path_result.to_vec(), path_expected)
399    }
400
401    #[test]
402    fn test_get_vec_of_nodes_along_path() {
403        let path = ["a", "b", "c"];
404        let data = "test";
405
406        let mut node_root = Node::new();
407
408        let mut node_child = Node::new();
409        node_child.field_string_data = data.to_string();
410
411        match node_root.insert_node_at_path(&path, node_child) {
412            Ok(()) => {}
413            Err(err) => panic!("{}", err),
414        };
415
416        let vec_of_nodes_result = match node_root.get_vec_of_nodes_along_path(&path) {
417            Some(result) => result,
418            None => panic!("Failed to get vec of nodes."),
419        };
420
421        let vec_result = vec_of_nodes_result
422            .iter()
423            .map(|item_node| item_node.field_string_data.as_str())
424            .collect::<Vec<&str>>();
425        let vec_expected = ["", "", data]
426            .iter()
427            .map(|item| *item)
428            .collect::<Vec<&str>>();
429        assert_eq!(vec_result, vec_expected)
430    }
431
432    #[test]
433    fn test_get_vec_of_nodes_in_tree() {
434        let path = ["a", "b", "c"];
435        let data = "test";
436
437        let mut node_root = Node::new();
438
439        let mut node_child = Node::new();
440        node_child.field_string_data = data.to_string();
441
442        match node_root.insert_node_at_path(&path, node_child) {
443            Ok(()) => {}
444            Err(err) => panic!("{}", err),
445        };
446
447        let vec_of_strings = node_root
448            .get_vec_of_nodes_in_tree()
449            .iter()
450            .map(|item| item.field_string_data.as_str())
451            .collect::<Vec<&str>>();
452
453        assert_eq!(vec_of_strings, ["", "", data].to_vec())
454    }
455
456    #[test]
457    fn test_get_vec_of_paths_in_tree() {
458        let mut node_root = Node::new();
459
460        let slice_of_string_data = [
461            "test_a",
462            "test_a_b",
463            "test_a_b_c_d_e",
464            "test_aa_ab_ac",
465            "test_ba_bb_bc_bd",
466        ];
467
468        let slice_of_paths: [Box<[&str]>; 5] = [
469            Box::new(["a"]),
470            Box::new(["a", "b"]),
471            Box::new(["a", "b", "c", "d", "e"]),
472            Box::new(["aa", "ab", "ac"]),
473            Box::new(["ba", "bb", "bc", "bd"]),
474        ];
475
476        for item_index in 0..slice_of_string_data.len() {
477            let mut item_node_child = Node::new();
478            item_node_child.field_string_data = slice_of_string_data[item_index].to_string();
479
480            match node_root.insert_node_at_path(&*slice_of_paths[item_index], item_node_child) {
481                Ok(()) => {}
482                Err(err) => panic!("{}", err),
483            };
484        }
485        //
486        // Reminder: Trying to turn 'expected' right off the bat throws a compile error
487        //
488        let expected: [Box<[&str]>; 12] = [
489            Box::new(["a"]),
490            Box::new(["a", "b"]),
491            Box::new(["a", "b", "c"]),
492            Box::new(["a", "b", "c", "d"]),
493            Box::new(["a", "b", "c", "d", "e"]),
494            Box::new(["aa"]),
495            Box::new(["aa", "ab"]),
496            Box::new(["aa", "ab", "ac"]),
497            Box::new(["ba"]),
498            Box::new(["ba", "bb"]),
499            Box::new(["ba", "bb", "bc"]),
500            Box::new(["ba", "bb", "bc", "bd"]),
501        ];
502
503        let vec_expected = expected
504            .iter()
505            .map(|item| (*item).iter().map(|item| *item).collect::<Vec<&str>>())
506            .collect::<Vec<Vec<&str>>>();
507
508        assert_eq!(node_root.get_vec_of_paths_in_tree_sorted(), vec_expected);
509    }
510    //
511    // Test - insert
512    //
513    #[test]
514    fn test_insert_node_at_key() {
515        // Functions covered...
516        // - add_node_at_key
517        // - set_string_data
518
519        let key = "a";
520        let data = "test";
521
522        let mut node_root = Node::new();
523
524        let mut node_child = Node::new();
525        node_child.field_string_data = data.to_string();
526
527        match node_root.insert_node_at_key(key, node_child) {
528            Ok(()) => {}
529            Err(err) => panic!("{}", err),
530        };
531
532        let node_at_key = match node_root.get_node_at_key(key) {
533            Some(result) => result,
534            None => panic!("Error: Failed to get node."),
535        };
536
537        assert_eq!(node_at_key.field_string_data, data.to_string());
538
539        let result_node = match node_root.get_node_at_key(key) {
540            Some(result) => result,
541            None => panic!("Failed to get node at key."),
542        };
543        assert_eq!(result_node.field_string_data, data.to_string())
544    }
545
546    #[test]
547    fn test_insert_node_at_path() {
548        let path = ["a", "b", "c"];
549
550        let data = "test";
551
552        let mut node_root = Node::new();
553        let mut node_child = Node::new();
554
555        node_child.field_string_data = data.to_string();
556
557        match node_root.insert_node_at_path(&path, node_child) {
558            Ok(()) => {}
559            Err(err) => panic!("{}", err),
560        };
561
562        let node_at_path = match node_root.get_node_at_path_or_error(&path) {
563            Ok(result) => result,
564            Err(err) => panic!("{}", err),
565        };
566
567        assert_eq!(node_at_path.field_string_data, data.to_string())
568    }
569    //
570    // Test - pop
571    //
572    #[test]
573    fn test_pop_all_children_and_return_vec_of_pairs_keys_and_child_nodes() {
574        let slice_of_keys = ["a", "b", "c"];
575
576        let str_prefix_data = "test_data_";
577
578        let mut vec_of_node_data_expected = Vec::new();
579        let mut node_root = Node::new();
580        for item_key in slice_of_keys {
581            let item_string_test_data = [str_prefix_data, item_key].join("");
582
583            let mut node_child = Node::new();
584
585            // Capture the string here for testing later
586            // Clone the string here so the compiler won't complain when it drops from memory
587            vec_of_node_data_expected.push(item_string_test_data.clone());
588
589            node_child.field_string_data = item_string_test_data;
590
591            // node_root won't leave its 'borrowed as mut' state until the loop ends completely
592            match node_root.insert_node_at_key(item_key, node_child) {
593                Ok(()) => {}
594                Err(err) => panic!("{}", err),
595            };
596        }
597
598        vec_of_node_data_expected.sort();
599
600        let vec_of_pairs_result =
601            match node_root.pop_all_children_and_return_vec_of_pairs_keys_and_child_nodes() {
602                Some(result) => result,
603                None => panic!(
604                    "Failed: pop_all_children_and_return_vec_of_pairs_keys_and_child_nodes()"
605                ),
606            };
607        //
608        // Validate keys
609        //
610        let mut vec_of_keys_result = vec_of_pairs_result
611            .iter()
612            .map(|(item_key, _item_node)| item_key.as_str())
613            .collect::<Vec<&str>>();
614        vec_of_keys_result.sort_by(|item_left, item_right| item_left.cmp(item_right));
615
616        let vec_of_keys_expected = slice_of_keys
617            .iter()
618            .map(|item| *item)
619            .collect::<Vec<&str>>();
620
621        assert_eq!(vec_of_keys_result, vec_of_keys_expected,);
622
623        let mut vec_of_test_data_result = vec_of_pairs_result
624            .iter()
625            .map(|(_item_key, item_node)| item_node.field_string_data.clone())
626            .collect::<Vec<String>>();
627
628        vec_of_test_data_result.sort();
629
630        // This has to be a String comparison because the initially generated values drop from memory in the loop
631        assert_eq!(vec_of_test_data_result, vec_of_node_data_expected)
632    }
633
634    #[test]
635    fn test_pop_node_at_key() {
636        let key = "test";
637        let data = "test_data";
638
639        let mut node_root = Node::new();
640
641        let mut node_child = Node::new();
642        node_child.field_string_data = data.to_string();
643
644        match node_root.insert_node_at_key(key, node_child) {
645            Ok(()) => {}
646            Err(err) => panic!("{}", err),
647        };
648
649        node_child = match node_root.pop_node_at_key(key) {
650            Some(result) => result,
651            None => panic!("Failed to pop node at key: {}", key),
652        };
653
654        if node_root.has_key(key) {
655            panic!("Error: node_root still has key: {}", key)
656        }
657
658        assert_eq!(node_child.field_string_data, data.to_string())
659    }
660
661    #[test]
662    fn test_pop_node_at_path() {
663        let data = "test_data";
664
665        let path = ["a", "b", "c"];
666
667        let mut node_root = Node::new();
668
669        let mut node_child = Node::new();
670        node_child.field_string_data = data.to_string();
671        match node_root.insert_node_at_path(&path, node_child) {
672            Ok(()) => {}
673            Err(err) => panic!("{}", err),
674        };
675
676        node_child = match node_root.pop_node_at_path(&path) {
677            Some(result) => result,
678            None => panic!("Failed to pop node at path: {:?}", &path),
679        };
680
681        if node_root.has_path(&path) {
682            panic!("Error: node_root still has path: {:?}", &path)
683        }
684
685        assert_eq!(node_child.field_string_data, data.to_string())
686    }
687
688    #[test]
689    fn test_pop_node_at_path_or_error() {
690        let mut node_root = ExampleTree::get_node_root_of_tree_new();
691
692        let path = ["b0", "b1", "b2", "b3"];
693
694        assert_eq!(node_root.has_path(&path), true);
695
696        let node_popped = match node_root.pop_node_at_path_or_error(&path) {
697            Ok(result) => result,
698            Err(err) => panic!("{}", err,),
699        };
700
701        assert_eq!(node_root.has_path(&path), false);
702
703        let path_to_parent = &path[0..path.len() - 1];
704
705        assert_eq!(node_root.has_path(&path_to_parent), true);
706
707        let node_parent_expected = match node_root.get_node_at_path_or_error(&path_to_parent) {
708            Ok(result) => result,
709            Err(err) => panic!("{}", err),
710        };
711
712        assert_eq!(node_parent_expected.has_key(path[path.len() - 1]), false);
713
714        assert_eq!(
715            node_popped.field_string_data,
716            ExampleTree::get_string_test_data_via_path(&path)
717        );
718    }
719
720    #[test]
721    fn test_pop_node_at_key_and_promote_its_children() {
722        let mut node_root = Node::new();
723
724        let key_to_pop = "a";
725
726        let slice_of_keys = [key_to_pop, "b", "c"];
727        let slice_of_keys_tier_two = ["aa", "ab", "ac"];
728
729        let str_prefix_data = "test_";
730
731        for item_key in slice_of_keys {
732            let mut item_child = Node::new();
733            item_child.field_string_data = [str_prefix_data, item_key].join("");
734
735            match node_root.insert_node_at_key(item_key, item_child) {
736                Ok(()) => {}
737                Err(err) => panic!("{}", err),
738            };
739        }
740
741        let node_root_child = match node_root.get_node_mut_at_key("a") {
742            Some(result) => result,
743            None => panic!("Failed to get child node."),
744        };
745        for item_key in slice_of_keys_tier_two {
746            let mut item_child = Node::new();
747            item_child.field_string_data = [str_prefix_data, item_key].join("");
748
749            match node_root_child.insert_node_at_key(item_key, item_child) {
750                Ok(()) => {}
751                Err(err) => panic!("{}", err),
752            };
753        }
754
755        let _node_popped =
756            match node_root.pop_node_at_key_and_promote_its_children("a", "_promoted") {
757                Ok(result) => result,
758                Err(err) => panic!("{}", err,),
759            };
760
761        let expected = ["aa_promoted", "ab_promoted", "ac_promoted", "b", "c"]
762            .iter()
763            .map(|item| item.to_string())
764            .collect::<Vec<String>>();
765
766        assert_eq!(node_root.get_vec_of_keys_sorted(), expected);
767
768        let expected_filtered = ["aa_promoted", "ab_promoted", "ac_promoted"];
769
770        assert_eq!(
771            node_root.get_vec_of_keys_all_ending_with_suffix_sorted("_promoted"),
772            expected_filtered
773        )
774    }
775
776    #[test]
777    fn test_pop_node_at_path_and_promote_its_children() {
778        let mut node_root = Node::new();
779
780        let path = ["a", "b", "c"];
781
782        let path_parent_of_popped_node = ["a", "b"];
783
784        let keys_for_child_at_path = ["ca", "cb", "cc"];
785
786        let str_prefix_data = "test_";
787
788        let item_child = Node::new();
789        match node_root.insert_node_at_path(&path, item_child) {
790            Ok(()) => {}
791            Err(err) => panic!("{}", err),
792        };
793
794        let node_root_child = match node_root.get_node_mut_at_path(&path) {
795            Some(result) => result,
796            None => panic!("Failed to get child node."),
797        };
798
799        for item_key in keys_for_child_at_path {
800            let mut item_child = Node::new();
801            item_child.field_string_data = [str_prefix_data, item_key].join("");
802
803            match node_root_child.insert_node_at_key(item_key, item_child) {
804                Ok(()) => {}
805                Err(err) => panic!("{}", err),
806            };
807        }
808
809        let _node_popped =
810            match node_root.pop_node_at_path_and_promote_its_children(&path, "_promoted") {
811                Ok(result) => result,
812                Err(err) => panic!("{}", err,),
813            };
814
815        let node_parent = match node_root.get_node_at_path_or_error(&path_parent_of_popped_node) {
816            Ok(result) => result,
817            Err(err) => panic!("{}", err),
818        };
819
820        let expected = ["ca_promoted", "cb_promoted", "cc_promoted"]
821            .iter()
822            .map(|item| item.to_string())
823            .collect::<Vec<String>>();
824
825        assert_eq!(node_parent.get_vec_of_keys_sorted(), expected)
826    }
827    //
828    // Test - raise
829    //
830    #[test]
831    fn test_raise_error_if_path_is_invalid() {
832        let path_valid = ["a", "b", "c"];
833        match Node::raise_error_if_path_is_invalid(&path_valid) {
834            Ok(()) => {}
835            Err(err) => panic!("{}", err),
836        };
837
838        let path_invalid = ["a", "b", ""];
839        match Node::raise_error_if_path_is_invalid(&path_invalid) {
840            Ok(()) => {
841                panic!("raise_error_if_path_is_invalid() failed to raise error on invalid path.")
842            }
843            Err(_err) => {}
844        }
845    }
846}
847//
848// Public
849//
850#[derive(Serialize, Deserialize, Debug)]
851pub struct Node {
852    //
853    // Fields
854    //
855    /// Stores any within node
856    pub field_string_data: String,
857    // Reminders:
858    // - References won't work here because Rust limits mutable borrows to *one*
859    // - &str seems to get Rust to demand Node also becomes a reference (moves are *absolutely* necessary to avoid 'borrow hell')
860    pub field_hash_map_children: HashMap<String, Node>,
861}
862
863impl Node {
864    //
865    // Public - clear
866    //
867    /// This removes all children without returning anything
868    // No test needed, simple wrapper
869    pub fn clear_children(&mut self) {
870        self.field_hash_map_children.clear()
871    }
872    //
873    // Public - get - count
874    //
875    /// Returns usize count for leaves
876    // Test: test_get_count_of_leaves()
877    pub fn get_count_of_leaves(&self) -> usize {
878        let mut int_count_to_return = 0;
879        let mut stack = self
880            .field_hash_map_children
881            .values()
882            .collect::<Vec<&Node>>();
883        loop {
884            if let Some(item_node) = stack.pop() {
885                if item_node.field_hash_map_children.is_empty() {
886                    int_count_to_return += 1;
887                } else {
888                    stack.extend(item_node.field_hash_map_children.values())
889                }
890            } else {
891                break;
892            }
893        }
894        int_count_to_return
895    }
896
897    /// Returns a usize value representing the number of children this node possesses
898    // No test needed, simple wrapper
899    pub fn get_count_of_node_children(&self) -> usize {
900        self.field_hash_map_children.values().len()
901    }
902    //
903    // Public - get - node
904    //
905    /// Returns the node reference; or None
906    /// # Arguments
907    /// * arg_key: Key referring to the child node
908    // Test: test_add_node_at_key()
909    pub fn get_node_at_key(&self, arg_key: &str) -> Option<&Node> {
910        Some(self.field_hash_map_children.get(&arg_key.to_string())?)
911    }
912
913    /// Returns the node referenced; or None
914    /// # Arguments
915    /// * arg_path: Path referring to node within sub-tree
916    // Test: test_insert_node_at_path()
917    pub fn get_node_at_path(&self, arg_path: &[&str]) -> Option<&Node> {
918        match arg_path.len() {
919            0 => return None,
920            1 => return Some(self.field_hash_map_children.get(arg_path[0])?),
921            _ => {
922                let mut node_to_return = self;
923                for item_key in arg_path {
924                    node_to_return = node_to_return
925                        .field_hash_map_children
926                        .get(&item_key.to_string())?
927                }
928                Some(node_to_return)
929            }
930        }
931    }
932
933    /// Returns the node referenced; or an error explaining where the path failed
934    /// # Arguments
935    /// * arg_path: Path referring to node within sub-tree
936    // Test: test_insert_node_at_path()
937    pub fn get_node_at_path_or_error(&self, arg_path: &[&str]) -> Result<&Node, String> {
938        match arg_path.len() {
939            0 => return Err("Error: arg_path is empty.".to_string()),
940            1 => match self.field_hash_map_children.get(arg_path[0]) {
941                Some(node) => return Ok(node),
942                None => {
943                    return Err([
944                        "Error: arg_path not in tree.".to_string(),
945                        format!("arg_path = {}", arg_path[0]),
946                    ]
947                    .join("\n"))
948                }
949            },
950            _ => {
951                let mut vec_path_that_exists = Vec::new();
952                let mut node_to_return = self;
953                for item_key in arg_path {
954                    if let Some(node) = node_to_return
955                        .field_hash_map_children
956                        .get(&item_key.to_string())
957                    {
958                        node_to_return = node;
959                        vec_path_that_exists.push(*item_key);
960                    } else {
961                        return Err(Node::raise_error_because_path_failed(
962                            item_key,
963                            &arg_path,
964                            &vec_path_that_exists,
965                        ));
966                    }
967                }
968                Ok(node_to_return)
969            }
970        }
971    }
972    //
973    // Public - get - node mut
974    //
975    /// Returns the node referenced as a mutable; or None
976    /// # Arguments
977    /// * arg_key: Key referring to child node
978    // Test: test_get_node_mute_at_key()
979    pub fn get_node_mut_at_key(&mut self, arg_key: &str) -> Option<&mut Node> {
980        Some(self.field_hash_map_children.get_mut(&arg_key.to_string())?)
981    }
982
983    /// Returns the node referenced as a mutable; or None
984    /// # Arguments
985    /// * arg_path: Path referring to node within sub-tree
986    // Test: test_pop_node_at_path_and_promote_its_children()
987    pub fn get_node_mut_at_path(&mut self, arg_path: &[&str]) -> Option<&mut Node> {
988        match arg_path.len() {
989            0 => return None,
990            1 => return self.get_node_mut_at_key(arg_path[0]),
991            _ => {
992                let mut node_to_return = self;
993                for item_key in arg_path {
994                    node_to_return = node_to_return
995                        .field_hash_map_children
996                        .get_mut(&item_key.to_string())?
997                }
998                Some(node_to_return)
999            }
1000        }
1001    }
1002
1003    /// Returns the node referenced as a mutable; or an error message explaining where the path failed
1004    /// # Arguments
1005    /// * arg_path: Path referring to node within sub-tree
1006    // Test: test_pop_node_at_path_and_promote_its_children()
1007    pub fn get_node_mut_at_path_or_error(
1008        &mut self,
1009        arg_path: &[&str],
1010    ) -> Result<&mut Node, String> {
1011        match arg_path.len() {
1012            0 => return Err("Error: arg_path is empty.".to_string()),
1013            1 => {
1014                if let Some(node) = self.get_node_mut_at_key(arg_path[0]) {
1015                    return Ok(node);
1016                } else {
1017                    return Err([
1018                        "Error: arg_path does not exist.".to_string(),
1019                        format!("arg_path = {:?}", arg_path),
1020                    ]
1021                    .join("\n"));
1022                }
1023            }
1024            _ => {
1025                let mut vec_path_that_exists = Vec::new();
1026                let mut node_to_return = self;
1027                for item_key in arg_path {
1028                    if let Some(node_result) = node_to_return
1029                        .field_hash_map_children
1030                        .get_mut(&item_key.to_string())
1031                    {
1032                        vec_path_that_exists.push(*item_key);
1033                        node_to_return = node_result
1034                    } else {
1035                        return Err(Node::raise_error_because_path_failed(
1036                            item_key,
1037                            arg_path,
1038                            &vec_path_that_exists,
1039                        ));
1040                    }
1041                }
1042                Ok(node_to_return)
1043            }
1044        }
1045    }
1046    //
1047    // Public - get - node parent
1048    //
1049    /// Returns the parent of a given node; or None
1050    /// # Arguments
1051    /// * arg_node: The node with the parent
1052    // Test: test_get_node_parent()
1053    pub fn get_node_parent(&self, arg_node: &Node) -> Option<&Node> {
1054        if eq(arg_node, self) {
1055            return None;
1056        }
1057        let mut stack = self
1058            .field_hash_map_children
1059            .values()
1060            .map(|item| (self, item))
1061            .collect::<Vec<(&Node, &Node)>>();
1062        loop {
1063            let (item_node_parent, item_node) = stack.pop()?;
1064            if eq(item_node, arg_node) {
1065                return Some(item_node_parent);
1066            }
1067            stack.extend(
1068                item_node
1069                    .field_hash_map_children
1070                    .values()
1071                    .map(|item_node_sub| (item_node, item_node_sub))
1072                    .collect::<Vec<(&Node, &Node)>>(),
1073            );
1074        }
1075    }
1076    //
1077    // Public - get - path
1078    //
1079    /// Returns the key pointing to arg_node
1080    /// # Arguments
1081    /// * arg_node: This is the node searched for
1082    // Test: test_get_key_to_node()
1083    pub fn get_key_to_node(&self, arg_node: &Node) -> Option<String> {
1084        for (item_key, item_node) in &self.field_hash_map_children {
1085            if eq(item_node, arg_node) {
1086                return Some(item_key.clone());
1087            }
1088        }
1089        None
1090    }
1091
1092    /// Returns the path to the node, relative to the root node; or None
1093    /// # Arguments
1094    /// * arg_node: This is the node searched for
1095    // Test: test_get_path_to_node()
1096    pub fn get_path_to_node(&self, arg_node: &Node) -> Option<Vec<String>> {
1097        let mut stack = self
1098            .field_hash_map_children
1099            .iter()
1100            .map(|(item_key, item_node)| (vec![item_key], item_node))
1101            .collect::<Vec<(Vec<&String>, &Node)>>();
1102        loop {
1103            // If the stack empties before leaving the function, then the node wasn't found
1104            let (item_path, item_node) = stack.pop()?;
1105            if eq(item_node, arg_node) {
1106                return Some(item_path.iter().map(|item| item.to_string()).collect());
1107            }
1108            stack.extend(
1109                item_node
1110                    .field_hash_map_children
1111                    .iter()
1112                    .map(|(item_key, item_node)| {
1113                        (
1114                            Node::get_path_with_appended_key(&item_path, item_key),
1115                            item_node,
1116                        )
1117                    })
1118                    .collect::<Vec<(Vec<&String>, &Node)>>(),
1119            );
1120        }
1121    }
1122    //
1123    // Public - get - vec - keys
1124    //
1125    /// Returns a vec of keys for each immediate child of the root node
1126    // No test needed since this func is a straight wrapper
1127    pub fn get_vec_of_keys(&self) -> Vec<String> {
1128        self.field_hash_map_children
1129            .keys()
1130            .map(|item| item.clone())
1131            .collect()
1132    }
1133
1134    /// Returns a vec of keys sorted
1135    // Tested in: test_pop_node_and_promote_its_children()
1136    pub fn get_vec_of_keys_sorted(&self) -> Vec<String> {
1137        let mut vec_to_return = self.get_vec_of_keys();
1138        vec_to_return.sort_by(|item_left, item_right| item_left.cmp(item_right));
1139        vec_to_return
1140    }
1141
1142    /// Returns a vec of child keys, filtered by suffix
1143    /// Tip: Useful if running pop_node_and_promote_children_at_key()
1144    /// # Arguments
1145    /// * arg_suffix: All keys possessing this suffix get returned
1146    // Test: get_vec_of_keys_all_ending_with_suffix_sorted()
1147    pub fn get_vec_of_keys_all_ending_with_suffix(&self, arg_suffix: &str) -> Vec<String> {
1148        self.field_hash_map_children
1149            .keys()
1150            .filter(|item| item.ends_with(arg_suffix))
1151            .map(|item| item.clone())
1152            .collect::<Vec<String>>()
1153    }
1154
1155    /// Returns a vec of child keys, filtered by suffix and sorted
1156    /// Tip: Useful if running pop_node_and_promote_children_at_key()
1157    /// # Arguments
1158    /// * arg_suffix: All keys possessing this suffix get returned
1159    // Tested: test_pop_node_at_key_and_promote_its_children()
1160    pub fn get_vec_of_keys_all_ending_with_suffix_sorted(&self, arg_suffix: &str) -> Vec<String> {
1161        let mut vec_to_return = self
1162            .field_hash_map_children
1163            .keys()
1164            .filter(|item| item.ends_with(arg_suffix))
1165            .map(|item| item.clone())
1166            .collect::<Vec<String>>();
1167        vec_to_return.sort_by(|item_left, item_right| item_left.cmp(item_right));
1168        vec_to_return
1169    }
1170    //
1171    // Public - get - vec - node
1172    //
1173    /// Returns vec consisting of the root node's immediate children
1174    // Testing not needed, this is a wrapper
1175    pub fn get_vec_of_node_children(&self) -> Vec<&Node> {
1176        self.field_hash_map_children
1177            .values()
1178            .collect::<Vec<&Node>>()
1179    }
1180
1181    /// Returns vec of nodes within subtree that have no children
1182    // Test: get_vec_of_node_leaves()
1183    pub fn get_vec_of_node_leaves(&self) -> Vec<&Node> {
1184        let mut vec_to_return = Vec::new();
1185        let mut stack = self
1186            .field_hash_map_children
1187            .values()
1188            .collect::<Vec<&Node>>();
1189        loop {
1190            if let Some(item_node) = stack.pop() {
1191                if item_node.field_hash_map_children.is_empty() {
1192                    vec_to_return.push(item_node)
1193                } else {
1194                    stack.extend(item_node.field_hash_map_children.values())
1195                }
1196            } else {
1197                break;
1198            }
1199        }
1200        vec_to_return
1201    }
1202
1203    /// Returns vec of nodes along a given path; this does *not* include the root node
1204    /// # Arguments
1205    /// * arg_path: This is the path along which the nodes will be collected
1206    // Test: test_pathing()
1207    pub fn get_vec_of_nodes_along_path(&self, arg_path: &[&str]) -> Option<Vec<&Node>> {
1208        match arg_path.len() {
1209            0 => return None,
1210            1 => return Some(vec![self.get_node_at_key(arg_path[0])?]),
1211            _ => {
1212                let mut vec_to_return = Vec::new();
1213                let mut item_node_current = self;
1214                for item_key in arg_path {
1215                    // Update item_node_current for next iteration
1216                    item_node_current = item_node_current
1217                        .field_hash_map_children
1218                        .get(&item_key.to_string())?;
1219                    vec_to_return.push(item_node_current);
1220                }
1221                Some(vec_to_return)
1222            }
1223        }
1224    }
1225
1226    /// Returns a vec of all nodes within the tree; this does *not* include the root node
1227    // Test: test_get_vec_of_nodes_in_tree()
1228    pub fn get_vec_of_nodes_in_tree(&self) -> Vec<&Node> {
1229        let mut vec_to_return = Vec::new();
1230        let mut stack = self
1231            .field_hash_map_children
1232            .values()
1233            .collect::<Vec<&Node>>();
1234        loop {
1235            if let Some(item_node) = stack.pop() {
1236                vec_to_return.push(item_node);
1237                stack.extend(item_node.field_hash_map_children.values())
1238            } else {
1239                break;
1240            }
1241        }
1242        vec_to_return
1243    }
1244
1245    /// Returns a vec of all nodes that cause callback to return true
1246    /// # Arguments
1247    /// * arg_callback: Receives a node and returns bool
1248    // Test: test_get_vec_of_nodes_satisfying_callback()
1249    pub fn get_vec_of_nodes_satisfying_callback(
1250        &self,
1251        arg_callback: impl Fn(&Node) -> bool,
1252    ) -> Vec<&Node> {
1253        let mut vec_to_return = Vec::new();
1254        let mut stack = self
1255            .field_hash_map_children
1256            .values()
1257            .collect::<Vec<&Node>>();
1258        loop {
1259            if let Some(item_node) = stack.pop() {
1260                if arg_callback(item_node) {
1261                    vec_to_return.push(item_node)
1262                }
1263                stack.extend(item_node.field_hash_map_children.values());
1264            } else {
1265                break;
1266            }
1267        }
1268        vec_to_return
1269    }
1270    //
1271    // Public - get - vec - pairs
1272    //
1273    /// Returns a vec of tuple-pairs referring to the keys and node children
1274    // No test needed; simple collection
1275    pub fn get_vec_of_pairs_keys_and_node_children(&self) -> Vec<(String, &Node)> {
1276        self.field_hash_map_children
1277            .iter()
1278            .map(|(item_string, item_node)| (item_string.clone(), item_node))
1279            .collect()
1280    }
1281
1282    /// Returns a vec of tuple-pairs referring to the keys and node children
1283    // No test needed; simple collection
1284    pub fn get_vec_of_pairs_keys_and_node_mut_children(&mut self) -> Vec<(String, &mut Node)> {
1285        self.field_hash_map_children
1286            .iter_mut()
1287            .map(|(item_string, item_node)| (item_string.clone(), item_node))
1288            .collect()
1289    }
1290
1291    /// Returns a vec of tuple-pairs consisting of paths and nodes; filtered by callback returning true
1292    /// Arguments
1293    /// * arg_callback: Receives a node and returns bool
1294    // Test: test_get_vec_of_pairs_paths_and_nodes_with_data_satisfying_callback_sorted()
1295    pub fn get_vec_of_pairs_paths_and_nodes_with_data_satisfying_callback(
1296        &self,
1297        arg_callback: impl Fn(&Node) -> bool,
1298    ) -> Vec<(Vec<String>, &Node)> {
1299        let mut vec_to_return = Vec::new();
1300        let mut stack = self
1301            .field_hash_map_children
1302            .iter()
1303            .map(|(item_key, item_node)| (vec![item_key], item_node))
1304            .collect::<Vec<(Vec<&String>, &Node)>>();
1305        loop {
1306            //
1307            // Pop from stack
1308            //
1309            if let Some((item_path, item_node)) = stack.pop() {
1310                //
1311                // Prep next iteration
1312                //
1313                stack.extend(
1314                    item_node
1315                        .field_hash_map_children
1316                        .iter()
1317                        .map(|(item_key, item_node)| {
1318                            (
1319                                Node::get_path_with_appended_key(&item_path, item_key),
1320                                item_node,
1321                            )
1322                        })
1323                        .collect::<Vec<(Vec<&String>, &Node)>>(),
1324                );
1325                //
1326                // Do comparison and add to return value
1327                //
1328                if arg_callback(item_node) {
1329                    vec_to_return.push((
1330                        item_path.into_iter().map(|item| item.clone()).collect(),
1331                        item_node,
1332                    ))
1333                }
1334            } else {
1335                break;
1336            }
1337        }
1338        vec_to_return
1339    }
1340
1341    /// Returns a sorted vec of tuple-pairs consisting of paths and nodes with data matching the argument; filtered by callback
1342    /// # Arguments
1343    /// * arg_callback: Receives a node and returns bool
1344    // Test: test_get_vec_of_pairs_paths_and_nodes_with_data_satisfying_callback_sorted()
1345    pub fn get_vec_of_pairs_paths_and_nodes_with_data_satisfying_callback_sorted(
1346        &self,
1347        arg_callback: impl Fn(&Node) -> bool,
1348    ) -> Vec<(Vec<String>, &Node)> {
1349        Node::get_vec_of_pairs_paths_and_generics_sorted(
1350            self.get_vec_of_pairs_paths_and_nodes_with_data_satisfying_callback(arg_callback),
1351        )
1352    }
1353    //
1354    // Public - get - vec - paths
1355    //
1356    /// Returns a vec of all paths within the tree
1357    // Test: test_get_vec_of_paths_in_tree()
1358    pub fn get_vec_of_paths_in_tree(&self) -> Vec<Vec<String>> {
1359        let mut vec_to_return = Vec::new();
1360        let mut stack = self
1361            .field_hash_map_children
1362            .iter()
1363            .map(|(item_key, item_node)| (vec![item_key], item_node))
1364            .collect::<Vec<(Vec<&String>, &Node)>>();
1365        loop {
1366            if let Some((item_path, item_node)) = stack.pop() {
1367                for (item_key_sub, item_node_sub) in &item_node.field_hash_map_children {
1368                    stack.push((
1369                        Node::get_path_with_appended_key(&item_path, item_key_sub),
1370                        &item_node_sub,
1371                    ));
1372                }
1373                vec_to_return.push(
1374                    item_path
1375                        .into_iter()
1376                        .map(|item| item.to_string())
1377                        .collect::<Vec<String>>(),
1378                );
1379            } else {
1380                break;
1381            }
1382        }
1383        vec_to_return
1384    }
1385
1386    /// Returns a vec of all paths within the tree, sorted
1387    // Test: test_get_vec_of_paths_in_tree()
1388    pub fn get_vec_of_paths_in_tree_sorted(&self) -> Vec<Vec<String>> {
1389        Node::get_vec_of_paths_sorted(self.get_vec_of_paths_in_tree())
1390    }
1391
1392    /// Returns a vec of all paths pointing to nodes with no children
1393    // Test: test_get_vec_of_node_leaves()
1394    pub fn get_vec_of_paths_to_node_leaves(&self) -> Vec<Vec<String>> {
1395        let mut vec_to_return = Vec::new();
1396        let mut stack = self
1397            .field_hash_map_children
1398            .iter()
1399            .map(|(item_key, item_node)| (vec![item_key], item_node))
1400            .collect::<Vec<(Vec<&String>, &Node)>>();
1401        loop {
1402            if let Some((item_path, item_node)) = stack.pop() {
1403                if item_node.field_hash_map_children.is_empty() {
1404                    vec_to_return.push(
1405                        item_path
1406                            .into_iter()
1407                            .map(|item| item.to_string())
1408                            .collect::<Vec<String>>(),
1409                    )
1410                } else {
1411                    for (item_key_sub, item_node_sub) in &item_node.field_hash_map_children {
1412                        stack.push((
1413                            Node::get_path_with_appended_key(&item_path, item_key_sub),
1414                            &item_node_sub,
1415                        ));
1416                    }
1417                }
1418            } else {
1419                break;
1420            }
1421        }
1422        vec_to_return
1423    }
1424
1425    /// Returns a vec of all paths pointing to nodes whose data satisfies the callback
1426    /// # Arguments
1427    /// * arg_callback: Receives a node and returns bool.
1428    // Test: test_get_vec_of_paths_to_nodes_satisfying_callback_sorted()
1429    pub fn get_vec_of_paths_to_nodes_satisfying_callback(
1430        &self,
1431        arg_callback: impl Fn(&Node) -> bool,
1432    ) -> Vec<Vec<String>> {
1433        let mut vec_to_return = Vec::new();
1434        let mut stack = self
1435            .field_hash_map_children
1436            .iter()
1437            .map(|(item_key, item_node)| (vec![item_key], item_node))
1438            .collect::<Vec<(Vec<&String>, &Node)>>();
1439        loop {
1440            if let Some((item_path, item_node)) = stack.pop() {
1441                stack.extend(
1442                    item_node
1443                        .field_hash_map_children
1444                        .iter()
1445                        .map(|(item_key, item_node)| {
1446                            (
1447                                Node::get_path_with_appended_key(&item_path, item_key),
1448                                item_node,
1449                            )
1450                        })
1451                        .collect::<Vec<(Vec<&String>, &Node)>>(),
1452                );
1453                if arg_callback(item_node) {
1454                    vec_to_return.push(
1455                        item_path
1456                            .into_iter()
1457                            .map(|item| item.to_string())
1458                            .collect::<Vec<String>>(),
1459                    )
1460                }
1461            } else {
1462                break;
1463            }
1464        }
1465        vec_to_return
1466    }
1467
1468    /// Returns a vec of paths to all nodes whose satisfies the callback
1469    /// * arg_callback: Receives a node and returns bool
1470    // Test: test_get_vec_of_paths_to_nodes_satisfying_callback_sorted()
1471    pub fn get_vec_of_paths_to_nodes_satisfying_callback_sorted(
1472        &self,
1473        arg_callback: impl Fn(&Node) -> bool,
1474    ) -> Vec<Vec<String>> {
1475        Node::get_vec_of_paths_sorted(
1476            self.get_vec_of_paths_to_nodes_satisfying_callback(arg_callback),
1477        )
1478    }
1479    //
1480    // Public - insert
1481    //
1482    /// Adds node at the designated key.
1483    /// WARNING: The tree needs to take ownership of this node upon passing
1484    /// # Arguments
1485    /// * arg_key: A key of type &str used to identify a child node
1486    /// * arg_node: This is node to add at the end of the path
1487    // Test: test_insert_node_at_key()
1488    pub fn insert_node_at_key(&mut self, arg_key: &str, arg_node: Node) -> Result<(), String> {
1489        Node::raise_error_if_key_is_invalid(arg_key)?;
1490        self.field_hash_map_children
1491            .insert(arg_key.to_string(), arg_node);
1492        Ok(())
1493    }
1494
1495    /// Adds node at path. Returns the parent of the new node. Despite the return value being 'optional'
1496    /// this will always return a Node.
1497    /// WARNING: The tree needs to take ownership of this node upon passing
1498    /// The function will create any necessary intermediate nodes along its approach
1499    /// # Arguments
1500    /// * arg_path: Slice of &str keys which is use to navigate from the node of origin to the descendant node
1501    /// * arg_node: This is node to add at the end of the path
1502    // Test: test_pop_node_at_path() ...also this is a 'work horse' function in the test file
1503    pub fn insert_node_at_path(&mut self, arg_path: &[&str], arg_node: Node) -> Result<(), String> {
1504        match arg_path.len() {
1505            0 => return Node::raise_error_if_path_is_invalid(&arg_path),
1506            1 => return self.insert_node_at_key(arg_path[0], arg_node),
1507            _ => {
1508                // Block any attempt to use a path with empty elements
1509                Node::raise_error_if_path_is_invalid(&arg_path)?;
1510
1511                let mut node_current = self;
1512                for item_key in &arg_path[0..arg_path.len() - 1] {
1513                    // Reminder: This approach is necessary because Rust won't tolerate more than *one* mutable borrow
1514                    if node_current
1515                        .field_hash_map_children
1516                        .contains_key(&item_key.to_string())
1517                    {
1518                        if let Some(node_next) = node_current
1519                            .field_hash_map_children
1520                            .get_mut(&item_key.to_string())
1521                        {
1522                            node_current = node_next
1523                        } else {
1524                            return Err("Error: Failed to get node child that's definitely there."
1525                                .to_string());
1526                        }
1527                    } else {
1528                        node_current
1529                            .field_hash_map_children
1530                            .insert(item_key.to_string(), Node::new());
1531                        if let Some(node_next) = node_current
1532                            .field_hash_map_children
1533                            .get_mut(&item_key.to_string())
1534                        {
1535                            node_current = node_next;
1536                        } else {
1537                            return Err("Error: Failed to get node child that's definitely there."
1538                                .to_string());
1539                        }
1540                    }
1541                }
1542                node_current
1543                    .field_hash_map_children
1544                    .insert(arg_path[arg_path.len() - 1].to_string(), arg_node);
1545            }
1546        }
1547        Ok(())
1548    }
1549
1550    //
1551    // Public - logic
1552    //
1553    /// Returns true if the root node has children
1554    // No test needed since this is a wrapper
1555    pub fn has_children(&self) -> bool {
1556        self.field_hash_map_children.len() > 0
1557    }
1558
1559    /// Returns true if the string within the node contains any data
1560    // No test needed since this is a wrapper
1561    pub fn has_data(&self) -> bool {
1562        self.field_string_data.len() > 0
1563    }
1564
1565    /// Returns true if the key exists for an immediate child
1566    /// # Arguments
1567    /// * arg_key: A key of type &str used to identify a child node
1568    // No test needed since this is a wrapper
1569    pub fn has_key(&self, arg_key: &str) -> bool {
1570        self.field_hash_map_children
1571            .contains_key(&arg_key.to_string())
1572    }
1573
1574    /// Returns true if function can travers entire path without encountering a missing node
1575    /// # Arguments
1576    /// * arg_path: Slice of &str keys which is use to navigate from the node of origin to the descendant node
1577    // Test: test_pop_node_at_path()
1578    pub fn has_path(&self, arg_path: &[&str]) -> bool {
1579        match arg_path.len() {
1580            0 => return false,
1581            1 => self.has_key(arg_path[0]),
1582            _ => {
1583                let mut node_current = self;
1584                for item_key in arg_path {
1585                    if let Some(node_next) = node_current
1586                        .field_hash_map_children
1587                        .get(&item_key.to_string())
1588                    {
1589                        node_current = node_next
1590                    } else {
1591                        return false;
1592                    }
1593                }
1594                true
1595            }
1596        }
1597    }
1598
1599    /// Returns true if all path elements are valid (is *not* empty, and has no empty components)
1600    // Test not needed
1601    pub fn is_path_valid(arg_path: &[&str]) -> bool {
1602        if arg_path.is_empty() {
1603            return false;
1604        }
1605        for item_key in arg_path {
1606            if item_key.is_empty() {
1607                return false;
1608            }
1609        }
1610        true
1611    }
1612    //
1613    // Public - pop
1614    //
1615    /// Returns a vec of tuple pairs: key and node, and removes them all from this node
1616    // Test: test_pop_all_children_and_return_vec_of_pairs_keys_and_child_nodes()
1617    pub fn pop_all_children_and_return_vec_of_pairs_keys_and_child_nodes(
1618        &mut self,
1619    ) -> Option<Vec<(String, Node)>> {
1620        let mut vec_to_return = Vec::new();
1621        // Reminder: The clone is needed here to avoid an mutability complaint
1622        for item_key in self
1623            .field_hash_map_children
1624            .keys()
1625            .map(|item| item.clone())
1626            .collect::<Vec<String>>()
1627        {
1628            vec_to_return.push((
1629                item_key.clone(),
1630                self.field_hash_map_children.remove(&item_key)?,
1631            ));
1632        }
1633        Some(vec_to_return)
1634    }
1635
1636    /// Pops a child, and promotes all of its children to become parents of this node
1637    /// # Arguments
1638    /// * arg_key: The str key to pop
1639    /// * arg_collision_suffix: Custom suffix to append to all promoted nodes
1640    // Test: test_pop_node_and_promote_its_children()
1641    pub fn pop_node_at_key_and_promote_its_children(
1642        &mut self,
1643        arg_key: &str,
1644        arg_collision_suffix: &str,
1645    ) -> Result<Node, String> {
1646        //
1647        // Reminder: This first lookup is here to check for possible collisions before making changes to the tree
1648        //
1649        let node_to_pop = match self.field_hash_map_children.get(arg_key) {
1650            Some(result) => result,
1651            None => {
1652                return Err([
1653                    "Error: arg_key is not a child.".to_string(),
1654                    format!("arg_key = {}", arg_key),
1655                ]
1656                .join("\n"))
1657            }
1658        };
1659        //
1660        // Generate the keys with the suffixes and check for collisions before making any changes to the tree
1661        //
1662        let mut vec_of_collisions_detected: Vec<String> = Vec::new();
1663        let mut vec_of_pairs_keys_in_node_to_pop_and_keys_with_suffixes = Vec::new();
1664        for item_key in node_to_pop.field_hash_map_children.keys() {
1665            let item_key_with_suffix = [item_key, arg_collision_suffix].join("");
1666            vec_of_pairs_keys_in_node_to_pop_and_keys_with_suffixes
1667                .push((item_key.clone(), item_key_with_suffix.clone()));
1668            if self
1669                .field_hash_map_children
1670                .contains_key(&item_key_with_suffix)
1671            {
1672                vec_of_collisions_detected.push(item_key_with_suffix.clone());
1673            }
1674        }
1675        //
1676        // Abort if arg_collision_suffix is insufficient to avoid collisions in the parent node
1677        //
1678        if vec_of_collisions_detected.len() > 0 {
1679            return Err([
1680                "Error: Collisions detected with suffix.".to_string(),
1681                format!(
1682                    "vec_of_collisions_detected = {:?}",
1683                    vec_of_collisions_detected
1684                ),
1685            ]
1686            .join("\n"));
1687        }
1688        //
1689        // If we get this far, then there are no collisions
1690        //
1691        let mut node_popped_root = match self.field_hash_map_children.remove(arg_key) {
1692            Some(result) => result,
1693            None => {
1694                return Err([
1695                    "Error: Failed key doesn't exist.".to_string(),
1696                    format!("arg_key = {}", arg_key),
1697                ]
1698                .join("\n"))
1699            }
1700        };
1701        for (item_key_to_pop, item_key_with_suffix) in
1702            vec_of_pairs_keys_in_node_to_pop_and_keys_with_suffixes
1703        {
1704            if let Some(item_node_popped_child) = node_popped_root
1705                .field_hash_map_children
1706                .remove(item_key_to_pop.as_str())
1707            {
1708                self.field_hash_map_children
1709                    .insert(item_key_with_suffix.to_string(), item_node_popped_child);
1710            } else {
1711                return Err([
1712                    "Error: Failed to pop child from node_popped.".to_string(),
1713                    format!("item_key_to_pop = {}", item_key_to_pop,),
1714                    format!(
1715                        "slice of valid keys = {:?}",
1716                        self.field_hash_map_children.keys()
1717                    ),
1718                ]
1719                .join("\n"));
1720            }
1721        }
1722        Ok(node_popped_root)
1723    }
1724
1725    /// Pops a child, and promotes all of its children to become parents of this node
1726    ///
1727    pub fn pop_node_at_path_and_promote_its_children(
1728        &mut self,
1729        arg_path: &[&str],
1730        arg_collision_suffix: &str,
1731    ) -> Result<Node, String> {
1732        match arg_path.len() {
1733            0 => return Err("Error: arg_path is empty.".to_string()),
1734            1 => {
1735                return self
1736                    .pop_node_at_key_and_promote_its_children(arg_path[0], arg_collision_suffix)
1737            }
1738            _ => {
1739                Node::raise_error_if_path_is_invalid(&arg_path)?;
1740
1741                let index_last = arg_path.len() - 1;
1742                Ok(self
1743                    .get_node_mut_at_path_or_error(&arg_path[0..index_last])?
1744                    .pop_node_at_key_and_promote_its_children(
1745                        arg_path[index_last],
1746                        arg_collision_suffix,
1747                    )?)
1748            }
1749        }
1750    }
1751
1752    /// Returns the node stored at the key; the tree will relinquish ownership of this node
1753    /// # Arguments
1754    /// * arg_key: A key of type &str used to identify a child node
1755    // Test: test_pop_node_at_key()
1756    pub fn pop_node_at_key(&mut self, arg_key: &str) -> Option<Node> {
1757        Some(self.field_hash_map_children.remove(&arg_key.to_string())?)
1758    }
1759
1760    /// Returns the node stored at the path; the tree will relinquish ownership of this node
1761    /// # Arguments
1762    /// * arg_path: Slice of &str keys which is use to navigate from the node of origin to the descendant node
1763    // Test: test_pop_node_at_key()
1764    pub fn pop_node_at_path(&mut self, arg_path: &[&str]) -> Option<Node> {
1765        match arg_path.len() {
1766            0 => return None,
1767            1 => return self.pop_node_at_key(arg_path[0]),
1768            _ => {
1769                let mut node_current = self;
1770                for item_key in &arg_path[0..arg_path.len() - 1] {
1771                    node_current = node_current
1772                        .field_hash_map_children
1773                        .get_mut(&item_key.to_string())?;
1774                }
1775                Some(
1776                    node_current
1777                        .field_hash_map_children
1778                        .remove(&arg_path[arg_path.len() - 1].to_string())?,
1779                )
1780            }
1781        }
1782    }
1783
1784    /// Returns the node stored at the path; the tree will relinquish ownership of this node
1785    /// If the path fails, then the function will return an error message explaining where the path failed
1786    /// # Arguments
1787    /// * arg_path: Slice of &str keys which is use to navigate from the node of origin to the descendant node
1788    pub fn pop_node_at_path_or_error(&mut self, arg_path: &[&str]) -> Result<Node, String> {
1789        match arg_path.len() {
1790            0 => return Err("Error: arg_path is empty.".to_string()),
1791            1 => {
1792                if let Some(node) = self.pop_node_at_key(arg_path[0]) {
1793                    return Ok(node);
1794                } else {
1795                    return Err([
1796                        "Error: arg_path not found.".to_string(),
1797                        format!("arg_path = {:?}", arg_path),
1798                    ]
1799                    .join("\n"));
1800                }
1801            }
1802            _ => {
1803                let mut vec_path_existing = Vec::new();
1804                let mut node_current = self;
1805                for item_key in &arg_path[0..arg_path.len() - 1] {
1806                    if let Some(node_sub) = node_current
1807                        .field_hash_map_children
1808                        .get_mut(&item_key.to_string())
1809                    {
1810                        vec_path_existing.push(*item_key);
1811                        node_current = node_sub
1812                    } else {
1813                        return Err(Node::raise_error_because_path_failed(
1814                            item_key,
1815                            arg_path,
1816                            &vec_path_existing,
1817                        ));
1818                    }
1819                }
1820                if let Some(node_popped) = node_current
1821                    .field_hash_map_children
1822                    .remove(arg_path[arg_path.len() - 1])
1823                {
1824                    Ok(node_popped)
1825                } else {
1826                    Err([
1827                        "Error: Failed to remove node at path.".to_string(),
1828                        format!("arg_path = {:?}", arg_path,),
1829                        format!("part of path that exists = {:?}", vec_path_existing,),
1830                    ]
1831                    .join("\n"))
1832                }
1833            }
1834        }
1835    }
1836    //
1837    // Public - raise
1838    //
1839    /// Returns error in all cases when called
1840    // No test needed, this is just a basic message
1841    fn raise_error_because_path_failed(
1842        arg_key_at_failure: &str,
1843        arg_path: &[&str],
1844        arg_vec_path_that_exists: &Vec<&str>,
1845    ) -> String {
1846        return [
1847            "Error: Path doesn't exist.".to_string(),
1848            format!("key at failure = {}", arg_key_at_failure),
1849            format!("path = {:?}", arg_path,),
1850            format!("existing path component = {:?}", arg_vec_path_that_exists),
1851        ]
1852        .join("\n");
1853    }
1854
1855    /// Returns an error if string is invalid
1856    // No test needed, this is a basic test
1857    pub fn raise_error_if_key_is_invalid(arg_key: &str) -> Result<(), String> {
1858        if arg_key.is_empty() {
1859            return Err("Error: arg_key is empty.".to_string());
1860        }
1861        Ok(())
1862    }
1863
1864    /// Returns an error if the path is invalid; otherwise it returns ()
1865    /// See is_path_valid() for criteria
1866    // Test: test_raise_error_if_path_is_invalid()
1867    pub fn raise_error_if_path_is_invalid(arg_path: &[&str]) -> Result<(), String> {
1868        if arg_path.is_empty() {
1869            return Err(["Error: arg_path is empty.".to_string()].join("\n"));
1870        }
1871        for item_key in arg_path {
1872            if item_key.is_empty() {
1873                return Err([
1874                    "Error: Empty items detected in arg_path.".to_string(),
1875                    format!("arg_path = {:?}", arg_path),
1876                ]
1877                .join("\n"));
1878            }
1879        }
1880        Ok(())
1881    }
1882    //
1883    // Privates
1884    //
1885    // Short-cut function for quickly replicating a vec and adding the latest key to it
1886    fn get_path_with_appended_key<'l>(
1887        arg_path: &Vec<&'l String>,
1888        arg_key: &'l String,
1889    ) -> Vec<&'l String> {
1890        let mut path_to_return = arg_path.to_vec();
1891        path_to_return.push(arg_key);
1892        path_to_return
1893    }
1894    // Sort functions...
1895    // - Each of these do a single pass of converting paths into strings, and then sorts them based on that
1896    // - When the sort finishes, the original layout is rebuilt and returned
1897    // - To keep the memory use low, this method *takes ownership* of the argument and does the sort on the data directly
1898    // - These are private since they 'move' data, rather than copy it
1899    //
1900    fn get_vec_of_pairs_paths_and_generics_sorted<T>(
1901        arg_vec_of_pairs: Vec<(Vec<String>, &T)>,
1902    ) -> Vec<(Vec<String>, &T)> {
1903        let mut vec_to_return = arg_vec_of_pairs
1904            .into_iter()
1905            .map(|(item_path, item_t)| (item_path.join("\n"), item_path, item_t))
1906            .collect::<Vec<(String, Vec<String>, &T)>>();
1907        vec_to_return.sort_by(
1908            |(item_string_left, _item_vec_left, _item_t_left),
1909             (item_string_right, _item_vec_right, _item_t_right)| {
1910                item_string_left.cmp(item_string_right)
1911            },
1912        );
1913        vec_to_return
1914            .into_iter()
1915            .map(|(_item_string, item_path, item_t)| (item_path, item_t))
1916            .collect()
1917    }
1918
1919    fn get_vec_of_paths_sorted(arg_vec_of_paths: Vec<Vec<String>>) -> Vec<Vec<String>> {
1920        let mut vec_to_sort = arg_vec_of_paths
1921            .into_iter()
1922            .map(|item| (item.join("."), item))
1923            .collect::<Vec<(String, Vec<String>)>>();
1924        vec_to_sort.sort_by(
1925            |(item_string_left, _item_vec_left), (item_string_right, _item_vec_right)| {
1926                item_string_left.cmp(item_string_right)
1927            },
1928        );
1929        vec_to_sort
1930            .into_iter()
1931            .map(|(_item_string, item_path)| item_path)
1932            .collect()
1933    }
1934    //
1935    // Setup
1936    //
1937    /// Get new node instance
1938    pub fn new() -> Self {
1939        return Self {
1940            field_string_data: "".to_string(),
1941            field_hash_map_children: HashMap::new(),
1942        };
1943    }
1944}