summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 170dad000aa59d4c163ceff9ae859b4f6800de18 (plain)
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
fn main() {
    let mut cont: Container<usize> = Container::new();
    cont.push(42);
    for v in cont.iter() {
        println!("{}", v);
    }
}

struct Container<T> {
    items: Vec<T>,
}

impl<T> Container<T> {
    fn new() -> Self {
        Self { items: vec![] }
    }

    fn push(&mut self, item: T) {
        self.items.push(item);
    }

    fn iter(&self) -> ContainerItems<T> {
        ContainerItems::new(self)
    }
}

struct ContainerItems<'a, T> {
    cont: &'a Container<T>,
    next: Option<usize>,
}

impl<'a, T> ContainerItems<'a, T> {
    fn new(cont: &'a Container<T>) -> Self {
        Self { cont, next: Some(0) }
    }
}

impl<'a, T> Iterator for ContainerItems<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(i) = self.next {
            if i < self.cont.items.len() {
                self.next = Some(i + 1);
                Some(&self.cont.items[i])
            } else {
                None
            }
        } else {
            None
        }
    }
}