]> git.lizzy.rs Git - rust.git/blob - src/libcore/iter/sources.rs
Auto merge of #47804 - retep007:recursive-requirements, r=pnkfelix
[rust.git] / src / libcore / iter / sources.rs
1 // Copyright 2013-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use fmt;
12 use marker;
13 use usize;
14
15 use super::{FusedIterator, TrustedLen};
16
17 /// An iterator that repeats an element endlessly.
18 ///
19 /// This `struct` is created by the [`repeat`] function. See its documentation for more.
20 ///
21 /// [`repeat`]: fn.repeat.html
22 #[derive(Clone, Debug)]
23 #[stable(feature = "rust1", since = "1.0.0")]
24 pub struct Repeat<A> {
25     element: A
26 }
27
28 #[stable(feature = "rust1", since = "1.0.0")]
29 impl<A: Clone> Iterator for Repeat<A> {
30     type Item = A;
31
32     #[inline]
33     fn next(&mut self) -> Option<A> { Some(self.element.clone()) }
34     #[inline]
35     fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
36 }
37
38 #[stable(feature = "rust1", since = "1.0.0")]
39 impl<A: Clone> DoubleEndedIterator for Repeat<A> {
40     #[inline]
41     fn next_back(&mut self) -> Option<A> { Some(self.element.clone()) }
42 }
43
44 #[unstable(feature = "fused", issue = "35602")]
45 impl<A: Clone> FusedIterator for Repeat<A> {}
46
47 #[unstable(feature = "trusted_len", issue = "37572")]
48 unsafe impl<A: Clone> TrustedLen for Repeat<A> {}
49
50 /// Creates a new iterator that endlessly repeats a single element.
51 ///
52 /// The `repeat()` function repeats a single value over and over and over and
53 /// over and over and 🔁.
54 ///
55 /// Infinite iterators like `repeat()` are often used with adapters like
56 /// [`take`], in order to make them finite.
57 ///
58 /// [`take`]: trait.Iterator.html#method.take
59 ///
60 /// # Examples
61 ///
62 /// Basic usage:
63 ///
64 /// ```
65 /// use std::iter;
66 ///
67 /// // the number four 4ever:
68 /// let mut fours = iter::repeat(4);
69 ///
70 /// assert_eq!(Some(4), fours.next());
71 /// assert_eq!(Some(4), fours.next());
72 /// assert_eq!(Some(4), fours.next());
73 /// assert_eq!(Some(4), fours.next());
74 /// assert_eq!(Some(4), fours.next());
75 ///
76 /// // yup, still four
77 /// assert_eq!(Some(4), fours.next());
78 /// ```
79 ///
80 /// Going finite with [`take`]:
81 ///
82 /// ```
83 /// use std::iter;
84 ///
85 /// // that last example was too many fours. Let's only have four fours.
86 /// let mut four_fours = iter::repeat(4).take(4);
87 ///
88 /// assert_eq!(Some(4), four_fours.next());
89 /// assert_eq!(Some(4), four_fours.next());
90 /// assert_eq!(Some(4), four_fours.next());
91 /// assert_eq!(Some(4), four_fours.next());
92 ///
93 /// // ... and now we're done
94 /// assert_eq!(None, four_fours.next());
95 /// ```
96 #[inline]
97 #[stable(feature = "rust1", since = "1.0.0")]
98 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
99     Repeat{element: elt}
100 }
101
102 /// An iterator that yields nothing.
103 ///
104 /// This `struct` is created by the [`empty`] function. See its documentation for more.
105 ///
106 /// [`empty`]: fn.empty.html
107 #[stable(feature = "iter_empty", since = "1.2.0")]
108 pub struct Empty<T>(marker::PhantomData<T>);
109
110 #[stable(feature = "core_impl_debug", since = "1.9.0")]
111 impl<T> fmt::Debug for Empty<T> {
112     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
113         f.pad("Empty")
114     }
115 }
116
117 #[stable(feature = "iter_empty", since = "1.2.0")]
118 impl<T> Iterator for Empty<T> {
119     type Item = T;
120
121     fn next(&mut self) -> Option<T> {
122         None
123     }
124
125     fn size_hint(&self) -> (usize, Option<usize>){
126         (0, Some(0))
127     }
128 }
129
130 #[stable(feature = "iter_empty", since = "1.2.0")]
131 impl<T> DoubleEndedIterator for Empty<T> {
132     fn next_back(&mut self) -> Option<T> {
133         None
134     }
135 }
136
137 #[stable(feature = "iter_empty", since = "1.2.0")]
138 impl<T> ExactSizeIterator for Empty<T> {
139     fn len(&self) -> usize {
140         0
141     }
142 }
143
144 #[unstable(feature = "trusted_len", issue = "37572")]
145 unsafe impl<T> TrustedLen for Empty<T> {}
146
147 #[unstable(feature = "fused", issue = "35602")]
148 impl<T> FusedIterator for Empty<T> {}
149
150 // not #[derive] because that adds a Clone bound on T,
151 // which isn't necessary.
152 #[stable(feature = "iter_empty", since = "1.2.0")]
153 impl<T> Clone for Empty<T> {
154     fn clone(&self) -> Empty<T> {
155         Empty(marker::PhantomData)
156     }
157 }
158
159 // not #[derive] because that adds a Default bound on T,
160 // which isn't necessary.
161 #[stable(feature = "iter_empty", since = "1.2.0")]
162 impl<T> Default for Empty<T> {
163     fn default() -> Empty<T> {
164         Empty(marker::PhantomData)
165     }
166 }
167
168 /// Creates an iterator that yields nothing.
169 ///
170 /// # Examples
171 ///
172 /// Basic usage:
173 ///
174 /// ```
175 /// use std::iter;
176 ///
177 /// // this could have been an iterator over i32, but alas, it's just not.
178 /// let mut nope = iter::empty::<i32>();
179 ///
180 /// assert_eq!(None, nope.next());
181 /// ```
182 #[stable(feature = "iter_empty", since = "1.2.0")]
183 pub fn empty<T>() -> Empty<T> {
184     Empty(marker::PhantomData)
185 }
186
187 /// An iterator that yields an element exactly once.
188 ///
189 /// This `struct` is created by the [`once`] function. See its documentation for more.
190 ///
191 /// [`once`]: fn.once.html
192 #[derive(Clone, Debug)]
193 #[stable(feature = "iter_once", since = "1.2.0")]
194 pub struct Once<T> {
195     inner: ::option::IntoIter<T>
196 }
197
198 #[stable(feature = "iter_once", since = "1.2.0")]
199 impl<T> Iterator for Once<T> {
200     type Item = T;
201
202     fn next(&mut self) -> Option<T> {
203         self.inner.next()
204     }
205
206     fn size_hint(&self) -> (usize, Option<usize>) {
207         self.inner.size_hint()
208     }
209 }
210
211 #[stable(feature = "iter_once", since = "1.2.0")]
212 impl<T> DoubleEndedIterator for Once<T> {
213     fn next_back(&mut self) -> Option<T> {
214         self.inner.next_back()
215     }
216 }
217
218 #[stable(feature = "iter_once", since = "1.2.0")]
219 impl<T> ExactSizeIterator for Once<T> {
220     fn len(&self) -> usize {
221         self.inner.len()
222     }
223 }
224
225 #[unstable(feature = "trusted_len", issue = "37572")]
226 unsafe impl<T> TrustedLen for Once<T> {}
227
228 #[unstable(feature = "fused", issue = "35602")]
229 impl<T> FusedIterator for Once<T> {}
230
231 /// Creates an iterator that yields an element exactly once.
232 ///
233 /// This is commonly used to adapt a single value into a [`chain`] of other
234 /// kinds of iteration. Maybe you have an iterator that covers almost
235 /// everything, but you need an extra special case. Maybe you have a function
236 /// which works on iterators, but you only need to process one value.
237 ///
238 /// [`chain`]: trait.Iterator.html#method.chain
239 ///
240 /// # Examples
241 ///
242 /// Basic usage:
243 ///
244 /// ```
245 /// use std::iter;
246 ///
247 /// // one is the loneliest number
248 /// let mut one = iter::once(1);
249 ///
250 /// assert_eq!(Some(1), one.next());
251 ///
252 /// // just one, that's all we get
253 /// assert_eq!(None, one.next());
254 /// ```
255 ///
256 /// Chaining together with another iterator. Let's say that we want to iterate
257 /// over each file of the `.foo` directory, but also a configuration file,
258 /// `.foorc`:
259 ///
260 /// ```no_run
261 /// use std::iter;
262 /// use std::fs;
263 /// use std::path::PathBuf;
264 ///
265 /// let dirs = fs::read_dir(".foo").unwrap();
266 ///
267 /// // we need to convert from an iterator of DirEntry-s to an iterator of
268 /// // PathBufs, so we use map
269 /// let dirs = dirs.map(|file| file.unwrap().path());
270 ///
271 /// // now, our iterator just for our config file
272 /// let config = iter::once(PathBuf::from(".foorc"));
273 ///
274 /// // chain the two iterators together into one big iterator
275 /// let files = dirs.chain(config);
276 ///
277 /// // this will give us all of the files in .foo as well as .foorc
278 /// for f in files {
279 ///     println!("{:?}", f);
280 /// }
281 /// ```
282 #[stable(feature = "iter_once", since = "1.2.0")]
283 pub fn once<T>(value: T) -> Once<T> {
284     Once { inner: Some(value).into_iter() }
285 }