Advertisement
tomdodd4598

Untitled

Oct 23rd, 2021
1,818
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.27 KB | None | 0 0
  1. use super::item::Item;
  2.  
  3. use std::fmt::Display;
  4. use std::ops::Index;
  5. use std::rc::Rc;
  6.  
  7. pub struct Node<T>
  8.     where T: Display
  9. {
  10.     pub value: Option<Rc<Item<T>>>,
  11. }
  12.  
  13. impl<T> Node<T>
  14.     where T: Display
  15. {
  16.     pub fn new(item: Item<T>) -> Self {
  17.         Node { value: Some(Rc::new(item)) }
  18.     }
  19.  
  20.     pub fn empty() -> Self {
  21.         Node { value: None }
  22.     }
  23.  
  24.     pub fn val_some(&self) -> bool {
  25.         self.value.is_some()
  26.     }
  27.  
  28.     pub fn val_none(&self) -> bool {
  29.         self.value.is_none()
  30.     }
  31. }
  32.  
  33. impl<T> Clone for Node<T>
  34.     where T: Display
  35. {
  36.     fn clone(&self) -> Self {
  37.         Node { value: self.value.clone() }
  38.     }
  39. }
  40.  
  41. impl<T> Default for Node<T>
  42.     where T: Display
  43. {
  44.     fn default() -> Self {
  45.         Node { value: None }
  46.     }
  47. }
  48.  
  49. impl<T> Index<usize> for Node<T>
  50.     where T: Display
  51. {
  52.     type Output = Self;
  53.  
  54.     fn index(&self, n: usize) -> &Self::Output {
  55.         let mut previous;
  56.         let mut current = self;
  57.         let empty = Node::empty();
  58.         for _i in 0..n {
  59.             previous = current;
  60.             current = match previous.value {
  61.                 Some(ref x) => &x.next,
  62.                 None => &empty,
  63.             };
  64.         }
  65.         unsafe { &*(current as *const Self) }
  66.     }
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement