1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use std::{rc::Rc, ops::Deref};

pub struct DigraphNode<T> {
    pub next: DigraphNodeRef<T>, // I made it `pub` to be able `item.next.next()` to remove an item from the middle.
    data: T,
}

pub struct DigraphNodeRef<T> {
    rc: Rc<DigraphNode<T>>,
}

impl<T> DigraphNodeRef<T> {
    pub fn from(rc: Rc<DigraphNode<T>>) -> Self {
        Self {
            rc
        }
    }
    pub fn remove(&mut self) {
        self.rc = self.rc.next.rc.clone()
    }
}

impl<T> Clone for DigraphNodeRef<T> {
    fn clone(&self) -> Self {
        Self { rc: self.rc.clone() }
    }
}

impl<T> Deref for DigraphNodeRef<T> {
    type Target = DigraphNode<T>;

    fn deref(&self) -> &Self::Target {
        self.rc.deref()
    }
}

impl<T> Iterator for DigraphNodeRef<T> {
    type Item = DigraphNodeRef<T>;

    fn next(&mut self) -> Option<Self::Item> {
        if Rc::strong_count(&self.rc) != 0 { // FIXME
            self.rc = (*self.rc).next.rc.clone();
            Some(self.clone())
        } else {
            None
        }
    }
}

pub struct DigraphNodeValuesIterator<T> {
    underlying: DigraphNodeRef<T>,
}

impl<T: Clone> Iterator for DigraphNodeValuesIterator<T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(next) = self.underlying.next() {
            Some(next.rc.data.clone())
        } else {
            None
        }
    }
}

// TODO: Test.