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