1 | use crate::iter::{FusedIterator, TrustedLen}; |
2 | use crate::{fmt, marker}; |
3 | |
4 | /// Creates an iterator that yields nothing. |
5 | /// |
6 | /// # Examples |
7 | /// |
8 | /// Basic usage: |
9 | /// |
10 | /// ``` |
11 | /// use std::iter; |
12 | /// |
13 | /// // this could have been an iterator over i32, but alas, it's just not. |
14 | /// let mut nope = iter::empty::<i32>(); |
15 | /// |
16 | /// assert_eq!(None, nope.next()); |
17 | /// ``` |
18 | #[stable (feature = "iter_empty" , since = "1.2.0" )] |
19 | #[rustc_const_stable (feature = "const_iter_empty" , since = "1.32.0" )] |
20 | pub const fn empty<T>() -> Empty<T> { |
21 | Empty(marker::PhantomData) |
22 | } |
23 | |
24 | /// An iterator that yields nothing. |
25 | /// |
26 | /// This `struct` is created by the [`empty()`] function. See its documentation for more. |
27 | #[must_use = "iterators are lazy and do nothing unless consumed" ] |
28 | #[stable (feature = "iter_empty" , since = "1.2.0" )] |
29 | #[rustc_diagnostic_item = "IterEmpty" ] |
30 | pub struct Empty<T>(marker::PhantomData<fn() -> T>); |
31 | |
32 | #[stable (feature = "core_impl_debug" , since = "1.9.0" )] |
33 | impl<T> fmt::Debug for Empty<T> { |
34 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
35 | f.debug_struct(name:"Empty" ).finish() |
36 | } |
37 | } |
38 | |
39 | #[stable (feature = "iter_empty" , since = "1.2.0" )] |
40 | impl<T> Iterator for Empty<T> { |
41 | type Item = T; |
42 | |
43 | fn next(&mut self) -> Option<T> { |
44 | None |
45 | } |
46 | |
47 | fn size_hint(&self) -> (usize, Option<usize>) { |
48 | (0, Some(0)) |
49 | } |
50 | } |
51 | |
52 | #[stable (feature = "iter_empty" , since = "1.2.0" )] |
53 | impl<T> DoubleEndedIterator for Empty<T> { |
54 | fn next_back(&mut self) -> Option<T> { |
55 | None |
56 | } |
57 | } |
58 | |
59 | #[stable (feature = "iter_empty" , since = "1.2.0" )] |
60 | impl<T> ExactSizeIterator for Empty<T> { |
61 | fn len(&self) -> usize { |
62 | 0 |
63 | } |
64 | } |
65 | |
66 | #[unstable (feature = "trusted_len" , issue = "37572" )] |
67 | unsafe impl<T> TrustedLen for Empty<T> {} |
68 | |
69 | #[stable (feature = "fused" , since = "1.26.0" )] |
70 | impl<T> FusedIterator for Empty<T> {} |
71 | |
72 | // not #[derive] because that adds a Clone bound on T, |
73 | // which isn't necessary. |
74 | #[stable (feature = "iter_empty" , since = "1.2.0" )] |
75 | impl<T> Clone for Empty<T> { |
76 | fn clone(&self) -> Empty<T> { |
77 | Empty(marker::PhantomData) |
78 | } |
79 | } |
80 | |
81 | // not #[derive] because that adds a Default bound on T, |
82 | // which isn't necessary. |
83 | #[stable (feature = "iter_empty" , since = "1.2.0" )] |
84 | impl<T> Default for Empty<T> { |
85 | fn default() -> Empty<T> { |
86 | Empty(marker::PhantomData) |
87 | } |
88 | } |
89 | |