tree_ds/node/mod.rs
1use core::cmp::Ordering;
2
3#[cfg(feature = "async")]
4use crate::lib::Arc;
5#[cfg(not(feature = "async"))]
6use crate::lib::Rc;
7use crate::lib::*;
8
9#[cfg(feature = "auto_id")]
10mod auto_id;
11#[cfg(feature = "serde")]
12mod serde;
13
14/// A node in a tree.
15///
16/// This struct represents a node in a tree. The node has a unique id, a value, children and a parent. The unique id
17/// is used to identify the node. The value is the value of the node. The children are the children of the node and
18/// the parent is the parent of the node.
19///
20/// # Type Parameters
21///
22/// * `Q` - The type of the unique id of the node. Odd, I know but this is for flexibility. Some people might want to use
23/// a string as the unique id of the node. Others might want to use an integer. This is why the unique id is a generic type.
24/// * `T` - The type of the value of the node.
25///
26/// # Fields
27///
28/// * `node_id` - The unique id of the node.
29/// * `value` - The value of the node.
30/// * `children` - The children of the node.
31/// * `parent` - The parent of the node.
32///
33/// # Example
34///
35/// ```rust
36/// # use tree_ds::prelude::Node;
37///
38/// let node: Node<i32, i32> = Node::new(1, Some(2));
39/// ```
40#[cfg(not(feature = "async"))]
41#[derive(Clone, Debug, Eq)]
42pub struct Node<Q, T>(Rc<RefCell<_Node<Q, T>>>)
43where
44 Q: PartialEq + Eq + Clone,
45 T: PartialEq + Eq + Clone;
46
47/// A node in a tree.
48///
49/// This struct represents a node in a tree. The node has a unique id, a value, children and a parent. The unique id
50/// is used to identify the node. The value is the value of the node. The children are the children of the node and
51/// the parent is the parent of the node.
52///
53/// # Type Parameters
54///
55/// * `Q` - The type of the unique id of the node. Odd, I know but this is for flexibility. Some people might want to use a string as the unique id of the node. Others might want to use an integer. This is why the unique id is a generic type.
56/// * `T` - The type of the value of the node.
57///
58/// # Fields
59///
60/// * `node_id` - The unique id of the node.
61/// * `value` - The value of the node.
62/// * `children` - The children of the node.
63/// * `parent` - The parent of the node.
64///
65/// # Example
66///
67/// ```rust
68/// # use tree_ds::prelude::Node;
69///
70/// let node: Node<i32, i32> = Node::new(1, Some(2));
71/// ```
72#[cfg(feature = "async")]
73#[derive(Clone, Debug, Eq)]
74pub struct Node<Q, T>(Arc<RefCell<_Node<Q, T>>>)
75where
76 Q: PartialEq + Eq + Clone,
77 T: PartialEq + Eq + Clone;
78
79impl<Q, T> Node<Q, T>
80where
81 Q: PartialEq + Eq + Clone,
82 T: PartialEq + Eq + Clone,
83{
84 /// Create a new node.
85 ///
86 /// This method creates a new node with the given node id and value. The node id is used to identify the node
87 /// and the value is the value of the node. The value can be used to store any data that you want to associate
88 /// with the node.
89 ///
90 /// # Arguments
91 ///
92 /// * `node_id` - The id of the node.
93 /// * `value` - The value of the node.
94 ///
95 /// # Returns
96 ///
97 /// A new node with the given node id and value.
98 ///
99 /// # Example
100 ///
101 /// ```rust
102 /// # use tree_ds::prelude::Node;
103 ///
104 /// let node = Node::new(1, Some(2));
105 /// ```
106 pub fn new(node_id: Q, value: Option<T>) -> Self {
107 #[cfg(not(feature = "async"))]
108 {
109 Node(Rc::new(RefCell::new(_Node {
110 node_id,
111 value,
112 children: vec![],
113 parent: None,
114 })))
115 }
116 #[cfg(feature = "async")]
117 {
118 Node(Arc::new(RefCell::new(_Node {
119 node_id,
120 value,
121 children: vec![],
122 parent: None,
123 })))
124 }
125 }
126
127 /// Add a child to the node.
128 ///
129 /// This method adds a child to the node. The child is added to the children of the node and the parent
130 /// of the child is set to the node.
131 ///
132 /// # Arguments
133 ///
134 /// * `child` - The child to add to the node.
135 ///
136 /// # Example
137 ///
138 /// ```rust
139 /// # use tree_ds::prelude::Node;
140 ///
141 /// let parent_node = Node::new(1, Some(2));
142 /// parent_node.add_child(Node::new(2, Some(3)));
143 /// ```
144 pub fn add_child(&self, child: Node<Q, T>) {
145 {
146 // This block is to ensure that the borrow_mut() is dropped before the next borrow_mut() call.
147 let mut node = self.0.borrow_mut();
148 node.children.push(child.get_node_id());
149 }
150 let mut child = child.0.borrow_mut();
151 child.parent = Some(self.get_node_id());
152 }
153
154 /// Remove a child from the node.
155 ///
156 /// This method removes a child from the node. The child is removed from the children of the node and the parent
157 /// of the child is set to `None`.
158 /// The reason as to why we pass the child as an argument instead of the node id is because we want to ensure that the
159 /// parent of the child is set to `None` when the child is removed from this parent. If we were to pass the node id
160 /// of the child as an argument, we would have to get the child from the tree and then set the parent to `None`. And
161 /// at this level we have no knowledge of the tree.
162 ///
163 /// # Arguments
164 ///
165 /// * `child` - The child to remove from the node.
166 ///
167 /// # Example
168 ///
169 /// ```rust
170 /// # use tree_ds::prelude::Node;
171 ///
172 /// let parent_node = Node::new(1, Some(2));
173 /// let child_node = Node::new(2, Some(3));
174 /// parent_node.add_child(child_node.clone());
175 /// parent_node.remove_child(child_node);
176 /// ```
177 pub fn remove_child(&self, child: Node<Q, T>) {
178 let mut node = self.0.borrow_mut();
179 node.children.retain(|x| x != &child.get_node_id());
180 let mut child = child.0.borrow_mut();
181 child.parent = None;
182 }
183
184 /// Get the unique Id of the node.
185 ///
186 /// This method returns the unique Id of the node. The unique Id is used to identify the node.
187 ///
188 /// # Returns
189 ///
190 /// The unique Id of the node.
191 ///
192 /// # Example
193 ///
194 /// ```rust
195 /// # use tree_ds::prelude::Node;
196 ///
197 /// let node = Node::new(1, Some(2));
198 /// assert_eq!(node.get_node_id(), 1);
199 /// ```
200 pub fn get_node_id(&self) -> Q {
201 self.0.borrow().node_id.clone()
202 }
203
204 /// Get the ids of the children of the node.
205 ///
206 /// This method returns the ids of the children of the node.
207 ///
208 /// # Returns
209 ///
210 /// The ids of the children of the node.
211 ///
212 /// # Example
213 ///
214 /// ```rust
215 /// # use tree_ds::prelude::Node;
216 ///
217 /// let node = Node::new(1, Some(2));
218 /// let child = Node::new(2, Some(3));
219 /// node.add_child(child);
220 /// assert_eq!(node.get_children_ids().len(), 1);
221 /// ```
222 pub fn get_children_ids(&self) -> Vec<Q> {
223 self.0.borrow().children.clone()
224 }
225
226 /// Get the node id of the parent of the node.
227 ///
228 /// This method returns the node_id of the parent of the node. In the case where the node is a root node in a tree,
229 /// the parent of the node will be `None`.
230 ///
231 /// # Returns
232 ///
233 /// The optional node_id of the parent of the node.
234 ///
235 /// # Example
236 ///
237 /// ```rust
238 /// # use tree_ds::prelude::Node;
239 ///
240 /// let parent_node = Node::new(1, Some(2));
241 /// let child_node = Node::new(2, Some(3));
242 /// parent_node.add_child(child_node.clone());
243 /// assert_eq!(child_node.get_parent_id().as_ref(), Some(&parent_node.get_node_id()));
244 /// assert!(parent_node.get_parent_id().is_none());
245 /// ```
246 pub fn get_parent_id(&self) -> Option<Q> {
247 self.0.borrow().parent.clone()
248 }
249
250 /// Get the value of the node.
251 ///
252 /// This method returns the value of the node. If the node has no value, `None` is returned.
253 ///
254 /// # Returns
255 ///
256 /// The value of the node.
257 ///
258 /// # Example
259 ///
260 /// ```rust
261 /// # use tree_ds::prelude::Node;
262 ///
263 /// let node = Node::new(1, Some(2));
264 /// assert_eq!(node.get_value(), Some(2));
265 /// ```
266 pub fn get_value(&self) -> Option<T> {
267 self.0.borrow().value.clone()
268 }
269
270 /// Set the value of the node.
271 ///
272 /// This method sets the value of the node.
273 ///
274 /// # Arguments
275 ///
276 /// * `value` - The value to set.
277 ///
278 /// # Example
279 ///
280 /// ```rust
281 /// # use tree_ds::prelude::Node;
282 ///
283 /// let node = Node::new(1, Some(2));
284 /// assert_eq!(node.get_value(), Some(2));
285 /// node.set_value(Some(3));
286 /// assert_eq!(node.get_value(), Some(3));
287 /// ```
288 pub fn set_value(&self, value: Option<T>) {
289 self.0.borrow_mut().value = value;
290 }
291
292 /// Update the value of the node.
293 ///
294 /// This method updates the value of the node using a closure.
295 ///
296 /// # Arguments
297 ///
298 /// * `modifier` - The closure to use for updating the value.
299 ///
300 /// # Example
301 ///
302 /// ```rust
303 /// # use tree_ds::prelude::Node;
304 ///
305 /// let node = Node::new(1, Some(2));
306 /// node.update_value(|value| *value = Some(3));
307 /// assert_eq!(node.get_value(), Some(3));
308 /// ```
309 pub fn update_value(&self, modifier: impl FnOnce(&mut Option<T>)) {
310 let mut node = self.0.borrow_mut();
311 modifier(&mut node.value);
312 }
313
314 /// Set the parent of the node.
315 ///
316 /// This method sets the parent of the node.
317 ///
318 /// # Arguments
319 ///
320 /// * `parent` - The parent to set.
321 ///
322 /// # Example
323 ///
324 /// ```rust
325 /// # use tree_ds::prelude::Node;
326 ///
327 /// let parent_node = Node::new(1, Some(2));
328 /// let child_node = Node::new(2, Some(3));
329 /// child_node.set_parent(Some(parent_node.clone()));
330 /// assert_eq!(child_node.get_parent_id().as_ref(), Some(&parent_node.get_node_id()));
331 /// ```
332 pub fn set_parent(&self, parent: Option<Node<Q, T>>) {
333 if let Some(parent) = parent.as_ref() {
334 parent.add_child(self.clone());
335 }
336 self.0.borrow_mut().parent = parent.map(|x| x.get_node_id());
337 }
338
339 /// Sort the children of the node by an ordering closure.
340 ///
341 /// # Arguments
342 ///
343 /// * `compare` - The closure to use for comparison.
344 ///
345 /// # Example
346 ///
347 /// ```rust
348 /// # use tree_ds::prelude::Node;
349 ///
350 /// let parent_node = Node::new(1, Some(2));
351 /// let child1 = Node::new(2, Some(3));
352 /// let child2 = Node::new(3, Some(4));
353 /// parent_node.add_child(child1);
354 /// parent_node.add_child(child2);
355 ///
356 /// parent_node.sort_children(|a, b| a.cmp(&b).reverse());
357 /// assert_eq!(parent_node.get_children_ids(), vec![3, 2]);
358 /// ```
359 pub fn sort_children(&self, compare: impl Fn(&Q, &Q) -> Ordering)
360 where
361 Q: Debug,
362 {
363 let mut children = self.0.borrow().children.clone();
364 children.sort_by(|a, b| compare(a, b));
365 self.update_children(children);
366 }
367
368 fn update_children(&self, update: impl AsRef<[Q]>) {
369 let children = &mut self.0.borrow_mut().children;
370 children.clear();
371 children.extend_from_slice(update.as_ref());
372 }
373}
374
375impl<Q, T> PartialEq for Node<Q, T>
376where
377 Q: PartialEq + Eq + Clone,
378 T: PartialEq + Eq + Clone,
379{
380 /// Compare two nodes for equality.
381 fn eq(&self, other: &Self) -> bool {
382 self.get_node_id() == other.get_node_id() && self.get_value() == other.get_value()
383 }
384}
385
386impl<Q, T> Display for Node<Q, T>
387where
388 Q: PartialEq + Eq + Clone + Display,
389 T: PartialEq + Eq + Clone + Display + Default,
390{
391 /// Display the node.
392 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
393 #[cfg(feature = "print_node_id")]
394 return write!(
395 f,
396 "{}: {}",
397 self.get_node_id(),
398 self.get_value().as_ref().cloned().unwrap_or_default()
399 );
400 #[cfg(not(feature = "print_node_id"))]
401 return write!(
402 f,
403 "{}",
404 self.get_value().as_ref().cloned().unwrap_or_default()
405 );
406 }
407}
408
409impl<Q, T> Hash for Node<Q, T>
410where
411 Q: PartialEq + Eq + Clone + Hash,
412 T: PartialEq + Eq + Clone + Hash,
413{
414 /// Hash the node.
415 fn hash<H: Hasher>(&self, state: &mut H) {
416 self.get_node_id().hash(state);
417 self.get_value().hash(state);
418 self.get_children_ids().hash(state);
419 self.get_parent_id().hash(state);
420 }
421}
422
423#[doc(hidden)]
424#[derive(Clone, Debug, PartialEq, Eq)]
425pub(crate) struct _Node<Q, T>
426where
427 Q: PartialEq + Eq + Clone,
428 T: PartialEq + Eq + Clone,
429{
430 /// The user supplied id of the node.
431 node_id: Q,
432 /// The value of the node.
433 value: Option<T>,
434 /// The children of the node.
435 children: Vec<Q>,
436 /// The parent of the node.
437 parent: Option<Q>,
438}
439
440/// An iterator over the nodes in a tree.
441///
442/// This struct represents an iterator over the nodes in a tree. The iterator is created by calling the `iter` method
443/// on the tree. The iterator yields the nodes in the tree in the order that they were added to the tree.
444///
445/// # Type Parameters
446///
447/// * `Q` - The type of the unique id of the node.
448/// * `T` - The type of the value of the node.
449#[derive(Clone, Debug, PartialEq, Eq, Hash)]
450pub struct Nodes<Q, T>
451where
452 Q: PartialEq + Eq + Clone,
453 T: PartialEq + Eq + Clone {
454 nodes: Vec<Node<Q, T>>,
455 index: usize,
456}
457
458impl<Q, T> Nodes<Q, T>
459where
460 Q: PartialEq + Eq + Clone,
461 T: PartialEq + Eq + Clone,
462{
463 /// Create a new iterator over the nodes in a tree.
464 ///
465 /// This method creates a new iterator over the nodes in a tree.
466 ///
467 /// # Arguments
468 ///
469 /// * `nodes` - The nodes in the tree.
470 ///
471 /// # Returns
472 ///
473 /// A new iterator over the nodes in a tree.
474 ///
475 /// # Example
476 ///
477 /// ```rust
478 /// # use tree_ds::prelude::{Node, Nodes};
479 ///
480 /// let nodes = Nodes::new(vec![Node::new(1, Some(2))]);
481 /// ```
482 pub fn new(nodes: Vec<Node<Q, T>>) -> Self {
483 Nodes{
484 nodes,
485 index: 0
486 }
487 }
488
489 /// Get an iterator over the nodes in the tree.
490 ///
491 /// This method returns an iterator over the nodes in the tree.
492 ///
493 /// # Returns
494 ///
495 /// An iterator over the nodes in the tree.
496 ///
497 /// # Example
498 ///
499 /// ```rust
500 /// # use tree_ds::prelude::{Node, Nodes};
501 ///
502 /// let nodes = Nodes::new(vec![Node::new(1, Some(2))]);
503 ///
504 /// for node in nodes.iter() {
505 /// // Do something with the node.
506 /// }
507 /// ```
508 pub fn iter(&self) -> Iter<Node<Q, T>> {
509 self.nodes.iter()
510 }
511
512 /// Get the number of nodes in the tree.
513 ///
514 /// This method returns the number of nodes in the tree.
515 ///
516 /// # Returns
517 ///
518 /// The number of nodes in the tree.
519 ///
520 /// # Example
521 ///
522 /// ```rust
523 /// # use tree_ds::prelude::{Node, Nodes};
524 ///
525 /// let nodes = Nodes::new(vec![Node::new(1, Some(2))]);
526 /// assert_eq!(nodes.len(), 1);
527 /// ```
528 pub fn len(&self) -> usize {
529 self.nodes.len()
530 }
531
532 /// Check if the tree is empty.
533 ///
534 /// This method checks if the tree is empty.
535 ///
536 /// # Returns
537 ///
538 /// `true` if the tree is empty, `false` otherwise.
539 pub fn is_empty(&self) -> bool {
540 self.nodes.is_empty()
541 }
542
543 /// Get a node at the specified index.
544 ///
545 /// This method returns a node at the specified index.
546 ///
547 /// # Arguments
548 ///
549 /// * `index` - The index of the node to get.
550 ///
551 /// # Returns
552 ///
553 /// The node at the specified index.
554 ///
555 /// # Example
556 ///
557 /// ```rust
558 /// # use tree_ds::prelude::{Node, Nodes};
559 ///
560 /// let nodes = Nodes::new(vec![Node::new(1, Some(2))]);
561 /// assert_eq!(nodes.get(0).unwrap().get_node_id(), 1);
562 /// ```
563 pub fn get(&self, index: usize) -> Option<&Node<Q, T>> {
564 self.nodes.get(index)
565 }
566
567 /// Get a node by the node id.
568 ///
569 /// This method returns a node by the node id.
570 ///
571 /// # Arguments
572 ///
573 /// * `node_id` - The node id of the node to get.
574 ///
575 /// # Returns
576 ///
577 /// The node with the specified node id.
578 ///
579 /// # Example
580 ///
581 /// ```rust
582 /// # use tree_ds::prelude::{Node, Nodes};
583 ///
584 /// let nodes = Nodes::new(vec![Node::new(1, Some(2))]);
585 /// assert_eq!(nodes.get_by_node_id(&1).unwrap().get_node_id(), 1);
586 /// ```
587 pub fn get_by_node_id(&self, node_id: &Q) -> Option<&Node<Q, T>> {
588 self.nodes.iter().find(|x| &x.get_node_id() == node_id)
589 }
590
591 /// Push a node to the nodes list.
592 ///
593 /// This method pushes a node to the nodes list.
594 ///
595 /// # Arguments
596 ///
597 /// * `node` - The node to push.
598 ///
599 /// # Example
600 ///
601 /// ```rust
602 /// # use tree_ds::prelude::{Node, Nodes};
603 ///
604 /// let mut nodes = Nodes::new(vec![Node::new(1, Some(2))]);
605 /// nodes.push(Node::new(2, Some(3)));
606 /// assert_eq!(nodes.len(), 2);
607 /// ```
608 pub fn push(&mut self, node: Node<Q, T>) {
609 self.nodes.push(node);
610 }
611
612 /// Remove a node at the specified index.
613 ///
614 /// This method removes a node at the specified index.
615 ///
616 /// # Arguments
617 ///
618 /// * `index` - The index of the node to remove.
619 ///
620 /// # Returns
621 ///
622 /// The removed node.
623 ///
624 /// # Example
625 ///
626 /// ```rust
627 /// # use tree_ds::prelude::{Node, Nodes};
628 ///
629 /// let mut nodes = Nodes::new(vec![Node::new(1, Some(2))]);
630 /// let removed_node = nodes.remove(0);
631 /// assert_eq!(removed_node.get_node_id(), 1);
632 /// assert_eq!(nodes.len(), 0);
633 /// ```
634 pub fn remove(&mut self, index: usize) -> Node<Q, T> {
635 self.nodes.remove(index)
636 }
637
638 /// Retain only the nodes that satisfy the predicate.
639 ///
640 /// This method retains only the nodes that satisfy the predicate.
641 /// The predicate is a function that takes a node and returns a boolean value.
642 /// If the predicate returns `true`, the node is retained. If the predicate returns `false`, the node is removed.
643 /// The nodes are retained in the order that they were added to the tree.
644 ///
645 /// # Arguments
646 ///
647 /// * `f` - The predicate function.
648 ///
649 /// # Example
650 ///
651 /// ```rust
652 /// # use tree_ds::prelude::{Node, Nodes};
653 ///
654 /// let mut nodes = Nodes::new(vec![Node::new(1, Some(2)), Node::new(2, Some(3))]);
655 /// nodes.retain(|node| node.get_node_id() == 1);
656 /// assert_eq!(nodes.len(), 1);
657 /// ```
658 pub fn retain<F>(&mut self, f: F)
659 where
660 F: FnMut(&Node<Q, T>) -> bool,
661 {
662 self.nodes.retain(f);
663 }
664
665 /// Clear the nodes list.
666 ///
667 /// This method clears the nodes list.
668 ///
669 /// # Example
670 ///
671 /// ```rust
672 /// # use tree_ds::prelude::{Node, Nodes};
673 ///
674 /// let mut nodes = Nodes::new(vec![Node::new(1, Some(2)), Node::new(2, Some(3))]);
675 /// nodes.clear();
676 /// assert_eq!(nodes.len(), 0);
677 /// ```
678 pub fn clear(&mut self) {
679 self.nodes.clear();
680 }
681
682 /// Append the nodes from another nodes list.
683 ///
684 /// This method appends the nodes from another nodes list.
685 ///
686 /// # Arguments
687 ///
688 /// * `other` - The other nodes list.
689 ///
690 /// # Example
691 ///
692 /// ```rust
693 /// # use tree_ds::prelude::{Node, Nodes};
694 ///
695 /// let mut nodes = Nodes::new(vec![Node::new(1, Some(2))]);
696 /// let mut other_nodes = Nodes::new(vec![Node::new(2, Some(3))]);
697 /// nodes.append(&mut other_nodes);
698 /// assert_eq!(nodes.len(), 2);
699 /// ```
700 pub fn append(&mut self, other: &mut Self) {
701 self.nodes.append(&mut other.nodes);
702 }
703
704 /// Append the nodes from another nodes list.
705 ///
706 /// This method appends the nodes from another nodes list. This method is useful when you want
707 /// to append the nodes as a raw vector.
708 ///
709 /// # Arguments
710 ///
711 /// * `other` - The other nodes list.
712 ///
713 /// # Example
714 ///
715 /// ```rust
716 /// # use tree_ds::prelude::{Node, Nodes};
717 ///
718 /// let mut nodes = Nodes::new(vec![Node::new(1, Some(2))]);
719 /// let mut other_nodes = vec![Node::new(2, Some(3))];
720 /// nodes.append_raw(&mut other_nodes);
721 /// assert_eq!(nodes.len(), 2);
722 /// ```
723 pub fn append_raw(&mut self, other: &mut Vec<Node<Q, T>>) {
724 self.nodes.append(other);
725 }
726
727 /// Get the first node in the nodes list.
728 ///
729 /// This method returns the first node in the nodes list.
730 ///
731 /// # Returns
732 ///
733 /// The first node in the nodes list.
734 ///
735 /// # Example
736 ///
737 /// ```rust
738 /// # use tree_ds::prelude::{Node, Nodes};
739 ///
740 /// let nodes = Nodes::new(vec![Node::new(1, Some(2)), Node::new(2, Some(3))]);
741 /// assert_eq!(nodes.first().unwrap().get_node_id(), 1);
742 /// ```
743 pub fn first(&self) -> Option<&Node<Q, T>> {
744 self.nodes.first()
745 }
746}
747
748impl<Q, T> AsRef<Nodes<Q, T>> for Nodes<Q, T>
749where
750 Q: PartialEq + Eq + Clone,
751 T: PartialEq + Eq + Clone,
752{
753 /// Get a reference to the nodes list.
754 fn as_ref(&self) -> &Nodes<Q, T> {
755 self
756 }
757}
758
759impl<Q, T> FromIterator<Node<Q, T>> for Nodes<Q, T>
760where
761 Q: PartialEq + Eq + Clone,
762 T: PartialEq + Eq + Clone,
763{
764 /// Create a nodes list from an iterator.
765 fn from_iter<I: IntoIterator<Item = Node<Q, T>>>(iter: I) -> Self {
766 Nodes::new(iter.into_iter().collect())
767 }
768}
769
770impl<Q, T> Iterator for Nodes<Q, T>
771where
772 Q: PartialEq + Eq + Clone,
773 T: PartialEq + Eq + Clone,
774{
775 type Item = Node<Q, T>;
776
777 /// Get the next node in the nodes list.
778 #[allow(clippy::iter_next_slice)]
779 fn next(&mut self) -> Option<Self::Item> {
780 let node = self.nodes.get(self.index).cloned();
781 self.index += 1;
782 node
783 }
784
785 /// Get the size hint of the nodes list.
786 fn size_hint(&self) -> (usize, Option<usize>) {
787 self.nodes.iter().size_hint()
788 }
789}
790
791impl<Q, T> Default for Nodes<Q, T>
792where
793 Q: PartialEq + Eq + Clone,
794 T: PartialEq + Eq + Clone,
795{
796 /// Create an empty nodes list.
797 fn default() -> Self {
798 Nodes::new(vec![])
799 }
800}
801
802impl<Q, T> Display for Nodes<Q, T>
803where
804 Q: PartialEq + Eq + Clone + Display,
805 T: PartialEq + Eq + Clone + Display + Default,
806{
807 /// Display the nodes list.
808 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
809 for node in self.iter() {
810 write!(f, "{}", node)?;
811 }
812 Ok(())
813 }
814}
815
816#[cfg(test)]
817mod tests {
818 use crate::lib::*;
819
820 use super::*;
821
822 #[test]
823 fn test_node_new() {
824 let node = Node::new(1, Some(2));
825 assert_eq!(node.get_node_id(), 1);
826 assert_eq!(node.get_value(), Some(2));
827 assert_eq!(node.get_children_ids().len(), 0);
828 assert!(node.get_parent_id().is_none());
829 }
830
831 #[test]
832 fn test_node_adding_children() {
833 let node = Node::new(1, Some(2));
834 let child = Node::new(2, Some(3));
835 node.add_child(child);
836 assert_eq!(node.get_children_ids().len(), 1);
837 }
838
839 #[test]
840 fn test_node_get_node_id() {
841 let node = Node::new(1, Some(2));
842 assert_eq!(node.get_node_id(), 1);
843 }
844
845 #[test]
846 fn test_node_get_parent() {
847 let parent_node = Node::new(1, Some(2));
848 let child_node = Node::new(2, Some(3));
849 parent_node.add_child(child_node.clone());
850 assert_eq!(
851 child_node.get_parent_id().as_ref(),
852 Some(&parent_node.get_node_id())
853 );
854 assert!(parent_node.get_parent_id().is_none());
855 }
856
857 #[test]
858 fn test_node_get_value() {
859 let node = Node::new(1, Some(2));
860 assert_eq!(node.get_value(), Some(2));
861 }
862
863 #[test]
864 fn test_node_set_value() {
865 let node = Node::new(1, Some(2));
866 assert_eq!(node.get_value(), Some(2));
867 node.set_value(Some(3));
868 assert_eq!(node.get_value(), Some(3));
869 }
870
871 #[test]
872 fn test_node_set_parent() {
873 let parent_node = Node::new(1, Some(2));
874 let child_node = Node::new(2, Some(3));
875 child_node.set_parent(Some(parent_node.clone()));
876 assert_eq!(
877 child_node.get_parent_id().as_ref(),
878 Some(&parent_node.get_node_id())
879 );
880 }
881
882 #[test]
883 fn test_node_remove_child() {
884 let parent_node = Node::new(1, Some(2));
885 let child_node = Node::new(2, Some(3));
886 parent_node.add_child(child_node.clone());
887 parent_node.remove_child(child_node);
888 assert_eq!(parent_node.get_children_ids().len(), 0);
889 }
890
891 #[test]
892 fn test_node_update_value() {
893 let node = Node::new(1, Some(2));
894 node.update_value(|value| *value = value.map(|x| x + 1));
895 assert_eq!(node.get_value(), Some(3));
896 }
897
898 #[test]
899 fn test_node_eq() {
900 let node1 = Node::new(1, Some(2));
901 let node2 = Node::new(1, Some(2));
902 assert_eq!(node1, node2);
903 }
904
905 #[test]
906 #[cfg_attr(not(feature = "print_node_id"), ignore)]
907 fn test_node_display_with_id() {
908 let node = Node::new(1, Some(2));
909 assert_eq!(format!("{}", node), "1: 2");
910 }
911
912 #[test]
913 #[cfg_attr(feature = "print_node_id", ignore)]
914 fn test_node_display_without_id() {
915 let node = Node::new(1, Some(2));
916 assert_eq!(format!("{}", node), "2");
917 }
918
919 #[test]
920 fn test_nodes() {
921 let nodes = Nodes::new(vec![Node::new(1, Some(2))]);
922 assert_eq!(nodes.len(), 1);
923 }
924
925 #[test]
926 fn test_nodes_len() {
927 let nodes = Nodes::new(vec![Node::new(1, Some(2))]);
928 assert_eq!(nodes.len(), 1);
929 }
930
931 #[test]
932 fn test_nodes_is_empty() {
933 let nodes: Nodes<i32, String> = Nodes::default();
934 assert!(nodes.is_empty());
935 }
936
937 #[test]
938 fn test_nodes_get() {
939 let nodes = Nodes::new(vec![Node::new(1, Some(2))]);
940 assert_eq!(nodes.get(0).unwrap().get_node_id(), 1);
941 }
942
943 #[test]
944 fn test_nodes_get_by_node_id() {
945 let nodes = Nodes::new(vec![Node::new(1, Some(2))]);
946 assert_eq!(nodes.get_by_node_id(&1).unwrap().get_node_id(), 1);
947 }
948
949 #[test]
950 fn test_nodes_push() {
951 let mut nodes = Nodes::new(vec![Node::new(1, Some(2))]);
952 nodes.push(Node::new(2, Some(3)));
953 assert_eq!(nodes.len(), 2);
954 }
955
956 #[test]
957 fn test_nodes_remove() {
958 let mut nodes = Nodes::new(vec![Node::new(1, Some(2))]);
959 let removed_node = nodes.remove(0);
960 assert_eq!(removed_node.get_node_id(), 1);
961 assert_eq!(nodes.len(), 0);
962 }
963
964 #[test]
965 fn test_nodes_retain() {
966 let mut nodes = Nodes::new(vec![Node::new(1, Some(2)), Node::new(2, Some(3))]);
967 nodes.retain(|node| node.get_node_id() == 1);
968 assert_eq!(nodes.len(), 1);
969 }
970
971 #[test]
972 fn test_nodes_clear() {
973 let mut nodes = Nodes::new(vec![Node::new(1, Some(2)), Node::new(2, Some(3))]);
974 nodes.clear();
975 assert_eq!(nodes.len(), 0);
976 }
977
978 #[test]
979 fn test_nodes_append() {
980 let mut nodes = Nodes::new(vec![Node::new(1, Some(2))]);
981 let mut other_nodes = Nodes::new(vec![Node::new(2, Some(3))]);
982 nodes.append(&mut other_nodes);
983 assert_eq!(nodes.len(), 2);
984 }
985
986 #[test]
987 fn test_nodes_append_raw() {
988 let mut nodes = Nodes::new(vec![Node::new(1, Some(2))]);
989 let mut other_nodes = vec![Node::new(2, Some(3))];
990 nodes.append_raw(&mut other_nodes);
991 assert_eq!(nodes.len(), 2);
992 }
993
994 #[test]
995 fn test_nodes_first() {
996 let nodes = Nodes::new(vec![Node::new(1, Some(2)), Node::new(2, Some(3))]);
997 assert_eq!(nodes.first().unwrap().get_node_id(), 1);
998 }
999
1000 #[test]
1001 fn test_nodes_default() {
1002 let nodes: Nodes<i32, String> = Nodes::default();
1003 assert!(nodes.is_empty());
1004 }
1005
1006 #[test]
1007 fn test_nodes_from_iter() {
1008 let nodes = Nodes::from_iter(vec![Node::new(1, Some(2))]);
1009 assert_eq!(nodes.len(), 1);
1010 }
1011
1012 #[test]
1013 fn test_nodes_iterator() {
1014 let nodes = Nodes::new(vec![Node::new(1, Some(2)), Node::new(2, Some(3))]);
1015 let mut iter = nodes.iter();
1016 assert_eq!(iter.next().unwrap().get_node_id(), 1);
1017 assert_eq!(iter.next().unwrap().get_node_id(), 2);
1018 }
1019
1020 #[test]
1021 fn test_nodes_next() {
1022 let mut nodes = Nodes::new(vec![Node::new(1, Some(2)), Node::new(2, Some(3))]);
1023 assert_eq!(nodes.next().unwrap().get_node_id(), 1);
1024 assert_eq!(nodes.next().unwrap().get_node_id(), 2);
1025 }
1026
1027 #[test]
1028 fn test_nodes_size_hint() {
1029 let nodes = Nodes::new(vec![Node::new(1, Some(2))]);
1030 let (lower, upper) = nodes.size_hint();
1031 assert_eq!(lower, 1);
1032 assert_eq!(upper, Some(1));
1033 }
1034
1035 #[test]
1036 fn test_nodes_as_ref() {
1037 let nodes = Nodes::new(vec![Node::new(1, Some(2))]);
1038 assert_eq!(nodes.as_ref().len(), 1);
1039 }
1040
1041 #[test]
1042 fn test_nodes_eq() {
1043 let nodes1 = Nodes::new(vec![Node::new(1, Some(2))]);
1044 let nodes2 = Nodes::new(vec![Node::new(1, Some(2))]);
1045 assert_eq!(nodes1, nodes2);
1046 }
1047
1048 #[test]
1049 fn test_nodes_display() {
1050 let nodes = Nodes::new(vec![Node::new(1, Some(2))]);
1051 #[cfg(feature = "print_node_id")]
1052 assert_eq!(format!("{}", nodes), "1: 2");
1053 #[cfg(not(feature = "print_node_id"))]
1054 assert_eq!(format!("{}", nodes), "2");
1055 }
1056}