Skip to main content

hedel_rs/
node.rs

1use std::{
2	rc::{
3		Weak,
4		Rc
5	}
6};
7
8use std::fmt::Debug;
9
10use crate::cell::{
11	HedelCell,
12	RefHedel,
13	RefMutHedel,
14};
15use crate::{
16	list::{
17		WeakList,
18		List
19	}
20};
21use crate::errors::HedelError;
22
23/// NodeInner contains pointers in both vertical and horizontal directions
24/// and a custom content field.
25#[derive(Debug, Clone)]
26pub struct NodeInner<T: Debug + Clone> {
27	pub next: Option<Node<T>>,
28	pub prev: Option<WeakNode<T>>,
29	pub child: Option<Node<T>>,
30	pub parent: Option<WeakNode<T>>,
31	pub list: Option<WeakList<T>>,
32	pub content: T
33}
34
35/// `Rc` is a strong pointer meaning it increment a reference counter.
36/// `Weak` is a weak pointer meaning it doesn't increment the reference counter,
37/// letting you access the value if it still exists in memory,
38/// modify it as its pointing to `HedelCell`,
39/// but without holding it in memory any longer.
40/// Necessary to avoid memory leaking.
41#[derive(Debug, Clone)]
42pub struct WeakNode<T: Debug + Clone> {
43	pub inner: Weak<HedelCell<NodeInner<T>>>
44}
45
46impl<T: Debug + Clone> WeakNode<T> {
47	/// upgrade `WeakNode` to `Node` if the `NodeInner` is still alive.
48	pub fn upgrade(&self) -> Option<Node<T>> {
49		Some(Node::<T> {
50			inner: self.inner.upgrade()?
51		})
52	}
53}
54
55/// Wraps the inner value with an Rc<HedelCell<_>> pointer.
56/// allowing for multiple owners and a mutable `NodeInner`
57#[derive(Debug)]
58pub struct Node<T: Debug + Clone > {
59	pub inner: Rc<HedelCell<NodeInner<T>>>,
60}
61
62impl<T: Debug + Clone> Clone for Node<T> {
63	fn clone(&self) -> Self {
64		Self {
65			inner: Rc::clone(&self.inner),
66		}
67	}
68}
69
70impl<T: Debug + Clone> Node<T> {
71	/// Default constructor. Notice how it builds a stand-alone node,
72	/// not pointing to any parent, any sibling and any child,
73	/// but owning the content
74	pub fn new(content: T) -> Self {
75		Self {
76			inner: Rc::new(HedelCell::new(NodeInner::<T> {
77				next: None,
78				prev: None,
79				child: None,
80				parent: None,
81				list: None,
82				content
83			})),
84		}
85	}
86
87	/// A `WeakNode` has to be built by downgrading `Node`
88	/// following the same logic to get a `Weak` from a `Rc`
89	pub fn downgrade(&self) -> WeakNode<T> {
90		WeakNode {
91			inner: Rc::downgrade(&self.inner)
92		}
93	}
94
95	/// Get access to `NodeInner` or return `HedelError` in case 
96	/// the runtime borrow checker in `HedelCell` doesn't allow to get a shared reference.
97	pub fn try_get(&self) -> Result<RefHedel<NodeInner<T>>, HedelError> {
98		Ok(self.inner.try_get()?)
99	}
100
101	/// Get access to `NodeInner` or panic! in case 
102	/// the runtime borrow checker in `HedelCell` doesn't allow to get a shared reference.
103	pub fn get(&self) -> RefHedel<NodeInner<T>> {
104		self.inner.get()
105	}
106
107	/// Get mutable access to `NodeInner` or return `HedelError` in case 
108	/// the runtime borrow checker in `HedelCell` doesn't allow to get a mutable reference.
109	pub fn try_get_mut(&self) -> RefMutHedel<'_, NodeInner<T>> {
110		self.inner.get_mut()
111	}
112
113	/// Get mutable access to `NodeInner` or panic! in case 
114	/// the runtime borrow checker in `HedelCell` doesn't allow to get a mutable reference.
115	pub fn get_mut(&self) -> RefMutHedel<'_, NodeInner<T>> {
116		self.inner.get_mut()
117	}
118
119	/// Get the next `Node` in horizontal direction
120	pub fn next(&self) -> Option<Node<T>> {
121		self.get().next.clone()	
122	}
123
124	/// Get the previous `Node` in horizontal direction by upgrading it.
125	pub fn prev(&self) -> Option<Node<T>> {
126		if let Some(ref p) = self.get().prev {
127			return p.upgrade()
128		} None
129	}
130
131	/// Get the parent `Node` in vertical direction by upgrading it.
132	pub fn parent(&self) -> Option<Node<T>> {
133		if let Some(ref p) = self.get().parent {
134			return p.upgrade();
135		} None
136	}
137
138	/// if currently under a NodeList, returns it.
139	pub fn list(&self) -> Option<List<T>> {	
140		if let Some(ref l) = self.get().list {
141			return Some(l.upgrade()?);
142		} None
143	}
144
145	/// Get the first child `Node` in vertical direction.
146	pub fn child(&self) -> Option<Node<T>> {
147		self.get().child.clone()
148	}
149	
150	pub fn to_content(self) -> T {
151		self.get().content.clone()	
152	}
153
154	/// Re-set the `parent`, `next` and `prev` fields on the `Node`.
155	/// WARNING: this is meant to be used by `NodeCollection::free` after 
156	/// the `HedelDetach::detach_preserve` function. Refer to it's documentation
157	/// for an usage example. 
158	///
159	/// If you want to detach a single Node while iterating, most of the times
160	/// you can simply break the loop and use `HedelDetach::detach`.
161	/// WARNING: using this function instead of `HedelDetach::detach` 
162	/// might break the linked list.
163	pub fn free(&self) {
164		let mut node = self.get_mut();
165		node.parent = None;
166		node.next = None;
167		node.prev = None;
168	}
169}
170
171/// Copy-free alternative to `Node::to_content`.
172///
173/// # Example
174///
175/// ```
176/// use hedel_rs::prelude::*;
177/// use hedel_rs::*;
178/// 
179/// fn main() {
180///		let node = node!(34);
181///		let c = 20;
182///		as_content!(&node, |num| {
183///			if num > c {
184///				println!("I am {}", num);
185///			}
186///		});
187/// }
188/// ```
189#[macro_export]
190macro_rules! as_content {
191	($self: expr, |$ident: ident| $cl: expr) => {
192		{
193			let $ident = $self.get().content;
194			$cl
195		}
196	}
197}
198
199pub trait DetachNode<T: Debug + Clone> {
200	fn detach(&self);
201	fn detach_preserve(&self, vec: &mut NodeCollection<T>);
202}
203
204impl<T: Debug + Clone> DetachNode<T> for Node<T> {
205	/// Detaches a single node from the linked list by fixing the pointers between the 
206	/// parent, the previous and next siblings. This also detaches all the children of the `Node`,
207	/// which will only remain linked with the node itself.
208	/// WARNING: This also re-sets the pointers in the node itself to None. 
209	/// So when you are detecting nodes in a linked-list and detaching them, you cant iterate over them using this method
210	/// as it would break the loop. Use `detach_preserve` instead.
211	fn detach(&self) {
212						// 1				3
213		let mut tuple: (Option<Node<T>>, Option<Node<T>>) = ( None, None );
214
215		if let Some(one) = self.prev() {
216			// 1,2,3
217			if let Some(three) = self.next() {
218				tuple = (Some(one), Some(three));
219			} else {
220				// 1,2
221				tuple = (Some(one), None);
222			}
223		} else {
224			// 2, 3
225			if let Some(three) = self.next() {
226				tuple = ( None, Some(three));
227			}
228		}
229		
230		match tuple {
231			(Some(one), Some(three)) => {
232				one.get_mut().next = Some(three.clone());
233				three.get_mut().prev = Some(one.downgrade());
234			},
235			(Some(one), None) => {
236				one.get_mut().next = None;
237			},
238			(None, Some(three)) => {
239				three.get_mut().prev = None;
240				if let Some(parent) = self.parent() {
241					parent.get_mut().child = Some(three.clone());
242				}
243			},
244			(None, None) => {
245				if let Some(parent) = self.parent() {
246					parent.get_mut().child = None;
247				}
248			}
249		}
250
251		self.free();
252	}
253	/// Detaches a single node from the linked list like `detach`, but doesn't re-set the pointers inside the Node.
254	/// This should only be used when you have to iterate over a linked list and detach some `Node`s.
255	/// You should create a vector to store the detached nodes, and iterate over them only when the while loop is 
256	/// compleated, re-setting the `parent`, `prev`, `next` fields to `None`.
257	///
258	/// # Example
259	/// 
260	/// ```
261	/// use hedel_rs::prelude::*;
262	/// use hedel_rs::*;
263	/// 
264	/// pub enum NumIdent {
265	///      Equal(i32),
266	///      BiggerThan(i32),
267	///      SmallerThan(i32)
268	///}
269	/// 
270	///impl CompareNode<i32> for NumIdent {
271	///    fn compare(&self, node: &Node<i32>) -> bool {
272	///        match &self {
273	///          NumIdent::Equal(n) => {
274	///            as_content!(node, |content| {
275	///                content == *n
276	///            })
277	///          },
278	///          NumIdent::BiggerThan(n) => {
279	///            as_content!(node, |content| {
280	///             	content > *n
281	///            })
282	///          },
283	///          NumIdent::SmallerThan(n) => {
284	///            as_content!(node, |content| {
285	///             	content < *n
286	///            })
287	///          }
288	///      }
289	///  }
290	///}
291	///
292	/// fn main() {
293	///		let list = list!(
294	///			node!(1),
295	///			node!(2),
296	///			node!(3),
297	///			node!(4),
298	///			node!(5),
299	///			node!(6)
300	///		);
301	///
302	///		let ident = NumIdent::SmallerThan(4);
303	///
304	///		let mut detached_nodes = NodeCollection::<i32>::new();
305	///	
306	///		// possible algorithm to detach all the nodes smaller than 4 in a linked list.
307	///		let mut next: Node<i32> = list.first().unwrap();
308	///
309	///		/* do */ {
310	///			if ident.compare(&next) {
311	///				next.detach_preserve(&mut detached_nodes);
312	///			}
313	///		} while let Some(n) = next.next() {
314	///
315	///			next = n;
316	///
317	///			if ident.compare(&next) {
318	///				next.detach_preserve(&mut detached_nodes);
319	///			}
320	///		}
321	///
322	///		// this will finally re-set to None every pointer in the collected
323	///		// nodes.
324	///		detached_nodes.free();
325	/// }
326	/// ```
327	fn detach_preserve(&self, vec: &mut NodeCollection<T>) {
328							// 1				3
329		let mut tuple: (Option<Node<T>>, Option<Node<T>>) = ( None, None );
330
331		if let Some(one) = self.prev() {
332			// 1,2,3
333			if let Some(three) = self.next() {
334				tuple = (Some(one), Some(three));
335			} else {
336				// 1,2
337				tuple = (Some(one), None);
338			}
339		} else {
340			// 2, 3
341			if let Some(three) = self.next() {
342				tuple = ( None, Some(three));
343			}
344		}
345		
346		match tuple {
347			(Some(one), Some(three)) => {
348				one.get_mut().next = Some(three.clone());
349				three.get_mut().prev = Some(one.downgrade());
350			},
351			(Some(one), None) => {
352				one.get_mut().next = None;
353			},
354			(None, Some(three)) => {
355				three.get_mut().prev = None;
356				if let Some(parent) = self.parent() {
357					parent.get_mut().child = Some(three.clone());
358				}
359			},
360			(None, None) => {
361				if let Some(parent) = self.parent() {
362					parent.get_mut().child = None;
363				}
364			}
365		}
366
367		vec.push(self.clone());
368	}
369}
370
371/// `NodeCollection` represents a `Vec` of `Node`s. Usually retrived by collecting over
372/// a `Node` linked list using the `CollectNode` trait implementation.
373/// WARNING: this is not a linked list, but simply a collection of unrelated nodes.
374/// The contained nodes might come from separated linked lists or from the same one.
375pub struct NodeCollection<T: Debug + Clone> {
376	pub nodes: Vec<Node<T>>
377}
378
379impl<T: Debug + Clone> NodeCollection<T> {
380	
381	/// Builds a new collection with the vector provided.
382	pub fn from_vec(nodes: Vec<Node<T>>) -> Self {
383		Self {
384			nodes
385		}
386	}
387		
388	pub fn new() -> Self {
389		Self {
390			nodes: Vec::new()
391		}
392	}
393	/// Consume `self` and retrive its `Node`s.
394	pub fn into_nodes(self) -> Vec<Node<T>> {
395		self.nodes
396	}
397
398	/// Retrive a reference to the `Node`s.
399	pub fn as_nodes(&self) -> &Vec<Node<T>> {
400		&self.nodes
401	}
402
403	/// Retrive a mutable reference to the `Node`s.
404	pub fn as_mut_nodes(&mut self) -> &mut Vec<Node<T>> {
405		&mut self.nodes
406	}
407
408	/// Push a node to the collection.
409	pub fn push(&mut self, node: Node<T>) {
410		self.nodes.push(node);
411	}
412
413	/// Re-set the `parent`, `prev` and `next` pointers in every node of the collection.
414	/// This function is commonly used when iterating over a linked list detaching the
415	/// nodes satisfying an identifier using `HedelDetach::detach_preserve`.
416	/// refer to `HedelDetach::detach_preserve` for a code example.
417	///
418	/// WARNING: don't use this function to detach a node from a linked list.
419	pub fn free(&self) {
420		for node in self.nodes.iter() {
421			node.free();
422		}
423	}
424
425}
426
427impl<T: Debug + Clone> IntoIterator for NodeCollection<T> {
428	type Item = Node<T>;
429	type IntoIter = std::vec::IntoIter<Node<T>>;
430
431	fn into_iter(self) -> Self::IntoIter {
432		self.nodes.into_iter()
433	}
434}
435
436/// Users are supposed to impl `CompareNode` for an enum they would
437/// like to use as an identifier.
438///
439/// # Example
440///
441/// ```
442/// use hedel_rs::prelude::*;
443/// use hedel_rs::*;
444///
445/// pub enum NumIdent {
446///		BiggerThan(i32),
447///		SmallerThan(i32)
448/// }
449///
450/// impl CompareNode<i32> for NumIdent {
451/// 	fn compare(&self, node: &Node<i32>) -> bool {
452/// 		as_content!(node, |content| {
453///				match &self {
454///					NumIdent::BiggerThan(num) => {
455///						return content > *num;
456///					},
457///					NumIdent::SmallerThan(num) => {
458///						return content < *num;
459///					}
460///				}
461///			});			
462///		}
463/// }
464/// ```
465pub trait CompareNode<T: Debug + Clone> {
466	fn compare(&self, node: &Node<T>) -> bool;
467}
468
469pub trait CollectNode<T: Debug + Clone, I: CompareNode<T>> {
470	fn collect_siblings(&self, ident: &I) -> NodeCollection<T>;
471	fn collect_children(&self, ident: &I) -> NodeCollection<T>;
472	fn collect_linked_list(&self, ident: &I) -> NodeCollection<T>;
473}                                                         
474
475impl<T: Debug + Clone, I: CompareNode<T>> CollectNode<T, I> for Node<T> {
476	/// Given an identifier of type implementing `CompareNode` this iterates over all the nodes
477	/// in the linked list horizontally ( iterates over the siblings, previous and next ),
478	/// and compare every node. The nodes satisfying the identifier get collected into a `NodeCollection`.
479	fn collect_siblings(&self, ident: &I) -> NodeCollection<T> {
480	
481		let mut collection = Vec::new();
482		
483		if ident.compare(&self) {
484			collection.push(self.clone());
485		}
486
487		// search in the previous nodes before
488		// search in the next nodes after 
489
490		let mut current;
491
492		if let Some(prev) = self.prev() {
493
494			/* do */ {
495
496				current = prev;
497
498				if ident.compare(&current) {
499					collection.push(current.clone());
500				}
501
502			} while let Some(prev) = current.prev() {
503
504				current = prev;
505
506				if ident.compare(&current) {
507					collection.push(current.clone());
508				}
509			}
510		}
511
512		if let Some(next) = self.next() {
513
514			/* do */ {
515
516				current = next;
517
518				if ident.compare(&current) {
519					collection.push(current.clone());
520				}
521
522			} while let Some(next) = current.next() {
523
524				current = next;
525
526				if ident.compare(&current) {
527					collection.push(current.clone());
528				}
529			}
530		}
531
532		NodeCollection::<T>::from_vec(collection) 
533	}
534
535	/// Given an identifier of type implementing `CompareNode` this iterates over all the nodes that stand 
536	/// lower and deeper in the linked list. Every child satysfying the identifier get collected into a `NodeCollection`
537	fn collect_children(&self, ident: &I) -> NodeCollection<T> {
538
539		let mut collection = Vec::new();
540
541		if let Some(child) = self.child() {
542
543			let mut child = child;
544
545			while let Some(c) = child.child() {
546
547				// we reached a new depth-level in hierarchy
548
549				child = c;
550
551				if ident.compare(&child) {
552					collection.push(child.clone());
553				}
554
555				// iterates horizontally in the previous siblings
556				
557				if let Some(prev) = child.prev() {
558					let mut prev = prev;
559
560					/* do */ {
561
562						if ident.compare(&prev) {
563							collection.push(prev.clone());
564						}
565
566						collection.extend(prev.collect_children(ident).nodes);
567
568					} while let Some(p) = prev.prev() {
569						
570						prev = p;
571
572						if ident.compare(&prev) {
573							collection.push(prev.clone());
574						}
575
576						collection.extend(prev.collect_children(ident).nodes);
577					}
578				}
579
580				// iterates horizontally in the next siblings
581
582				if let Some(n) = child.next() {
583
584					let mut next = n;
585
586					/* do */ {
587
588						if ident.compare(&next) {
589							collection.push(next.clone());
590						}
591
592						collection.extend(next.collect_children(ident).nodes);
593
594					} while let Some(n) = next.next() {
595
596						next = n;
597
598						if ident.compare(&next) {
599							collection.push(next.clone());
600						}
601
602						collection.extend(next.collect_children(ident).nodes);
603					}
604				}
605			}
606		}
607
608		NodeCollection::<T>::from_vec(collection)
609	}
610	
611	/// Given an identifier of type implementing `CompareNode` this iterates over all the nodes in the 
612	/// linked list both horizontally and vertically ( iterates horizontally in each hierarchical level,
613	/// up to the top parent and down to the deepest child also
614	/// iterating vertically and horizontally for each layer of the children ).
615	/// The nodes satisfying the identifier get collected into a `NodeCollection`.
616	///
617	/// # Example
618	///
619	/// ```
620	/// use hedel_rs::prelude::*;
621	/// use hedel_rs::*;
622	/// 
623	/// pub enum NumIdent {
624	/// 	  Equal(i32),
625	/// 	  BiggerThan(i32),
626	/// 	  SmallerThan(i32)
627	/// }
628	///
629	/// impl CompareNode<i32> for NumIdent {
630	/// 	fn compare(&self, node: &Node<i32>) -> bool {
631	/// 		match &self {
632	/// 		  NumIdent::Equal(n) => {
633	/// 			as_content!(node, |content| {
634	/// 			  content == *n
635	/// 			})
636	/// 	   	  },
637	/// 		  NumIdent::BiggerThan(n) => {
638	/// 			as_content!(node, |content| {
639	/// 			  content > *n
640	/// 			})
641	/// 		  },
642	/// 		  NumIdent::SmallerThan(n) => {
643	/// 			as_content!(node, |content| {
644	/// 				content < *n
645	/// 			})
646	/// 		  }
647	/// 	  }
648	///   }
649	/// }
650	///
651	/// fn main() {
652	///		let node = node!(1,
653	///			node!(8),
654	///			node!(3),
655	///			node!(7),
656	///			node!(6, node!(3))
657	///		);
658	///
659	///		// retrive any child
660	///		let a = node.get_last_child().unwrap();
661	///
662	///		let collection = a.collect_linked_list(&NumIdent::SmallerThan(5));
663	///
664	///		for node in collection.into_iter() {
665	///			println!("{}", node.to_content());
666	///		}
667	/// }
668	/// ```
669	fn collect_linked_list(&self, ident: &I) -> NodeCollection<T> {
670		
671		let mut collection = Vec::new();
672		
673		// collect on the current level
674		// collect on the upper levels
675		// collect on the inner levels
676	
677		if let Some(parent) = self.parent() {
678			let mut parent = parent;
679			
680			while let Some(p) = parent.parent() {
681				parent = p;
682			}
683
684			// we obtained the top parent node
685
686			if ident.compare(&parent) {
687				collection.push(parent.clone());
688			}
689
690			collection.extend(parent.collect_children(ident).nodes);
691			
692			// does the same thing on all the other next top parent nodes
693
694			if let Some(n) = parent.prev() {
695				let mut prev = n;
696
697				/* do */ {
698
699					if ident.compare(&prev) {
700						collection.push(prev.clone());
701					}
702
703					collection.extend(prev.collect_children(ident).nodes);
704
705				} while let Some(n) = prev.prev() {
706					prev = n;
707
708					if ident.compare(&prev) {
709						collection.push(prev.clone());
710					}
711
712					collection.extend(prev.collect_children(ident).nodes);
713				}
714			}
715
716			if let Some(n) = parent.next() {
717				let mut next = n;
718
719				/* do */ {
720
721					if ident.compare(&next) {
722						collection.push(next.clone());
723					}
724
725					collection.extend(next.collect_children(ident).nodes);
726
727				} while let Some(n) = next.next() {
728					next = n;
729
730					if ident.compare(&next) {
731						collection.push(next.clone());
732					}
733
734					collection.extend(next.collect_children(ident).nodes);
735				}
736			}
737		} else {
738			// in case we dont have a parent
739			// iterates in the previous siblings
740			// iterates in the next siblings
741
742			if ident.compare(&self) {
743				collection.push(self.clone());
744			}
745
746			collection.extend(self.collect_children(ident).nodes);
747	
748			if let Some(n) = self.prev() {
749				let mut prev = n;
750
751				/* do */ {
752
753					if ident.compare(&prev) {
754						collection.push(prev.clone());
755					}
756
757					collection.extend(prev.collect_children(ident).nodes);
758
759				} while let Some(n) = prev.prev() {
760					prev = n;
761
762					if ident.compare(&prev) {
763						collection.push(prev.clone());
764					}
765
766					collection.extend(prev.collect_children(ident).nodes);
767				}
768			}
769
770			if let Some(n) = self.next() {
771				let mut next = n;
772
773				/* do */ {
774
775					if ident.compare(&next) {
776						collection.push(next.clone());
777					}
778
779					collection.extend(next.collect_children(ident).nodes);
780
781				} while let Some(n) = next.next() {
782					next = n;
783
784					if ident.compare(&next) {
785						collection.push(next.clone());
786					}
787
788					collection.extend(next.collect_children(ident).nodes);
789				}
790			}
791		}
792
793		NodeCollection::<T>::from_vec(collection)
794	}
795} 
796
797pub trait FindNode<T: Debug + Clone, I: CompareNode<T>> {
798	fn find_next(&self, ident: &I) -> Option<Node<T>>;
799	fn find_prev(&self, ident: &I) -> Option<Node<T>>;
800	fn find_sibling(&self, ident: &I) -> Option<Node<T>>;
801	fn find_child(&self, ident: &I) -> Option<Node<T>>;
802	fn find_linked_list(&self, ident: &I) -> Option<Node<T>>;
803}                                                         
804
805impl<T: Debug + Clone, I: CompareNode<T>> FindNode<T, I> for Node<T> {
806	/// Get the first `Node` in the linked list, at the same depth-level of `&self` and coming after it,
807	/// matching the identifier.
808	/// This guarantees to actually retrive the closest `Node`.
809	///
810	/// # Example
811	///
812	/// ```
813	/// use hedel_rs::prelude::*;
814	/// use hedel_rs::*;
815	///
816	/// pub enum NumIdent {
817	///      Equal(i32),
818	///      BiggerThan(i32),
819	///      SmallerThan(i32)
820	/// }
821	///
822	/// impl CompareNode<i32> for NumIdent {
823	///     fn compare(&self, node: &Node<i32>) -> bool {
824	///         match &self {
825	///           NumIdent::Equal(n) => {
826	///               as_content!(node, |content| {
827	///                  content == *n
828	///               })
829	///            },
830	///           NumIdent::BiggerThan(n) => {
831	///             as_content!(node, |content| {
832	///               content > *n
833	///             })
834	///           },
835	///           NumIdent::SmallerThan(n) => {
836	///             as_content!(node, |content| {
837	///                 content < *n
838	///             })
839	///           }
840	///       }
841	///   }
842	/// }
843	///
844	/// fn main() {
845	///
846	///		let node = node!(33,
847	///			node!(1),
848	///			node!(34),
849	///			node!(66)
850	///		); 
851	///		
852	///		let one = node.child().unwrap();
853	///		assert_eq!(
854	///			one.find_next(&NumIdent::BiggerThan(50)).unwrap().to_content(),
855	///			66
856	///		); 
857	/// }
858	/// ```
859	fn find_next(&self, ident: &I) -> Option<Node<T>> {
860		if let Some(next) = self.next() {
861			let mut next = next;
862
863			/* do */ {
864
865				if ident.compare(&next) {
866					return Some(next);
867				}
868				
869			} while let Some(n) = next.next() {
870				next = n;
871
872				if ident.compare(&next) {
873					return Some(next);
874				}
875			}
876		}
877	
878		None
879	}
880	
881	/// Get the first `Node` in the linked list, at the same depth-level of `&self` and coming before it,
882	/// matching the identifier.
883	/// This guarantees to actually retrive the closest `Node`.
884	fn find_prev(&self, ident: &I) -> Option<Node<T>> {
885		if let Some(prev) = self.prev() {
886			let mut prev = prev;
887
888			/* do */ {
889
890				if ident.compare(&prev) {
891					return Some(prev);
892				}
893				
894			} while let Some(n) = prev.prev() {
895				prev = n;
896
897				if ident.compare(&prev) {
898					return Some(prev);
899				}
900	
901			}
902		}
903		None
904
905	}
906	
907	/// Get a `Node` somewhere in the linked list matching the identifier.
908	/// WARNING: it's not guaranteed to retrive the closest `Node`. Only use when you don't
909	/// care about which node is retrived as long as it matches the identifier or when you are 100% sure
910	/// that there isn't more than one `Node` satisfying the identifier in the linked list.
911	fn find_linked_list(&self, ident: &I) -> Option<Node<T>> {
912		if let 	Some(parent) = self.parent() {
913			let mut parent = parent;
914			
915			while let Some(p) = parent.parent() {
916				parent = p;
917			}
918
919			// we obtained the top parent node
920
921			if ident.compare(&parent) {
922				return Some(parent);
923			}
924
925			if let Some(c) = parent.find_child(ident) {
926				return Some(c);
927			}
928			
929			// does the same thing on all the other next top parent nodes
930
931			if let Some(n) = parent.prev() {
932				let mut prev = n;
933
934				/* do */ {
935
936					if ident.compare(&prev) {
937						return Some(prev);
938					}
939
940					if let Some(c) = prev.find_child(ident) {
941						return Some(c);
942					}
943
944				} while let Some(n) = prev.prev() {
945					prev = n;
946
947					if ident.compare(&prev) {
948						return Some(prev);
949					}
950
951					if let Some(c) = prev.find_child(ident) {
952						return Some(c);
953					}
954				}
955			}
956
957			if let Some(n) = parent.next() {
958				let mut next = n;
959
960				/* do */ {
961
962					if ident.compare(&next) {
963						return Some(next);
964					}
965
966					if let Some(c) = next.find_child(ident) {
967						return Some(c);
968					}
969
970				} while let Some(n) = next.next() {
971					next = n;
972
973					if ident.compare(&next) {
974						return Some(next);
975					}
976
977					if let Some(c) = next.find_child(ident) {
978						return Some(c);
979					}
980				}
981			}
982
983		} else {
984
985			if ident.compare(&self) {
986				return Some(self.clone());
987			}
988
989			if let Some(child) = self.find_child(ident) {
990				return Some(child);
991			}
992
993			if let Some(n) = self.prev() {
994				let mut prev = n;
995
996				/* do */ {
997
998					if ident.compare(&prev) {
999						return Some(prev);
1000					}
1001
1002					if let Some(child) = prev.find_child(ident) {
1003						return Some(child);
1004					}
1005
1006				} while let Some(n) = prev.prev() {
1007					prev = n;
1008
1009					if ident.compare(&prev) {
1010						return Some(prev);
1011					}
1012
1013					if let Some(child) = prev.find_child(ident) {
1014						return Some(child);
1015					}
1016				}
1017			}
1018
1019			if let Some(n) = self.next() {
1020				let mut next = n;
1021
1022				/* do */ {
1023
1024					if ident.compare(&next) {
1025						return Some(next);
1026					}
1027
1028					if let Some(child) = next.find_child(ident) {
1029						return Some(child);
1030					}
1031
1032				} while let Some(n) = next.next() {
1033					next = n;
1034
1035					if ident.compare(&next) {
1036						return Some(next);
1037					}
1038
1039					if let Some(child) = next.find_child(ident) {
1040						return Some(child);
1041					}
1042				}
1043			}
1044		}
1045
1046		None
1047	}
1048
1049	/// Get the first child `Node` of `&self` in the linked list matching the identifier. 
1050	/// WARNING: it's not guaranteed to retrive the closest `Node`. Only use when you don't
1051	/// care about which node is retrived as long as it matches the identifier or when you are 100% sure
1052	/// that there isn't more than one `Node` satisfying the identifier in the children.
1053	fn find_child(&self, ident: &I) -> Option<Node<T>> {
1054		if let Some(child) = self.child() {
1055			let mut child = child;
1056			/* do */ {
1057
1058				if ident.compare(&child) {
1059					return Some(child);
1060				}
1061				
1062				if let Some(next) = child.next() {
1063					let mut next = next;
1064					/* do */ {
1065						if ident.compare(&next) {
1066							return Some(next);
1067						}
1068
1069						if let Some(c) = next.find_child(ident) {
1070							return Some(c);
1071						}
1072					} while let Some(n) = next.next() {
1073					
1074						next = n;
1075
1076						if ident.compare(&next) {
1077							return Some(next);
1078						}
1079
1080						if let Some(c) = next.find_child(ident) {
1081							return Some(c);
1082						}
1083					}
1084				}
1085
1086			} while let Some(c) = child.child() {
1087				child = c;	
1088
1089				if ident.compare(&child) {
1090					return Some(child);
1091				}
1092				
1093				if let Some(next) = child.next() {
1094					let mut next = next;
1095					/* do */ {
1096						if ident.compare(&next) {
1097							return Some(next);
1098						}
1099
1100						if let Some(c) = next.find_child(ident) {
1101							return Some(c);
1102						}
1103					} while let Some(n) = next.next() {
1104					
1105						next = n;
1106
1107						if ident.compare(&next) {
1108							return Some(next);
1109						}
1110
1111						if let Some(c) = next.find_child(ident) {
1112							return Some(c);
1113						}
1114					}
1115				}
1116
1117			}
1118		}	
1119
1120		None
1121	}
1122
1123	/// In the case you can't know if the `Node` you are looking for comes before or after, here's a combination of the two previous methods. 
1124	/// Always prefer using `HedelFind::find_next` and `HedelFind::find_prev` when you know the position of the `Node`,
1125	/// as they might be faster.
1126	fn find_sibling(&self, ident: &I) -> Option<Node<T>> {
1127		// in case we dont have a parent
1128		// iterates in the previous siblings
1129		// iterates in the next siblings
1130
1131		//if let Some(child) = self.find_child(ident) {
1132		//	return Some(child);
1133		//}
1134
1135		if let Some(n) = self.prev() {
1136			let mut prev = n;
1137
1138			/* do */ {
1139
1140				if ident.compare(&prev) {
1141					return Some(prev);
1142				}
1143
1144				if let Some(child) = prev.find_child(ident) {
1145					return Some(child);
1146				}
1147
1148			} while let Some(n) = prev.prev() {
1149				prev = n;
1150
1151				if ident.compare(&prev) {
1152					return Some(prev);
1153				}
1154
1155				if let Some(child) = prev.find_child(ident) {
1156					return Some(child);
1157				}
1158			}
1159		}
1160
1161		if let Some(n) = self.next() {
1162			let mut next = n;
1163
1164			/* do */ {
1165
1166				if ident.compare(&next) {
1167					return Some(next);
1168				}
1169
1170				if let Some(child) = next.find_child(ident) {
1171					return Some(child);
1172				}
1173
1174			} while let Some(n) = next.next() {
1175				next = n;
1176
1177				if ident.compare(&next) {
1178					return Some(next);
1179				}
1180
1181				if let Some(child) = next.find_child(ident) {
1182					return Some(child);
1183				}
1184			}
1185		}
1186
1187		None
1188	}
1189
1190}
1191
1192pub trait GetNode<T: Debug + Clone> {
1193	fn get_first_sibling(&self) -> Option<Node<T>>;
1194	fn get_last_sibling(&self) -> Option<Node<T>>;
1195	fn get_last_child(&self) -> Option<Node<T>>;
1196}
1197
1198impl<T: Debug + Clone> GetNode<T> for Node<T> {
1199
1200	/// Get the first `Node` in the linked list at the same depth level of `&self`.
1201	/// If None is returned, `&self` is the first `Node` at that depth level.
1202	fn get_first_sibling(&self) -> Option<Node<T>> {
1203		
1204		// faster in case there's a parent
1205		if let Some(parent) = self.parent() {
1206			return parent.child();
1207		}
1208
1209		let mut first;
1210
1211		/* do */ {
1212			
1213			if let Some(prev) = self.prev() {
1214				first = prev;
1215			} else { return None; }
1216
1217		} while let Some(prev) = first.prev() {
1218			first = prev;
1219		}
1220
1221		Some(first)
1222	}
1223
1224	/// Get the last `Node` in the linked list at the same depth level of `&self`.
1225	/// If None is returned, `&self` is the last `Node` at that depth level.
1226	fn get_last_sibling(&self) -> Option<Node<T>> {
1227		
1228		let mut last;
1229
1230		/* do */ {
1231
1232			if let Some(next) = self.next() {
1233				last = next;
1234			} else { return None; }
1235
1236		} while let Some(next) = last.next() {
1237			last = next;
1238		}
1239
1240		Some(last)
1241	}
1242
1243	/// Get the last child `Node` of `&self`
1244	/// If None is returned, `&self` doesn't have any children.
1245	/// NOTE: use &self.child() to get the first `Node`.
1246	fn get_last_child(&self) -> Option<Node<T>> {
1247
1248		if let Some(child) = self.child() {
1249			
1250			let child = child;
1251			
1252			if let Some(s) = child.get_last_sibling() {
1253				return Some(s);
1254			}
1255
1256			return Some(child);
1257
1258		} None
1259	}
1260}
1261
1262pub trait AppendNode<T: Debug + Clone> {
1263	fn append_next(&self, node: Node<T>);
1264	fn append_child(&self, node: Node<T>);
1265	fn append_prev(&self, node: Node<T>);
1266}
1267
1268impl<T: Debug + Clone> AppendNode<T> for Node<T> {
1269
1270	/// Inserts a new node right after `&self`.
1271	///
1272	/// # Example
1273	///
1274	/// ```
1275	/// use hedel_rs::prelude::*;
1276	/// use hedel_rs::*;
1277	///
1278	/// fn main() {
1279	///		let node = node!(1, node!(2));
1280	///		let two = node.child().unwrap();                            	
1281	///		two.append_next(node!(3));                         	
1282	///		assert_eq!(node.get_last_child().unwrap().to_content(), 3);	
1283	/// }	
1284	/// ```
1285	fn append_next(&self, node: Node<T>) {
1286		if let Some(parent) = self.parent() {
1287			node.get_mut().parent = Some(parent.downgrade());
1288		}
1289		
1290		if let Some(next) = self.next() {
1291			next.get_mut().prev = Some(node.downgrade());
1292			node.get_mut().next = Some(next);
1293		}
1294
1295		self.get_mut().next = Some(node.clone());
1296		node.get_mut().prev = Some(self.downgrade());
1297	}
1298	
1299	/// Inserts a new node right before `&self`.
1300	///
1301	/// # Example
1302	///
1303	/// ```
1304	/// use hedel_rs::prelude::*;
1305	/// use hedel_rs::*;
1306	///
1307	/// fn main() {
1308	///		let node = node!(1, node!(2));
1309	///		let two = node.child().unwrap();
1310	///		two.append_prev(node!(3));
1311	///		assert_eq!(node.child().unwrap().to_content(), 3);
1312	/// }
1313	/// ```
1314	fn append_prev(&self, node: Node<T>) {
1315		
1316		
1317		
1318		
1319		if let Some(prev) = self.prev() {
1320			prev.get_mut().next = Some(node.clone());
1321			node.get_mut().prev = Some(prev.downgrade());
1322			self.get_mut().prev = Some(node.downgrade());
1323			node.get_mut().next = Some(self.clone());
1324
1325
1326		} else {
1327			if let Some(list) = self.list() {
1328
1329				self.get_mut().prev = Some(node.downgrade());
1330				node.get_mut().next = Some(self.clone());
1331				node.get_mut().list = Some(list.downgrade());	
1332				*list.first.get_mut() = Some(node.clone());
1333				
1334			} else { /* !!!!HELP */ } 
1335		}
1336		
1337		if let Some(parent) = self.parent() {
1338			node.get_mut().parent = Some(parent.downgrade());
1339			parent.get_mut().child = Some(node.clone());
1340		}	
1341	}
1342
1343	/// Inserts a new node right after the last child of `&self`.
1344	///
1345	/// # Example
1346	///
1347	/// ```
1348	/// use hedel_rs::prelude::*;
1349	/// use hedel_rs::*;
1350	///
1351	/// fn main() {
1352	///		let node = node!(1, node!(2));
1353	///		node.append_child(node!(3));
1354	///		println!("{}", node.get_last_child().unwrap().to_content());
1355	/// }
1356	/// ```
1357	fn append_child(&self, node: Node<T>) {
1358		node.get_mut().parent = Some(self.downgrade());
1359		if let Some(last_child) = self.get_last_child() {
1360			last_child.get_mut().next = Some(node.clone());
1361			node.get_mut().prev = Some(last_child.downgrade());
1362		} else {
1363			self.get_mut().child = Some(node);
1364		}
1365	}
1366}
1367pub trait InsertNode<T: Debug + Clone> {
1368	fn insert_sibling(&self, position: usize, node: Node<T>);
1369	fn insert_child(&self, position: usize, node: Node<T>);
1370}
1371
1372impl<T: Debug + Clone> InsertNode<T> for Node<T> {
1373	/// Inserts a new node at the same depth-level of `&self` and at the given position.
1374	///
1375	/// # Example
1376	///
1377	///	```
1378	/// use hedel_rs::prelude::*;
1379	/// use hedel_rs::*;
1380	///
1381	/// fn main() {
1382	///		let mut node = node!(1, node!(2), node!(4));
1383	///
1384	///		let two = node.child().unwrap();
1385	///		two.insert_sibling(23, node!(3));
1386	///
1387	///		// if the position is bigger than the length, the node gets placed at the end
1388	///		let three = node.get_last_child().unwrap();
1389	///		println!("{}", three.to_content()); // prints 3
1390	/// }
1391	/// ```
1392	///
1393	
1394	fn insert_sibling(&self, position: usize, node: Node<T>) {
1395		
1396		let mut sibling = self.clone(); 
1397
1398		let mut c = 0;
1399
1400		if c != position {
1401			while let Some(sib) = sibling.next() {
1402				sibling = sib;
1403				c += 1;
1404				if c == position {
1405					break; 
1406				}
1407			}	
1408		} 
1409		
1410		// PARENT
1411		//  node 0 -> next: my OK
1412		//  node 1 -> prev: my
1413		//  node 2
1414		//  
1415		// my -> next: node 1
1416		// my -> prev: node 0
1417		// my -> parent: ---    OK
1418
1419		if c != position {
1420			// append to the last
1421			sibling.append_next(node.clone());
1422		} else {
1423			
1424			if let Some(parent) = self.parent() {
1425				node.get_mut().parent = Some(parent.downgrade());
1426			}
1427
1428			if let Some(prev) = sibling.prev() {
1429				let previous = prev;
1430				previous.get_mut().next = Some(node.clone());
1431			} else {
1432				if let Some(parent) = self.parent() {
1433					// NOTE: NOT SUPPORTING NODELIST, BUG
1434					parent.get_mut().child = Some(node.clone());
1435				}	
1436			}
1437
1438			sibling.get_mut().prev = Some(node.downgrade());
1439		}
1440	}
1441
1442	/// Inserts a new node to the childrenl of `&self` and at the given position.
1443	///
1444	/// # Example
1445	///
1446	///	```
1447	/// use hedel_rs::prelude::*;
1448	/// use hedel_rs::*;
1449	///
1450	/// fn main() {
1451	///		let mut node = node!(1, node!(2), node!(4));
1452	///
1453	///		node.insert_child(2, node!(3));
1454	///
1455	///		let three = node.get_last_child().unwrap();
1456	///		println!("{}", three.to_content()); // prints 3
1457	/// }
1458	/// ```
1459	///
1460	
1461	fn insert_child(&self, position: usize, node: Node<T>) {
1462		if let Some(first_child) = self.child() {
1463			first_child.insert_sibling(position, node);
1464		} else {
1465			node.get_mut().parent = Some(self.downgrade());
1466			self.get_mut().child = Some(node);
1467		}
1468	}	
1469}
1470/// Generate a node blazingly fast, with any number of child nodes.
1471/// 
1472/// # Example
1473///
1474/// ```
1475/// use hedel_rs::prelude::*;
1476/// use hedel_rs::*;
1477/// 
1478/// fn main() {
1479///		let my_node = node!("Parent",
1480///			node!("Child"),
1481///			node!("Child")
1482///		);
1483///
1484///		let another_node = node!("Another");
1485/// }
1486/// ```
1487#[macro_export]
1488macro_rules! node {
1489	($content: expr $(,$node: expr)*) => {
1490		{
1491			let mut node = hedel_rs::Node::new($content);
1492
1493			let mut children: Vec<hedel_rs::Node<_>> = Vec::new();
1494
1495			let mut lists: Vec<usize> = Vec::new();
1496
1497			let mut c = 0;
1498
1499			$(
1500				let n: hedel_rs::Node::<_> = $node.into();
1501				
1502				if let Some(_) = n.get().list {
1503					lists.push(c as usize);
1504				}
1505
1506				children.push(n);
1507
1508				c += 1;
1509			)*
1510
1511			if children.len() > 0 {
1512				node.get_mut().child = Some(children[0].clone());
1513	
1514				c = 0;
1515				
1516				let max_idx = children.len() - 1;
1517
1518				for ref child in &children {
1519					let mut borrow = child.get_mut();
1520
1521					if c != max_idx {
1522						borrow.next = Some(children[c + 1].clone()); 
1523					}
1524
1525					if c != 0 {
1526						borrow.prev = Some(children[c - 1].downgrade());
1527					}
1528
1529					borrow.parent = Some(hedel_rs::WeakNode {
1530						inner: std::rc::Rc::downgrade(&node.inner)
1531					});
1532
1533					c += 1;
1534				}
1535
1536			} 
1537		
1538			for idx in lists.into_iter() {
1539				
1540				let first = children[idx].clone();
1541
1542				if idx > 0 {
1543					if let Some(prev) = children.get(idx - 1) {
1544						prev.get_mut().next = Some(first.clone());
1545						first.get_mut().prev = Some(prev.downgrade());
1546					}
1547				}
1548
1549				if let Some(last) = first.get_last_sibling() {
1550					if let Some(next) = children.get(idx + 1) {
1551						next.get_mut().prev = Some(last.downgrade());
1552						last.get_mut().next = Some(next.clone());
1553					}
1554				}
1555
1556				let mut child = first;
1557
1558				/* do */ {
1559
1560					child.get_mut().parent = Some(node.downgrade());
1561
1562				} while let Some(ch) = child.next() {
1563					child = ch;
1564					child.get_mut().parent = Some(node.downgrade());
1565				}
1566			}
1567
1568			node
1569		}
1570	}
1571}
1572
1573// TODO: create a node_no_child macro for cases when the user is sure there won't be any children
1574// e.g void html elements.