-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathdeluge_ext.rs
991 lines (903 loc) · 26.7 KB
/
deluge_ext.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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
use std::default::Default;
use std::future::Future;
use crate::deluge::Deluge;
use crate::ops::*;
impl<T> DelugeExt for T where T: Deluge {}
/// Exposes easy to use Deluge operations. **This should be your first step**
pub trait DelugeExt: Deluge {
/// Resolves to true if all of the calls to `F` return true
/// for each element of the deluge.
/// Evaluates the elements concurrently and short circuits evaluation
/// on a first failure.
///
/// # Examples
///
/// ```
/// use deluge::*;
///
/// # futures::executor::block_on(async {
/// let result = [1, 2, 3, 4]
/// .into_deluge()
/// .all(None, |x| async move { x < 5 })
/// .await;
///
/// assert!(result);
///
/// let result = [1, 2, 3, 4]
/// .into_deluge()
/// .all(None, |x| async move { x < 3 })
/// .await;
///
/// assert!(!result);
/// # });
/// ```
fn all<'a, Fut, F>(self, concurrency: impl Into<Option<usize>>, f: F) -> All<'a, Self, Fut, F>
where
F: Fn(Self::Item) -> Fut + Send + 'a,
Fut: Future<Output = bool> + Send,
Self: Sized,
{
All::new(self, concurrency, f)
}
/// A parallel version of `DelugeExt::all`.
/// Resolves to true if all of the calls to `F` return true
/// for each element of the deluge.
/// Evaluates the elements in parallel and short circuits evaluation
/// on a first failure.
///
/// # Examples
///
/// ```
/// use deluge::*;
///
/// # futures::executor::block_on(async {
/// let result = [1, 2, 3, 4]
/// .into_deluge()
/// .all_par(None, None, |x| async move { x < 5 })
/// .await;
///
/// assert!(result);
///
/// let result = [1, 2, 3, 4]
/// .into_deluge()
/// .all_par(None, None, |x| async move { x < 3 })
/// .await;
///
/// assert!(!result);
/// # });
/// ```
fn all_par<'a, Fut, F>(
self,
worker_count: impl Into<Option<usize>>,
worker_concurrency: impl Into<Option<usize>>,
f: F,
) -> AllPar<'a, Self, Fut, F>
where
F: Fn(Self::Item) -> Fut + Send + 'a,
Fut: Future<Output = bool> + Send,
Self: Sized,
{
AllPar::new(self, worker_count, worker_concurrency, f)
}
/// Resolves to true if any of the calls to `F` return true
/// for any element of the deluge.
/// Evaluates the elements concurrently and short circuits evaluation
/// on a successful result.
///
/// # Examples
///
/// ```
/// use deluge::*;
///
/// # futures::executor::block_on(async {
/// let result = [1, 2, 3, 4]
/// .into_deluge()
/// .any(None, |x| async move { x == 4 })
/// .await;
///
/// assert!(result);
///
/// let result = [1, 2, 3, 4]
/// .into_deluge()
/// .any(None, |x| async move { x > 10 })
/// .await;
///
/// assert!(!result);
/// # });
/// ```
fn any<'a, Fut, F>(self, concurrency: impl Into<Option<usize>>, f: F) -> Any<'a, Self, Fut, F>
where
F: Fn(Self::Item) -> Fut + Send + 'a,
Fut: Future<Output = bool> + Send,
Self: Sized,
{
Any::new(self, concurrency, f)
}
/// A parallel version of `DelugeExt::any`.
/// Resolves to true if any of the calls to `F` return true
/// for any element of the deluge.
/// Evaluates the elements in parallel and short circuits evaluation
/// on a successful result.
///
/// # Examples
///
/// ```
/// use deluge::*;
///
/// # futures::executor::block_on(async {
/// let result = [1, 2, 3, 4]
/// .into_deluge()
/// .any_par(None, None, |x| async move { x == 4 })
/// .await;
///
/// assert!(result);
///
/// let result = [1, 2, 3, 4]
/// .into_deluge()
/// .any_par(None, None, |x| async move { x > 10 })
/// .await;
///
/// assert!(!result);
/// # });
/// ```
fn any_par<'a, Fut, F>(
self,
worker_count: impl Into<Option<usize>>,
worker_concurrency: impl Into<Option<usize>>,
f: F,
) -> AnyPar<'a, Self, Fut, F>
where
F: Fn(Self::Item) -> Fut + Send + 'a,
Fut: Future<Output = bool> + Send,
Self: Sized,
{
AnyPar::new(self, worker_count, worker_concurrency, f)
}
/// Chains two deluges together
///
/// # Examples
///
/// ```
/// use deluge::*;
///
/// # futures::executor::block_on(async {
/// let result = [1, 2, 3, 4]
/// .into_deluge()
/// .chain([5, 6, 7, 8].into_deluge())
/// .collect::<Vec<usize>>(None)
/// .await;
///
/// assert_eq!(result.len(), 8);
/// assert_eq!(result, vec![1, 2, 3, 4, 5, 6, 7, 8]);
/// # })
/// ```
fn chain<'a, Del2>(self, deluge2: Del2) -> Chain<'a, Self, Del2>
where
Del2: for<'x> Deluge<Item = Self::Item, Output<'x> = Self::Output<'x>> + 'static,
Self: Sized,
{
Chain::new(self, deluge2)
}
/// Consumes all the items in a deluge and returns
/// the number of elements that were observed.
///
/// # Examples
///
/// ```
/// use deluge::*;
///
/// # futures::executor::block_on(async {
/// let result = [1, 2, 3, 4]
/// .into_deluge()
/// .count();
///
/// assert_eq!(result, 4);
/// # })
/// ```
fn count(self) -> usize
where
Self: Sized,
{
count(self)
}
/// Transforms each element by applying an asynchronous function `f` to it
///
/// # Examples
///
/// ```
/// use deluge::*;
///
/// # futures::executor::block_on(async {
/// let result = [1, 2, 3, 4]
/// .into_deluge()
/// .map(|x| async move { x * 2 })
/// .collect::<Vec<usize>>(None)
/// .await;
///
/// assert_eq!(vec![2, 4, 6, 8], result);
/// # });
/// ```
fn map<Fut, F>(self, f: F) -> Map<Self, F>
where
F: Fn(Self::Item) -> Fut + Send,
Fut: Future + Send,
Self: Sized,
{
Map::new(self, f)
}
/// Leaves the elements for which `f` returns a promise evaluating to `true`.
///
/// # WARNING
///
/// Currently has [a breaking bug](https://github.com/mkawalec/deluge/issues/1).
///
/// # Examples
///
// ```
// use deluge::*;
//
// # futures::executor::block_on(async {
// let result = (0..10).into_deluge()
// .filter(|x| async move { x % 2 == 0 })
// .collect::<Vec<usize>>(None)
// .await;
//
// assert_eq!(vec![0, 2, 4, 6, 8], result);
// # });
//
// ```
// 27.10.2022: Commented out filter until the issue#1 is solved
/*fn filter<'a, F>(self, f: F) -> Filter<'a, Self, F>
where
for<'b> F: XFn<'b, Self::Item, bool> + Send + 'b,
Self: Sized,
{
Filter::new(self, f)
}*/
/// Filters out elements for which a function returns `None`,
/// substitutes the elements for the ones there it returns `Some(new_value)`.
///
/// # Examples
///
/// ```
/// use deluge::*;
///
/// # futures::executor::block_on(async {
/// let result = (0..10).into_deluge()
/// .filter_map(|x| async move { if x % 2 == 0 {
/// Some(x.to_string())
/// } else {
/// None
/// }
/// })
/// .collect::<Vec<String>>(None)
/// .await;
///
/// assert_eq!(vec![0.to_string(), 2.to_string(), 4.to_string(), 6.to_string(), 8.to_string()], result);
/// # });
///
/// ```
fn filter_map<Fut, F>(self, f: F) -> FilterMap<Self, F>
where
F: Fn(Self::Item) -> Fut + Send,
Fut: Future + Send,
Self: Sized,
{
FilterMap::new(self, f)
}
/// Returns the first element of the input deluge and then finishes
///
/// # Examples
/// ```
/// use deluge::*;
///
/// # futures::executor::block_on(async {
/// let result = (0..10).into_deluge()
/// .first()
/// .collect::<Vec<usize>>(None)
/// .await;
///
/// assert_eq!(vec![0], result);
/// # });
///
/// ```
fn first(self) -> First<Self>
where
Self: Sized,
{
First::new(self)
}
/// Concurrently accummulates values in the accummulator. The degree of concurrency
/// can either be unlimited (the default) or limited depending on the requirements.
///
/// # Examples
///
/// Unlimited concurrency:
///
/// ```
/// use deluge::*;
///
/// # futures::executor::block_on(async {
/// let result = (0..100).into_deluge()
/// .fold(None, 0, |acc, x| async move { acc + x })
/// .await;
///
/// assert_eq!(result, 4950);
/// # });
/// ```
///
/// Concurrency limited to at most ten futures evaluated at once:
///
/// ```
/// use deluge::*;
///
/// # futures::executor::block_on(async {
/// let result = (0..100).into_deluge()
/// .fold(10, 0, |acc, x| async move { acc + x })
/// .await;
///
/// assert_eq!(result, 4950);
/// # });
/// ```
fn fold<Acc, F, Fut>(
self,
concurrency: impl Into<Option<usize>>,
acc: Acc,
f: F,
) -> Fold<Self, Acc, F, Fut>
where
F: FnMut(Acc, Self::Item) -> Fut + Send,
Fut: Future<Output = Acc> + Send,
Self: Sized,
{
Fold::new(self, concurrency, acc, f)
}
/// Accummulates values in an accummulator with futures evaluated in parallel.
/// The number of workers spawned and concurrency for each worker can be controlled.
/// By default the number of workers equals the number of logical cpus
/// and concurrency for each worker is the total number of futures to evaluate
/// divided by the number of available workers.
///
/// # Examples
///
/// ```
/// use deluge::*;
///
/// # futures::executor::block_on(async {
/// let result = (0..100).into_deluge()
/// .fold_par(None, None, 0, |acc, x| async move { acc + x })
/// .await;
///
/// assert_eq!(result, 4950);
/// # });
/// ```
#[cfg(feature = "async-runtime")]
fn fold_par<'a, Acc, F, Fut>(
self,
worker_count: impl Into<Option<usize>>,
worker_concurrency: impl Into<Option<usize>>,
acc: Acc,
f: F,
) -> FoldPar<'a, Self, Acc, F, Fut>
where
F: FnMut(Acc, Self::Item) -> Fut + Send + 'a,
Fut: Future<Output = Acc> + Send + 'a,
Self: Sized,
{
FoldPar::new(self, worker_count, worker_concurrency, acc, f)
}
/// Returns the last element of the input deluge and then finishes
///
/// # Examples
/// ```
/// use deluge::*;
///
/// # futures::executor::block_on(async {
/// let result = (0..10).into_deluge()
/// .last()
/// .collect::<Vec<usize>>(None)
/// .await;
///
/// assert_eq!(vec![9], result);
/// # });
///
/// ```
fn last(self) -> Last<Self>
where
Self: Sized,
{
Last::new(self)
}
/// Consumes at most `how_many` elements from the Deluge, ignoring the rest.
///
/// # Examples
///
/// ```
/// use deluge::*;
///
/// # futures::executor::block_on(async {
/// let result = (0..100).into_deluge()
/// .take(1)
/// .fold(None, 0, |acc, x| async move { acc + x })
/// .await;
///
/// assert_eq!(0, result);
/// # });
/// ```
fn take(self, how_many: usize) -> Take<Self>
where
Self: Sized,
{
Take::new(self, how_many)
}
/// Combines two Deluges into one with elements being
/// tuples of subsequent elements from each
///
/// # Examples
///
/// ```
/// use deluge::*;
///
/// # futures::executor::block_on(async {
/// let result = (0..100).rev()
/// .into_deluge()
/// .zip((0..90).into_deluge(), None)
/// .collect::<Vec<(u64, u64)>>(None)
/// .await;
///
/// assert_eq!(result.len(), 90);
/// assert_eq!(result[0], (99, 0));
/// assert_eq!(result[1], (98, 1));
/// # });
/// ```
fn zip<'a, Del2>(
self,
other: Del2,
concurrency: impl Into<Option<usize>>,
) -> Zip<'a, Self, Del2>
where
Del2: Deluge + 'a,
Self: Sized,
{
Zip::new(self, other, concurrency)
}
/// Collects elements in the current `Deluge` into a collection with a desired concurrency
///
/// # Examples
///
/// ```
/// use deluge::*;
///
/// # futures::executor::block_on(async {
/// let result = (0..100).into_deluge()
/// .collect::<Vec<usize>>(None)
/// .await;
///
/// assert_eq!(result.len(), 100);
/// # });
/// ```
fn collect<'a, C>(self, concurrency: impl Into<Option<usize>>) -> Collect<'a, Self, C>
where
C: Default + Extend<Self::Item>,
Self: Sized,
{
Collect::new(self, concurrency)
}
/// Collects elements in the current `Deluge` into a collection
/// in parallel. Optionally accepts a degree of parallelism
/// and concurrency for each worker.
///
/// If the number of workers is not specified, we will default to the number of logical cpus.
/// If concurrency per worker is not specified, we will default to the total number of
/// items in a current deluge divided by the number of workers.
///
/// # Examples
///
/// ```
/// use deluge::*;
///
/// # futures::executor::block_on(async {
/// let result = (0..100).into_deluge()
/// .collect_par::<Vec<usize>>(None, None)
/// .await;
///
/// assert_eq!(result.len(), 100);
/// # });
/// ```
#[cfg(feature = "async-runtime")]
fn collect_par<'a, C>(
self,
worker_count: impl Into<Option<usize>>,
worker_concurrency: impl Into<Option<usize>>,
) -> CollectPar<'a, Self, C>
where
C: Default + Extend<Self::Item>,
Self: Sized,
{
CollectPar::new(self, worker_count, worker_concurrency)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::into_deluge::IntoDeluge;
use crate::iter::iter;
use more_asserts::{assert_gt, assert_lt};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
#[tokio::test]
async fn map_can_be_created() {
[1, 2, 3, 4].into_deluge().map(|x| async move { x * 2 });
assert_eq!(2, 2);
}
#[tokio::test]
async fn we_can_collect() {
let result = [1, 2, 3, 4].into_deluge().collect::<Vec<usize>>(None).await;
assert_eq!(vec![1, 2, 3, 4], result);
}
#[tokio::test]
async fn any_works() {
let result = [1, 2, 3, 4]
.into_deluge()
.any(None, |x| async move { x == 4 })
.await;
assert!(result);
}
#[tokio::test]
async fn any_short_circuits() {
let evaluated = Arc::new(Mutex::new(Vec::new()));
let result = [1, 2, 3, 4, 5, 6, 7]
.into_deluge()
.any(1, |x| {
let evaluated = evaluated.clone();
async move {
{
let mut evaluated = evaluated.lock().await;
evaluated.push(x);
}
tokio::time::sleep(Duration::from_millis(100 - 10 * x)).await;
x == 2
}
})
.await;
assert!(result);
// We might evaluate a little bit more than we should have, but not much more
assert_lt!(Arc::try_unwrap(evaluated).unwrap().into_inner().len(), 4);
}
#[tokio::test]
async fn any_par_works() {
let result = [1, 2, 3, 4]
.into_deluge()
.any_par(None, None, |x| async move { x == 4 })
.await;
assert!(result);
}
#[tokio::test]
async fn any_par_short_circuits() {
let evaluated = Arc::new(Mutex::new(Vec::new()));
let result = [1, 2, 3, 4, 5, 6, 7]
.into_deluge()
.any_par(2, 1, |x| {
let evaluated = evaluated.clone();
async move {
{
let mut evaluated = evaluated.lock().await;
evaluated.push(x);
}
tokio::time::sleep(Duration::from_millis(100 - 10 * x)).await;
x == 2
}
})
.await;
assert!(result);
// We might evaluate a little bit more than we should have, but not much more
assert_lt!(Arc::try_unwrap(evaluated).unwrap().into_inner().len(), 5);
}
#[tokio::test]
async fn all_works() {
let result = [1, 2, 3, 4]
.into_deluge()
.all(None, |x| async move { x < 5 }).await;
assert!(result);
}
#[tokio::test]
async fn all_short_circuits() {
let evaluated = Arc::new(Mutex::new(Vec::new()));
let result = [1, 2, 3, 4, 5, 6, 7]
.into_deluge()
.all(1, |x| {
let evaluated = evaluated.clone();
async move {
{
let mut evaluated = evaluated.lock().await;
evaluated.push(x);
}
tokio::time::sleep(Duration::from_millis(100 - 10 * x)).await;
x < 3
}
})
.await;
assert!(!result);
// We might evaluate a little bit more than we should have, but not much more
assert_lt!(Arc::try_unwrap(evaluated).unwrap().into_inner().len(), 5);
}
#[tokio::test]
async fn all_par_works() {
let result = [1, 2, 3, 4]
.into_deluge()
.all_par(None, None, |x| async move { x < 5 })
.await;
assert!(result);
}
#[tokio::test]
async fn all_par_short_circuits() {
let evaluated = Arc::new(Mutex::new(Vec::new()));
let result = [1, 2, 3, 4, 5, 6, 7]
.into_deluge()
.all_par(2, 1, |x| {
let evaluated = evaluated.clone();
async move {
{
let mut evaluated = evaluated.lock().await;
evaluated.push(x);
}
tokio::time::sleep(Duration::from_millis(100 - 10 * x)).await;
x < 3
}
})
.await;
assert!(!result);
// We might evaluate a little bit more than we should have, but not much more
assert_lt!(Arc::try_unwrap(evaluated).unwrap().into_inner().len(), 7);
}
#[tokio::test]
async fn chain_works() {
let result = [1, 2, 3, 4]
.into_deluge()
.chain([5, 6, 7, 8].into_deluge())
.collect::<Vec<usize>>(None)
.await;
assert_eq!(result.len(), 8);
assert_eq!(result, vec![1, 2, 3, 4, 5, 6, 7, 8]);
}
#[tokio::test]
async fn count_works() {
let result = [1, 2, 3, 4].into_deluge().count();
assert_eq!(result, 4);
}
#[tokio::test]
async fn we_can_mult() {
let result = [1, 2, 3, 4]
.into_deluge()
.map(|x| async move { x * 2 })
.collect::<Vec<usize>>(None)
.await;
assert_eq!(vec![2, 4, 6, 8], result);
}
#[tokio::test]
async fn filter_map_works() {
let result = [1, 2, 3, 4]
.into_deluge()
.filter_map(|x| async move {
if x % 2 == 0 {
Some("yes")
} else {
None
}
})
.collect::<Vec<&str>>(None)
.await;
assert_eq!(vec!["yes", "yes"], result);
}
#[tokio::test]
async fn we_can_go_between_values_and_deluges() {
let result = [1, 2, 3, 4]
.into_deluge()
.map(|x| async move { x * 2 })
.collect::<Vec<usize>>(None)
.await
.into_deluge()
.map(|x| async move { x * 2 })
.fold(None, 0, |acc, x| async move { acc + x })
.await;
assert_eq!(result, 40);
}
#[tokio::test]
async fn we_wait_cuncurrently() {
let start = Instant::now();
let result = (0..100)
.into_deluge()
.map(|idx| async move {
tokio::time::sleep(Duration::from_millis(100 - (idx as u64))).await;
idx
})
.collect::<Vec<usize>>(None)
.await;
let iteration_took = Instant::now() - start;
assert_lt!(iteration_took.as_millis(), 200);
assert_eq!(result.len(), 100);
result
.into_iter()
.enumerate()
.for_each(|(idx, elem)| assert_eq!(idx, elem));
}
#[tokio::test]
async fn concurrency_limit() {
let start = Instant::now();
let result = (0..15)
.into_deluge()
.map(|idx| async move {
tokio::time::sleep(Duration::from_millis(50)).await;
idx
})
.collect::<Vec<usize>>(5)
.await;
let iteration_took = Instant::now() - start;
assert_gt!(iteration_took.as_millis(), 150);
assert_lt!(iteration_took.as_millis(), 200);
assert_eq!(result.len(), 15);
}
#[tokio::test]
async fn take_until_a_limit() {
let result = (0..100)
.into_deluge()
.take(10)
.fold(None, 0, |acc, idx| async move { acc + idx })
.await;
assert_eq!(result, 45);
}
#[tokio::test]
async fn first_works() {
let result = (0..100)
.into_deluge()
.first()
.collect::<Vec<usize>>(None)
.await;
assert_eq!(result, vec![0]);
}
#[tokio::test]
async fn last_works() {
let result = (0..100)
.into_deluge()
.last()
.collect::<Vec<usize>>(None)
.await;
assert_eq!(result, vec![99]);
}
#[cfg(feature = "tokio")]
#[tokio::test]
async fn concurrent_fold() {
let start = Instant::now();
let result = (0..100)
.into_deluge()
.map(|idx| async move {
tokio::time::sleep(Duration::from_millis(100)).await;
idx
})
.fold(None, 0, |acc, idx| async move { acc + idx })
.await;
let iteration_took = Instant::now() - start;
assert_lt!(iteration_took.as_millis(), 200);
assert_eq!(result, 4950);
}
#[cfg(feature = "tokio")]
#[tokio::test]
async fn parallel_test() {
let start = Instant::now();
let result = (0..150)
.into_deluge()
.map(|idx| async move {
tokio::time::sleep(Duration::from_millis(50)).await;
idx
})
.collect_par::<Vec<usize>>(10, 5)
.await;
let iteration_took = Instant::now() - start;
assert_gt!(iteration_took.as_millis(), 150);
assert_lt!(iteration_took.as_millis(), 200);
assert_eq!(result.len(), 150);
}
#[cfg(feature = "async-std")]
#[async_std::test]
async fn parallel_test() {
let start = Instant::now();
let result = (0..150)
.into_deluge()
.map(|idx| async move {
async_std::task::sleep(Duration::from_millis(50)).await;
idx
})
.collect_par::<Vec<usize>>(10, 5)
.await;
let iteration_took = Instant::now() - start;
assert_gt!(iteration_took.as_millis(), 150);
assert_lt!(iteration_took.as_millis(), 200);
assert_eq!(result.len(), 150);
}
#[cfg(feature = "tokio")]
#[tokio::test]
async fn parallel_fold() {
let start = Instant::now();
let result = (0..150)
.into_deluge()
.map(|idx| async move {
tokio::time::sleep(Duration::from_millis(50)).await;
idx
})
.fold_par(10, 5, 0, |acc, x| async move { acc + x })
.await;
let iteration_took = Instant::now() - start;
assert_gt!(iteration_took.as_millis(), 150);
assert_lt!(iteration_took.as_millis(), 200);
assert_eq!(result, 11175);
}
#[cfg(feature = "async-std")]
#[async_std::test]
async fn parallel_fold() {
let start = Instant::now();
let result = (0..150)
.into_deluge()
.map(|idx| async move {
async_std::task::sleep(Duration::from_millis(50)).await;
idx
})
.fold_par(10, 5, 0, |acc, x| async move { acc + x })
.await;
let iteration_took = Instant::now() - start;
assert_gt!(iteration_took.as_millis(), 150);
assert_lt!(iteration_took.as_millis(), 200);
assert_eq!(result, 11175);
}
#[cfg(feature = "async-runtime")]
#[tokio::test]
async fn zips_work() {
let result = (0..100)
.into_deluge()
.zip((10..90).into_deluge(), None)
.collect::<Vec<(usize, usize)>>(None)
.await;
assert_eq!(result.len(), 80);
}
#[cfg(feature = "async-runtime")]
#[tokio::test]
async fn zips_inverted_waits() {
let other_deluge = (0..90).into_deluge().map(|idx| async move {
// We sleep here so first element from this Deluge
// only becomes available with the last element from the next one
tokio::time::sleep(Duration::from_millis(idx)).await;
idx
});
let result = (0..100).rev()
.into_deluge()
.map(|idx| async move {
tokio::time::sleep(Duration::from_millis(idx)).await;
idx
})
.zip(other_deluge, None)
.collect::<Vec<(u64, u64)>>(None)
.await;
assert_eq!(result.len(), 90);
for (idx, (fst, snd)) in result.into_iter().enumerate() {
assert_eq!(idx as u64, 99 - fst);
assert_eq!(idx as u64, snd);
}
}
// Filter doesn't want to build, I have no idea why.
// Let's move to augmenting the collector first
/*
#[tokio::test]
async fn filter_works() {
let result = (0..100)
.into_deluge()
.filter(|idx| async move {
idx % 2 == 0
})
.collect::<Vec<usize>>().await;
assert_eq!(result.len(), 50);
result.into_iter()
.enumerate()
.for_each(|(idx, elem)| assert_eq!(idx * 2, elem));
}
*/
}