table/list/
iter.rs

1// Copyright (C) 2018  Project Tsukurou!
2//
3// This program is free software: you can redistribute it and/or modify
4// it under the terms of the GNU General Public License as published by
5// the Free Software Foundation, either version 3 of the License, or
6// (at your option) any later version.
7//
8// This program is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License
14// along with this program.  If not, see <https://www.gnu.org/licenses/>.
15
16use std::iter::FromIterator;
17use std::slice;
18use std::vec;
19
20use value::Value;
21use list::List;
22
23/// A borrowing iterator over the elements in a list.
24pub struct Iter<'a: 'b, 'b> {
25    iter: slice::Iter<'b, Value<'a>>,
26}
27
28impl<'a, 'b> Iterator for Iter<'a, 'b> {
29    type Item = &'b Value<'a>;
30
31    fn next(&mut self) -> Option<Self::Item> {
32        self.iter.next()
33    }
34}
35
36impl<'a, 'b> IntoIterator for &'b List<'a> {
37    type Item = &'b Value<'a>;
38    type IntoIter = Iter<'a, 'b>;
39
40    fn into_iter(self) -> Self::IntoIter {
41        Iter {
42            iter: self.vec.iter(),
43        }
44    }
45}
46
47/// A mutably borrowing iterator over the elements in a list.
48pub struct IterMut<'a: 'b, 'b> {
49    iter: slice::IterMut<'b, Value<'a>>,
50}
51
52impl<'a, 'b> Iterator for IterMut<'a, 'b> {
53    type Item = &'b mut Value<'a>;
54
55    fn next(&mut self) -> Option<Self::Item> {
56        self.iter.next()
57    }
58}
59
60impl<'a, 'b> IntoIterator for &'b mut List<'a> {
61    type Item = &'b mut Value<'a>;
62    type IntoIter = IterMut<'a, 'b>;
63
64    fn into_iter(self) -> Self::IntoIter {
65        IterMut {
66            iter: self.vec.iter_mut(),
67        }
68    }
69}
70
71/// A consuming iterator over the elements in a list.
72pub struct IntoIter<'a> {
73    iter: vec::IntoIter<Value<'a>>,
74}
75
76impl<'a> Iterator for IntoIter<'a> {
77    type Item = Value<'a>;
78
79    fn next(&mut self) -> Option<Self::Item> {
80        self.iter.next()
81    }
82}
83
84impl<'a> IntoIterator for List<'a> {
85    type Item = Value<'a>;
86    type IntoIter = IntoIter<'a>;
87
88    fn into_iter(self) -> Self::IntoIter {
89        IntoIter {
90            iter: self.vec.into_iter(),
91        }
92    }
93}
94
95impl<'a, V> FromIterator<V> for List<'a>
96where
97    Value<'a>: From<V>,
98{
99    fn from_iter<I>(iter: I) -> Self
100    where
101        I: IntoIterator<Item=V>,
102    {
103        let vec = iter.into_iter()
104            .map(Value::from)
105            .collect();
106
107        List::with_vec(vec)
108    }
109}