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
67
68
69
70
use rustc_index::vec::{Idx, IndexVec};

pub fn iter<Ls>(
    first: Option<Ls::LinkIndex>,
    links: &Ls,
) -> impl Iterator<Item = Ls::LinkIndex> + '_
where
    Ls: Links,
{
    VecLinkedListIterator { links, current: first }
}

pub struct VecLinkedListIterator<Ls>
where
    Ls: Links,
{
    links: Ls,
    current: Option<Ls::LinkIndex>,
}

impl<Ls> Iterator for VecLinkedListIterator<Ls>
where
    Ls: Links,
{
    type Item = Ls::LinkIndex;

    fn next(&mut self) -> Option<Ls::LinkIndex> {
        if let Some(c) = self.current {
            self.current = <Ls as Links>::next(&self.links, c);
            Some(c)
        } else {
            None
        }
    }
}

pub trait Links {
    type LinkIndex: Copy;

    fn next(links: &Self, index: Self::LinkIndex) -> Option<Self::LinkIndex>;
}

impl<Ls> Links for &Ls
where
    Ls: Links,
{
    type LinkIndex = Ls::LinkIndex;

    fn next(links: &Self, index: Ls::LinkIndex) -> Option<Ls::LinkIndex> {
        <Ls as Links>::next(links, index)
    }
}

pub trait LinkElem {
    type LinkIndex: Copy;

    fn next(elem: &Self) -> Option<Self::LinkIndex>;
}

impl<L, E> Links for IndexVec<L, E>
where
    E: LinkElem<LinkIndex = L>,
    L: Idx,
{
    type LinkIndex = L;

    fn next(links: &Self, index: L) -> Option<L> {
        <E as LinkElem>::next(&links[index])
    }
}