]> git.lizzy.rs Git - rust.git/blob - src/test/ui/generic-associated-types/streaming_iterator.rs
Rollup merge of #102954 - GuillaumeGomez:cfg-hide-attr-checks, r=Manishearth
[rust.git] / src / test / ui / generic-associated-types / streaming_iterator.rs
1 // run-pass
2
3 use std::fmt::Display;
4
5 trait StreamingIterator {
6     type Item<'a> where Self: 'a;
7     // Applying the lifetime parameter `'a` to `Self::Item` inside the trait.
8     fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
9 }
10
11 struct Foo<T: StreamingIterator + 'static> {
12     // Applying a concrete lifetime to the constructor outside the trait.
13     bar: <T as StreamingIterator>::Item<'static>,
14 }
15
16 // Users can bound parameters by the type constructed by that trait's associated type constructor
17 // of a trait using HRTB. Both type equality bounds and trait bounds of this kind are valid:
18 //FIXME(#44265): This next line should parse and be valid
19 //fn foo<T: for<'a> StreamingIterator<Item<'a>=&'a [i32]>>(_iter: T) { /* ... */ }
20 fn _foo<T>(_iter: T) where T: StreamingIterator, for<'a> T::Item<'a>: Display { /* ... */ }
21
22 // Full example of enumerate iterator
23
24 #[must_use = "iterators are lazy and do nothing unless consumed"]
25 struct StreamEnumerate<I> {
26     iter: I,
27     count: usize,
28 }
29
30 impl<I: StreamingIterator> StreamingIterator for StreamEnumerate<I> {
31     type Item<'a> = (usize, I::Item<'a>) where Self: 'a;
32     fn next<'a>(&'a mut self) -> Option<Self::Item<'a>> {
33         match self.iter.next() {
34             None => None,
35             Some(val) => {
36                 let r = Some((self.count, val));
37                 self.count += 1;
38                 r
39             }
40         }
41     }
42 }
43
44 impl<I: Iterator> StreamingIterator for I {
45     type Item<'a> = <I as Iterator>::Item where Self: 'a;
46     fn next(&mut self) -> Option<<I as StreamingIterator>::Item<'_>> {
47         Iterator::next(self)
48     }
49 }
50
51 impl<I> StreamEnumerate<I> {
52     pub fn new(iter: I) -> Self {
53         StreamEnumerate {
54             count: 0,
55             iter,
56         }
57     }
58 }
59
60 fn test_stream_enumerate() {
61     let v = vec!["a", "b", "c"];
62     let mut se = StreamEnumerate::new(v.iter());
63     while let Some(item) = se.next() {
64         assert_eq!(v[item.0], *item.1);
65     }
66     let x = Foo::<std::slice::Iter<'static, u32>> {
67         bar: &0u32,
68     };
69     assert_eq!(*x.bar, 0u32);
70 }
71
72 fn main() {
73     test_stream_enumerate();
74 }