|
| 1 | +use std::pin::Pin; |
| 2 | +use std::task::{Context, Poll}; |
| 3 | + |
| 4 | +/// A stream that moves out of a vector. |
| 5 | +#[derive(Debug)] |
| 6 | +pub struct IntoStream<T> { |
| 7 | + iter: std::vec::IntoIter<T>, |
| 8 | +} |
| 9 | + |
| 10 | +impl<T: Send> crate::stream::IntoStream for Vec<T> { |
| 11 | + type Item = T; |
| 12 | + type IntoStream = IntoStream<T>; |
| 13 | + |
| 14 | + /// Creates a consuming iterator, that is, one that moves each value out of |
| 15 | + /// the vector (from start to end). The vector cannot be used after calling |
| 16 | + /// this. |
| 17 | + /// |
| 18 | + /// # Examples |
| 19 | + /// |
| 20 | + /// ``` |
| 21 | + /// let v = vec!["a".to_string(), "b".to_string()]; |
| 22 | + /// for s in v.into_stream() { |
| 23 | + /// // s has type String, not &String |
| 24 | + /// println!("{}", s); |
| 25 | + /// } |
| 26 | + /// ``` |
| 27 | + #[inline] |
| 28 | + fn into_stream(mut self) -> IntoStream<T> { |
| 29 | + let iter = self.into_iter(); |
| 30 | + IntoStream { iter } |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +impl<T: Send> futures_core::stream::Stream for IntoStream<T> { |
| 35 | + type Item = T; |
| 36 | + |
| 37 | + fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> { |
| 38 | + Poll::Ready(self.iter.next()) |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +/// Slice stream. |
| 43 | +#[derive(Debug)] |
| 44 | +pub struct Stream<'a, T: 'a> { |
| 45 | + iter: std::slice::Iter<'a, T>, |
| 46 | +} |
| 47 | + |
| 48 | +impl<'a, T: Sync> futures_core::stream::Stream for Stream<'a, T> { |
| 49 | + type Item = &'a T; |
| 50 | + |
| 51 | + fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> { |
| 52 | + Poll::Ready(self.iter.next()) |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +impl<'a, T: Sync> crate::stream::IntoStream for &'a Vec<T> { |
| 57 | + type Item = &'a T; |
| 58 | + type IntoStream = Stream<'a, T>; |
| 59 | + |
| 60 | + fn into_stream(self) -> Stream<'a, T> { |
| 61 | + let iter = self.iter(); |
| 62 | + Stream { iter } |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +/// Mutable slice stream. |
| 67 | +#[derive(Debug)] |
| 68 | +pub struct StreamMut<'a, T: 'a> { |
| 69 | + iter: std::slice::IterMut<'a, T>, |
| 70 | +} |
| 71 | + |
| 72 | +impl<'a, T: Sync> futures_core::stream::Stream for StreamMut<'a, T> { |
| 73 | + type Item = &'a mut T; |
| 74 | + |
| 75 | + fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> { |
| 76 | + Poll::Ready(self.iter.next()) |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +impl<'a, T: Send + Sync> crate::stream::IntoStream for &'a mut Vec<T> { |
| 81 | + type Item = &'a mut T; |
| 82 | + |
| 83 | + type IntoStream = StreamMut<'a, T>; |
| 84 | + |
| 85 | + fn into_stream(self) -> StreamMut<'a, T> { |
| 86 | + let iter = self.iter_mut(); |
| 87 | + StreamMut { iter } |
| 88 | + } |
| 89 | +} |
0 commit comments