stream_fusion/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#![feature(impl_trait_in_assoc_type)]
#![feature(iter_next_chunk)]
#![feature(maybe_uninit_uninit_array)]
#![feature(core_intrinsics)]

use std::{future::Future, intrinsics::transmute_unchecked, marker::PhantomData, mem::MaybeUninit};

use futures_lite::{future::yield_now, StreamExt};
use futures_util::{select, stream::FuturesUnordered, FutureExt};
use tokio::task::{JoinError, JoinHandle};

pub enum Step<T> {
    NotYet,
    Ready(T),
    Done,
}

impl<T> Step<T> {
    #[inline]
    pub fn map<G, F>(self, mut f: F) -> Step<G>
    where
        F: FnMut(T) -> G,
    {
        match self {
            Step::NotYet => Step::NotYet,
            Step::Ready(ready) => Step::Ready((f)(ready)),
            Step::Done => Step::Done,
        }
    }

    #[inline]
    pub fn and_then<G, F>(self, mut f: F) -> Step<G>
    where
        F: FnMut(T) -> Step<G>,
    {
        match self {
            Step::NotYet => Step::NotYet,
            Step::Ready(ready) => (f)(ready),
            Step::Done => Step::Done,
        }
    }
}

pub trait Morsel: 'static + Send {
    type Item;

    fn next(&mut self) -> Step<Self::Item>;
}

pub trait Source {
    type Item;
    type Morsel: Morsel<Item = Self::Item>;
    type NextFuture<'next>: 'next + Future<Output = Option<Self::Morsel>>
    where
        Self: 'next;

    fn next(&mut self) -> Self::NextFuture<'_>;
}

pub trait Transformer<I>: 'static + Clone + Send {
    type Item;

    fn next(&mut self, input: I) -> Step<Self::Item>;
}

pub trait Consumer<I>: 'static + Clone + Send {
    type Return: 'static + Send;

    fn consume(&mut self, input: Step<I>) -> Step<()>;

    fn take(self) -> Self::Return;
}

#[derive(Clone)]
pub struct Id;

impl<I> Transformer<I> for Id {
    type Item = I;

    #[inline]
    fn next(&mut self, input: I) -> Step<Self::Item> {
        Step::Ready(input)
    }
}

#[derive(Clone)]
pub struct Map<T, F> {
    upper: T,
    f: F,
}

impl<T, F> Map<T, F> {
    pub(crate) fn new(upper: T, f: F) -> Self {
        Map { upper, f }
    }
}

impl<I, T, G, F> Transformer<I> for Map<T, F>
where
    T: Transformer<I>,
    F: 'static + Fn(T::Item) -> G + Clone + Send,
{
    type Item = G;

    #[inline]
    fn next(&mut self, input: I) -> Step<Self::Item> {
        self.upper.next(input).map(&self.f)
    }
}

#[derive(Clone)]
pub struct Never;

impl<I> Consumer<I> for Never {
    type Return = ();

    #[inline]
    fn consume(&mut self, input: Step<I>) -> Step<()> {
        let _ = input;
        Step::NotYet
    }

    #[inline]
    fn take(self) -> Self::Return {
        ()
    }
}

#[derive(Clone)]
pub struct Reduce<Acc, F> {
    acc: Option<Acc>,
    f: F,
}

impl<Acc, F> Reduce<Acc, F>
where
    F: Fn(Acc, Acc) -> Acc,
{
    pub(crate) fn new(f: F) -> Self {
        Self { acc: None, f }
    }
}

impl<Acc, F> Consumer<Acc> for Reduce<Acc, F>
where
    Acc: 'static + Send + Clone,
    F: 'static + Fn(Acc, Acc) -> Acc + Send + Clone,
{
    type Return = Option<Acc>;

    #[inline]
    fn consume(&mut self, input: Step<Acc>) -> Step<()> {
        match input {
            Step::NotYet => Step::NotYet,
            Step::Ready(item) => {
                match self.acc.take() {
                    Some(acc) => self.acc = Some((self.f)(acc, item)),
                    None => self.acc = Some(item),
                }
                Step::NotYet
            }
            Step::Done => Step::Done,
        }
    }

    #[inline]
    fn take(self) -> Self::Return {
        self.acc
    }
}

pub struct Stream<S, T, C> {
    source: S,
    transformer: T,
    consumer: C,
}

impl<S> Stream<S, Id, Never>
where
    S: Source,
{
    fn new(source: S) -> Self {
        Stream {
            source,
            transformer: Id,
            consumer: Never,
        }
    }
}

impl<S, T, C> Stream<S, T, C>
where
    S: Source,
    T: Transformer<S::Item>,
    C: Consumer<T::Item>,
{
    #[inline]
    pub async fn execute<const N: usize>(&mut self) -> Option<JoinHandle<C::Return>> {
        self.source.next().await.map(|mut morsel| {
            let mut transformer = self.transformer.clone();
            let mut consumer = self.consumer.clone();
            tokio::spawn(async move {
                let mut step = 0;
                loop {
                    if step == N {
                        yield_now().await;
                    }
                    let consumed =
                        consumer.consume(morsel.next().and_then(|item| transformer.next(item)));
                    match consumed {
                        Step::NotYet => {}
                        Step::Done => return consumer.take(),
                        _ => unreachable!(),
                    }
                    step += 1;
                }
            })
        })
    }

    #[inline]
    pub fn map<G, F>(self, f: F) -> Stream<S, Map<T, F>, C>
    where
        F: 'static + Fn(T::Item) -> G + Clone + Send,
    {
        Stream {
            source: self.source,
            transformer: Map::new(self.transformer, f),
            consumer: self.consumer,
        }
    }

    #[inline]
    pub async fn reduce<F, const N: usize>(self, f: F) -> Result<Option<T::Item>, JoinError>
    where
        T::Item: 'static + Send + Clone,
        F: 'static + Fn(T::Item, T::Item) -> T::Item + Send + Clone,
    {
        let mut stream = Stream {
            source: self.source,
            transformer: self.transformer,
            consumer: Reduce::new(f.clone()),
        };
        let mut result = None;

        let mut tasks = FuturesUnordered::new();
        loop {
            select! {
                task = stream.execute::<N>().fuse() => match task {
                    Some(task) => tasks.push(task),
                    None => break,
                },
                task = tasks.next().fuse() => match task {
                    Some(item) => {
                        let item = item?;
                        match result.take() {
                            Some(inner) => {
                                result = item.map(|item| (f)(inner, item));
                            }
                            None => {
                                result = item;
                            }
                        }
                    }
                    _ => {}
                },
            }
        }

        loop {
            match tasks.next().await {
                Some(item) => {
                    let item = item?;
                    match result.take() {
                        Some(inner) => {
                            result = item.map(|item| (f)(inner, item));
                        }
                        None => {
                            result = item;
                        }
                    }
                }
                None => break,
            }
        }

        Ok(result)
    }
}

pub struct ChunkMorsel<T, const N: usize> {
    chunk: [MaybeUninit<T>; N],
    size: usize,
    pos: usize,
}

impl<T: 'static + Send, const N: usize> Morsel for ChunkMorsel<T, N> {
    type Item = T;

    #[inline]
    fn next(&mut self) -> Step<Self::Item> {
        if self.pos == self.size {
            return Step::Done;
        }
        let item = unsafe { self.chunk.get_unchecked(self.pos).assume_init_read() };
        self.pos += 1;
        Step::Ready(item)
    }
}

impl<T, const N: usize> ChunkMorsel<T, N> {
    fn new(chunk: [MaybeUninit<T>; N], size: usize) -> Self {
        Self {
            chunk,
            size,
            pos: 0,
        }
    }
}

pub struct WindowIterator<I, const N: usize> {
    iter: I,
    done: bool,
    _marker: PhantomData<[(); N]>,
}

impl<I, const N: usize> WindowIterator<I, N> {
    #[inline]
    pub fn from(iter: I) -> Self {
        WindowIterator {
            iter,
            done: false,
            _marker: PhantomData,
        }
    }
}

impl<I, const N: usize> Source for WindowIterator<I, N>
where
    I: Iterator,
    I::Item: 'static + Send,
{
    type Item = I::Item;

    type Morsel = ChunkMorsel<Self::Item, N>;

    type NextFuture<'next> = impl 'next + Future<Output = Option<Self::Morsel>>
    where
        Self: 'next;

    #[inline]
    fn next(&mut self) -> Self::NextFuture<'_> {
        async {
            if self.done {
                return None;
            }
            Some(match self.iter.next_chunk::<N>() {
                Ok(chunk) => ChunkMorsel::new(unsafe { transmute_unchecked(chunk) }, N),
                Err(iter) => {
                    self.done = true;
                    let mut chunk = MaybeUninit::uninit_array();
                    let mut size = 0;
                    for (id, item) in iter.enumerate() {
                        unsafe {
                            chunk.get_unchecked_mut(id).write(item);
                        }
                        size += 1;
                    }
                    ChunkMorsel::new(chunk, size)
                }
            })
        }
    }
}

pub trait IntoFusion {
    type Source: Source;

    fn fusion(self) -> Stream<Self::Source, Id, Never>;
}

impl<S: Source> IntoFusion for S {
    type Source = Self;

    #[inline]
    fn fusion(self) -> Stream<Self::Source, Id, Never> {
        Stream::new(self)
    }
}

#[cfg(test)]
mod tests {

    use crate::{IntoFusion, WindowIterator};

    #[tokio::test]
    async fn chain() {
        let i = WindowIterator::<_, 512>::from((0..4096).into_iter());
        let result = i
            .fusion()
            .map(|item| item + 1)
            .map(|item| item + 1)
            .reduce::<_, 32>(|r, item| r + item)
            .await
            .unwrap();

        let expect = (0..4096)
            .into_iter()
            .map(|item| item + 1)
            .map(|item| item + 1)
            .reduce(|r, item| r + item);
        assert_eq!(result, expect);
    }
}