didedoshka

Persistent Stack Iter

Oct 31st, 2025
615
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.61 KB | None | 0 0
  1. use std::borrow::Borrow;
  2. use std::rc::Rc;
  3.  
  4. struct PStackEntry<T> {
  5.     value: T,
  6.     down: PStack<T>,
  7. }
  8.  
  9. pub struct PStack<T>(Rc<Option<PStackEntry<T>>>);
  10.  
  11. impl<T> PStack<T> {
  12.     pub fn iter<'a>(&'a self) -> Iter<'a, T> {
  13.        Iter(self)
  14.    }
  15. }
  16.  
  17. pub struct Iter<'a, T>(&'a PStack<T>);
  18.  
  19. impl<'a, T> Iterator for Iter<'a, T> {
  20.    type Item = &'a T;
  21.  
  22.     fn next(&mut self) -> Option<Self::Item> {
  23.         match self.0.0.borrow() {
  24.             None => None,
  25.             Some(entry) => {
  26.                 self.0 = &entry.down;
  27.                 Some(&entry.value)
  28.             }
  29.         }
  30.     }
  31. }
  32.  
Advertisement
Add Comment
Please, Sign In to add comment