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
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under both the MIT license found in the
 * LICENSE-MIT file in the root directory of this source tree and the Apache
 * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
 * of this source tree.
 */

#![deny(warnings, missing_docs, clippy::all, broken_intra_doc_links)]
#![feature(never_type)]

//! Crate extending functionality of [`futures`] crate

use anyhow::format_err;
use bytes_old::Bytes;
use futures::sync::{mpsc, oneshot};
use futures::{
    future, stream, try_ready, Async, AsyncSink, Future, IntoFuture, Poll, Sink, Stream,
};
use std::{
    fmt::Debug,
    io as std_io,
    time::{Duration, Instant},
};
use tokio::timer::Delay;
use tokio_io::{
    codec::{Decoder, Encoder},
    AsyncWrite,
};
use tokio_threadpool::blocking;

pub mod bounded_traversal;
mod bytes_stream;
pub mod decode;
pub mod encode;
mod futures_ordered;
pub mod io;
mod launch;
mod select_all;
mod split_err;
mod stream_clone;
mod stream_wrappers;
mod streamfork;

pub use crate::bytes_stream::{BytesStream, BytesStreamFuture};
pub use crate::futures_ordered::{futures_ordered, FuturesOrdered};
pub use crate::launch::top_level_launch;
pub use crate::select_all::{select_all, SelectAll};
pub use crate::split_err::split_err;
pub use crate::stream_clone::stream_clone;
pub use crate::stream_wrappers::{CollectNoConsume, CollectTo};

// Re-exports. Those are used by the macros in this crate in order to reference a stable version of
// what "futures" means.
pub use futures as futures_reexport;

/// Map `Item` and `Error` to `()`
///
/// Adapt an existing `Future` to return unit `Item` and `Error`, while still
/// waiting for the underlying `Future` to complete.
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Discard<F>(F);

impl<F> Discard<F> {
    /// Create instance wrapping `f`
    pub fn new(f: F) -> Self {
        Discard(f)
    }
}

impl<F> Future for Discard<F>
where
    F: Future,
{
    type Item = ();
    type Error = ();

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        match self.0.poll() {
            Err(_) => Err(()),
            Ok(Async::NotReady) => Ok(Async::NotReady),
            Ok(Async::Ready(_)) => Ok(Async::Ready(())),
        }
    }
}

/// Send an item over an mpsc channel, discarding both the sender and receiver-closed errors. This
/// should be used when the receiver being closed makes sending values moot, since no one is
/// interested in the results any more.
///
/// `E` is an arbitrary error type useful for getting types to match up, but it will never be
/// produced by the returned future.
#[inline]
pub fn send_discard<T, E>(
    sender: mpsc::Sender<T>,
    value: T,
) -> impl Future<Item = (), Error = E> + Send
where
    T: Send,
    E: Send,
{
    sender.send(value).then(|_| Ok(()))
}

/// Replacement for BoxFuture, deprecated in upstream futures-rs.
pub type BoxFuture<T, E> = Box<dyn Future<Item = T, Error = E> + Send>;
/// Replacement for BoxFutureNonSend, deprecated in upstream futures-rs.
pub type BoxFutureNonSend<T, E> = Box<dyn Future<Item = T, Error = E>>;
/// Replacement for BoxStream, deprecated in upstream futures-rs.
pub type BoxStream<T, E> = Box<dyn Stream<Item = T, Error = E> + Send>;
/// Replacement for BoxStreamNonSend, deprecated in upstream futures-rs.
pub type BoxStreamNonSend<T, E> = Box<dyn Stream<Item = T, Error = E>>;

/// Do something with an error if the future failed.
///
/// This is created by the `FutureExt::inspect_err` method.
#[derive(Debug)]
#[must_use = "futures do nothing unless polled"]
pub struct InspectErr<A, F>
where
    A: Future,
{
    future: A,
    f: Option<F>,
}

impl<A, F> Future for InspectErr<A, F>
where
    A: Future,
    F: FnOnce(&A::Error),
{
    type Item = A::Item;
    type Error = A::Error;

    fn poll(&mut self) -> Poll<A::Item, A::Error> {
        match self.future.poll() {
            Ok(Async::NotReady) => Ok(Async::NotReady),
            Ok(Async::Ready(e)) => Ok(Async::Ready(e)),
            Err(e) => {
                self.f.take().map_or_else(
                    // Act like a fused future
                    || Ok(Async::NotReady),
                    |func| {
                        func(&e);
                        Err(e)
                    },
                )
            }
        }
    }
}

/// Inspect the Result returned by a future
///
/// This is created by the `FutureExt::inspect_result` method.
#[derive(Debug)]
#[must_use = "futures do nothing unless polled"]
pub struct InspectResult<A, F>
where
    A: Future,
{
    future: A,
    f: Option<F>,
}

impl<A, F> Future for InspectResult<A, F>
where
    A: Future,
    F: FnOnce(Result<&A::Item, &A::Error>),
{
    type Item = A::Item;
    type Error = A::Error;

    fn poll(&mut self) -> Poll<A::Item, A::Error> {
        match self.future.poll() {
            Ok(Async::NotReady) => Ok(Async::NotReady),
            Ok(Async::Ready(i)) => self.f.take().map_or_else(
                // Act like a fused future
                || Ok(Async::NotReady),
                |func| {
                    func(Ok(&i));
                    Ok(Async::Ready(i))
                },
            ),

            Err(e) => self.f.take().map_or_else(
                // Act like a fused future
                || Ok(Async::NotReady),
                |func| {
                    func(Err(&e));
                    Err(e)
                },
            ),
        }
    }
}

/// A trait implemented by default for all Futures which extends the standard
/// functionality.
pub trait FutureExt: Future + Sized {
    /// Map a `Future` to have `Item=()` and `Error=()`. This is
    /// useful when a future is being used to drive a computation
    /// but the actual results aren't interesting (such as when used
    /// with `Handle::spawn()`).
    fn discard(self) -> Discard<Self> {
        Discard(self)
    }

    /// Create a `Send`able boxed version of this `Future`.
    #[inline]
    fn boxify(self) -> BoxFuture<Self::Item, Self::Error>
    where
        Self: 'static + Send,
    {
        // TODO: (rain1) T21801845 rename to 'boxed' once gone from upstream.
        Box::new(self)
    }

    /// Create a non-`Send`able boxed version of this `Future`.
    #[inline]
    fn boxify_nonsend(self) -> BoxFutureNonSend<Self::Item, Self::Error>
    where
        Self: 'static,
    {
        Box::new(self)
    }

    /// Shorthand for returning [`future::Either::A`]
    fn left_future<B>(self) -> future::Either<Self, B> {
        future::Either::A(self)
    }

    /// Shorthand for returning [`future::Either::B`]
    fn right_future<A>(self) -> future::Either<A, Self> {
        future::Either::B(self)
    }

    /// Similar to [`future::Future::inspect`], but runs the function on error
    fn inspect_err<F>(self, f: F) -> InspectErr<Self, F>
    where
        F: FnOnce(&Self::Error) -> (),
        Self: Sized,
    {
        InspectErr {
            future: self,
            f: Some(f),
        }
    }

    /// Similar to [`future::Future::inspect`], but runs the function on both
    /// output or error of the Future treating it as a regular [`Result`]
    fn inspect_result<F>(self, f: F) -> InspectResult<Self, F>
    where
        F: FnOnce(Result<&Self::Item, &Self::Error>) -> (),
        Self: Sized,
    {
        InspectResult {
            future: self,
            f: Some(f),
        }
    }
}

impl<T> FutureExt for T where T: Future {}

/// Params for [StreamExt::buffered_weight_limited] and [WeightLimitedBufferedStream]
pub struct BufferedParams {
    /// Limit for the sum of weights in the [WeightLimitedBufferedStream] stream
    pub weight_limit: u64,
    /// Limit for size of buffer in the [WeightLimitedBufferedStream] stream
    pub buffer_size: usize,
}

/// A trait implemented by default for all Streams which extends the standard
/// functionality.
pub trait StreamExt: Stream {
    /// Fork elements in a stream out to two sinks, depending on a predicate
    ///
    /// If the predicate returns false, send the item to `out1`, otherwise to
    /// `out2`. `streamfork()` acts in a similar manner to `forward()` in that it
    /// keeps operating until the input stream ends, and then returns everything
    /// in the resulting Future.
    ///
    /// The predicate returns a `Result` so that it can fail (if there's a malformed
    /// input that can't be assigned to either output).
    fn streamfork<Out1, Out2, F, E>(
        self,
        out1: Out1,
        out2: Out2,
        pred: F,
    ) -> streamfork::Forker<Self, Out1, Out2, F, E>
    where
        Self: Sized,
        Out1: Sink<SinkItem = Self::Item>,
        Out2: Sink<SinkItem = Self::Item, SinkError = Out1::SinkError>,
        F: FnMut(&Self::Item) -> Result<bool, E>,
        E: From<Self::Error> + From<Out1::SinkError> + From<Out2::SinkError>,
    {
        streamfork::streamfork(self, out1, out2, pred)
    }

    /// Returns a future that yields a `(Vec<<Self>::Item>, Self)`, where the
    /// vector is a collections of all elements yielded by the Stream.
    fn collect_no_consume(self) -> CollectNoConsume<Self>
    where
        Self: Sized,
    {
        stream_wrappers::collect_no_consume::new(self)
    }

    /// A shorthand for [encode::encode]
    fn encode<Enc>(self, encoder: Enc) -> encode::LayeredEncoder<Self, Enc>
    where
        Self: Sized,
        Enc: Encoder<Item = Self::Item>,
    {
        encode::encode(self, encoder)
    }

    /// Similar to [std::iter::Iterator::enumerate], returns a Stream that yields
    /// `(usize, Self::Item)` where the first element of tuple is the iteration
    /// count.
    fn enumerate(self) -> Enumerate<Self>
    where
        Self: Sized,
    {
        Enumerate::new(self)
    }

    /// Creates a stream wrapper and a future. The future will resolve into the wrapped stream when
    /// the stream wrapper returns None. It uses ConservativeReceiver to ensure that deadlocks are
    /// easily caught when one tries to poll on the receiver before consuming the stream.
    fn return_remainder(self) -> (ReturnRemainder<Self>, ConservativeReceiver<Self>)
    where
        Self: Sized,
    {
        ReturnRemainder::new(self)
    }

    /// Whether this stream is empty.
    ///
    /// This will consume one element from the stream if returned.
    fn is_empty<'a>(self) -> Box<dyn Future<Item = bool, Error = Self::Error> + Send + 'a>
    where
        Self: 'a + Send + Sized,
    {
        Box::new(
            self.into_future()
                .map(|(first, _rest)| first.is_none())
                .map_err(|(err, _rest)| err),
        )
    }

    /// Whether this stream is not empty (has at least one element).
    ///
    /// This will consume one element from the stream if returned.
    fn not_empty<'a>(self) -> Box<dyn Future<Item = bool, Error = Self::Error> + Send + 'a>
    where
        Self: 'a + Send + Sized,
    {
        Box::new(
            self.into_future()
                .map(|(first, _rest)| first.is_some())
                .map_err(|(err, _rest)| err),
        )
    }

    /// Create a `Send`able boxed version of this `Stream`.
    #[inline]
    fn boxify(self) -> BoxStream<Self::Item, Self::Error>
    where
        Self: 'static + Send + Sized,
    {
        // TODO: (rain1) T21801845 rename to 'boxed' once gone from upstream.
        Box::new(self)
    }

    /// Create a non-`Send`able boxed version of this `Stream`.
    #[inline]
    fn boxify_nonsend(self) -> BoxStreamNonSend<Self::Item, Self::Error>
    where
        Self: 'static + Sized,
    {
        Box::new(self)
    }

    /// Shorthand for returning [`StreamEither::A`]
    fn left_stream<B>(self) -> StreamEither<Self, B>
    where
        Self: Sized,
    {
        StreamEither::A(self)
    }

    /// Shorthand for returning [`StreamEither::B`]
    fn right_stream<A>(self) -> StreamEither<A, Self>
    where
        Self: Sized,
    {
        StreamEither::B(self)
    }

    /// It's different from [tokio::timer::Timeout] in that it sets a timeout on the whole Stream,
    /// not just on a single Stream item
    fn whole_stream_timeout(self, duration: Duration) -> StreamWithTimeout<Self>
    where
        Self: Sized,
    {
        StreamWithTimeout {
            stream: self,
            delay: Delay::new(Instant::now() + duration),
        }
    }

    /// Similar to [Stream::chunks], but returns earlier if [futures::Async::NotReady]
    /// was returned.
    fn batch(self, limit: usize) -> BatchStream<Self>
    where
        Self: Sized,
    {
        BatchStream::new(self, limit)
    }

    /// Like [Stream::buffered] call, but can also limit number of futures in a buffer by "weight".
    fn buffered_weight_limited<I, E, Fut>(
        self,
        params: BufferedParams,
    ) -> WeightLimitedBufferedStream<Self, I, E>
    where
        Self: Sized + Send + 'static,
        Self: Stream<Item = (Fut, u64), Error = E>,
        Fut: Future<Item = I, Error = E>,
    {
        WeightLimitedBufferedStream::new(params, self)
    }

    /// Returns a Future that yields a collection `C` containing all `Self::Item`
    /// yielded by the stream
    fn collect_to<C: Default + Extend<Self::Item>>(self) -> CollectTo<Self, C>
    where
        Self: Sized,
    {
        CollectTo::new(self)
    }
}

impl<T> StreamExt for T where T: Stream {}

/// Like [stream::Buffered], but can also limit number of futures in a buffer by "weight".
pub struct WeightLimitedBufferedStream<S, I, E> {
    queue: stream::FuturesOrdered<BoxFuture<(I, u64), E>>,
    current_weight: u64,
    weight_limit: u64,
    max_buffer_size: usize,
    stream: stream::Fuse<S>,
}

impl<S, I, E> WeightLimitedBufferedStream<S, I, E>
where
    S: Stream,
{
    /// Create a new instance that will be configured using the `params` provided
    pub fn new(params: BufferedParams, stream: S) -> Self {
        Self {
            queue: stream::FuturesOrdered::new(),
            current_weight: 0,
            weight_limit: params.weight_limit,
            max_buffer_size: params.buffer_size,
            stream: stream.fuse(),
        }
    }
}

impl<S, Fut, I: 'static, E: 'static> Stream for WeightLimitedBufferedStream<S, I, E>
where
    S: Stream<Item = (Fut, u64), Error = E>,
    Fut: Future<Item = I, Error = E> + Send + 'static,
{
    type Item = I;
    type Error = E;

    fn poll(&mut self) -> Poll<Option<Self::Item>, E> {
        // First up, try to spawn off as many futures as possible by filling up
        // our slab of futures.
        while self.queue.len() < self.max_buffer_size && self.current_weight < self.weight_limit {
            let future = match self.stream.poll()? {
                Async::Ready(Some((s, weight))) => {
                    self.current_weight += weight;
                    s.map(move |val| (val, weight)).boxify()
                }
                Async::Ready(None) | Async::NotReady => break,
            };

            self.queue.push(future);
        }

        // Try polling a new future
        if let Some((val, weight)) = try_ready!(self.queue.poll()) {
            self.current_weight -= weight;
            return Ok(Async::Ready(Some(val)));
        }

        // If we've gotten this far, then there are no events for us to process
        // and nothing was ready, so figure out if we're not done yet  or if
        // we've reached the end.
        if self.stream.is_done() {
            Ok(Async::Ready(None))
        } else {
            Ok(Async::NotReady)
        }
    }
}

/// Trait that provides a function for making a decoding layer on top of Stream of Bytes
pub trait StreamLayeredExt: Stream<Item = Bytes> {
    /// Returnes a Stream that will yield decoded chunks of Bytes as they come
    /// using provided [Decoder]
    fn decode<Dec>(self, decoder: Dec) -> decode::LayeredDecode<Self, Dec>
    where
        Self: Sized,
        Dec: Decoder;
}

impl<T> StreamLayeredExt for T
where
    T: Stream<Item = Bytes>,
{
    fn decode<Dec>(self, decoder: Dec) -> decode::LayeredDecode<Self, Dec>
    where
        Self: Sized,
        Dec: Decoder,
    {
        decode::decode(self, decoder)
    }
}

/// Like [std::iter::Enumerate], but for Stream
pub struct Enumerate<In> {
    inner: In,
    count: usize,
}

impl<In> Enumerate<In> {
    fn new(inner: In) -> Self {
        Enumerate { inner, count: 0 }
    }
}

impl<In: Stream> Stream for Enumerate<In> {
    type Item = (usize, In::Item);
    type Error = In::Error;

    fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
        match self.inner.poll() {
            Err(err) => Err(err),
            Ok(Async::NotReady) => Ok(Async::NotReady),
            Ok(Async::Ready(None)) => Ok(Async::Ready(None)),
            Ok(Async::Ready(Some(v))) => {
                let c = self.count;
                self.count += 1;
                Ok(Async::Ready(Some((c, v))))
            }
        }
    }
}

/// Like [future::Either], but for Stream
pub enum StreamEither<A, B> {
    /// First branch of the type
    A(A),
    /// Second branch of the type
    B(B),
}

impl<A, B> Stream for StreamEither<A, B>
where
    A: Stream,
    B: Stream<Item = A::Item, Error = A::Error>,
{
    type Item = A::Item;
    type Error = A::Error;

    fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
        match self {
            StreamEither::A(a) => a.poll(),
            StreamEither::B(b) => b.poll(),
        }
    }
}

/// This is a wrapper around oneshot::Receiver that will return error when the receiver was polled
/// and the result was not ready. This is a very strict way of preventing deadlocks in code when
/// receiver is polled before the sender has send the result
pub struct ConservativeReceiver<T>(oneshot::Receiver<T>);

/// Error that can be returned by [ConservativeReceiver]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ConservativeReceiverError {
    /// The underlying [oneshot::Receiver] returned [oneshot::Canceled]
    Canceled,
    /// The underlying [oneshot::Receiver] returned [Async::NotReady], which means it was polled
    /// before the [oneshot::Sender] send some data
    ReceiveBeforeSend,
}

impl ::std::error::Error for ConservativeReceiverError {
    fn description(&self) -> &str {
        match self {
            ConservativeReceiverError::Canceled => "oneshot canceled",
            ConservativeReceiverError::ReceiveBeforeSend => "recv called on channel before send",
        }
    }
}

impl ::std::fmt::Display for ConservativeReceiverError {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        match self {
            ConservativeReceiverError::Canceled => write!(fmt, "oneshot canceled"),
            ConservativeReceiverError::ReceiveBeforeSend => {
                write!(fmt, "recv called on channel before send")
            }
        }
    }
}

impl ::std::convert::From<oneshot::Canceled> for ConservativeReceiverError {
    fn from(_: oneshot::Canceled) -> ConservativeReceiverError {
        ConservativeReceiverError::Canceled
    }
}

impl<T> ConservativeReceiver<T> {
    /// Return an instance of [ConservativeReceiver] wrapping the [oneshot::Receiver]
    pub fn new(recv: oneshot::Receiver<T>) -> Self {
        ConservativeReceiver(recv)
    }
}

impl<T> Future for ConservativeReceiver<T> {
    type Item = T;
    type Error = ConservativeReceiverError;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        match self.0.poll()? {
            Async::Ready(item) => Ok(Async::Ready(item)),
            Async::NotReady => Err(ConservativeReceiverError::ReceiveBeforeSend),
        }
    }
}

/// A stream wrapper returned by [StreamExt::return_remainder]
pub struct ReturnRemainder<In> {
    inner: Option<In>,
    send: Option<oneshot::Sender<In>>,
}

impl<In> ReturnRemainder<In> {
    fn new(inner: In) -> (Self, ConservativeReceiver<In>) {
        let (send, recv) = oneshot::channel();
        (
            Self {
                inner: Some(inner),
                send: Some(send),
            },
            ConservativeReceiver::new(recv),
        )
    }
}

impl<In: Stream> Stream for ReturnRemainder<In> {
    type Item = In::Item;
    type Error = In::Error;

    fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
        let maybe_item = match self.inner {
            Some(ref mut inner) => try_ready!(inner.poll()),
            None => return Ok(Async::Ready(None)),
        };

        if maybe_item.is_none() {
            let inner = self
                .inner
                .take()
                .expect("inner was just polled, should be some");
            let send = self.send.take().expect("send is None iff inner is None");
            // The Receiver will handle errors
            let _ = send.send(inner);
        }

        Ok(Async::Ready(maybe_item))
    }
}

/// Error returned by [StreamWithTimeout]
pub enum StreamTimeoutError {
    /// The original error returned
    Error(anyhow::Error),
    /// Error returned when timeout was reached
    Timeout,
}

/// A stream wrapper returned by [StreamExt::whole_stream_timeout]
pub struct StreamWithTimeout<S> {
    delay: Delay,
    stream: S,
}

impl<S: Stream<Error = anyhow::Error>> Stream for StreamWithTimeout<S> {
    type Item = S::Item;
    type Error = StreamTimeoutError;

    fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
        match self.delay.poll() {
            Ok(Async::Ready(())) => {
                return Err(StreamTimeoutError::Timeout);
            }
            Err(err) => {
                return Err(StreamTimeoutError::Error(format_err!(
                    "internal error: timeout failed {}",
                    err
                )));
            }
            _ => {}
        };

        match self.stream.poll() {
            Ok(Async::Ready(item)) => Ok(Async::Ready(item)),
            Ok(Async::NotReady) => Ok(Async::NotReady),
            Err(err) => Err(StreamTimeoutError::Error(err)),
        }
    }
}

/// A convenience macro for working with `io::Result<T>` from the `Read` and
/// `Write` traits.
///
/// This macro takes `io::Result<T>` as input, and returns `Poll<T, io::Error>`
/// as the output. If the input type is of the `Err` variant, then
/// `Poll::NotReady` is returned if it indicates `WouldBlock` or otherwise `Err`
/// is returned.
#[macro_export]
#[rustfmt::skip]
macro_rules! handle_nb {
    ($e:expr) => {
        match $e {
            Ok(t) => Ok(::futures::Async::Ready(t)),
            Err(ref e) if e.kind() == ::std::io::ErrorKind::WouldBlock => {
                Ok(::futures::Async::NotReady)
            }
            Err(e) => Err(e),
        }
    };
}

/// Macro that can be used like `?` operator, but in the context where the expected return type is
/// BoxFuture. The result of it is either Ok part of Result or immediate returning the Err part
/// converted into BoxFuture.
#[macro_export]
#[rustfmt::skip]
macro_rules! try_boxfuture {
    ($e:expr) => {
        match $e {
            Ok(t) => t,
            Err(e) => return $crate::FutureExt::boxify($crate::futures_reexport::future::err(e.into())),
        }
    };
}

/// Macro that can be used like `?` operator, but in the context where the expected return type is
/// BoxStream. The result of it is either Ok part of Result or immediate returning the Err part
/// converted into BoxStream.
#[macro_export]
#[rustfmt::skip]
macro_rules! try_boxstream {
    ($e:expr) => {
        match $e {
            Ok(t) => t,
            Err(e) => return $crate::StreamExt::boxify($crate::futures_reexport::stream::once(Err(e.into()))),
        }
    };
}

/// Macro that can be used like ensure! macro from failure crate, but in the context where the
/// expected return type is BoxFuture. Exits a function early with an Error if the condition is not
/// satisfied.
#[macro_export]
#[rustfmt::skip]
macro_rules! ensure_boxfuture {
    ($cond:expr, $e:expr) => {
        if !($cond) {
            return $crate::FutureExt::boxify(::futures::future::err($e.into()));
        }
    };
}

/// Macro that can be used like ensure! macro from failure crate, but in the context where the
/// expected return type is BoxStream. Exits a function early with an Error if the condition is not
/// satisfied.
#[macro_export]
#[rustfmt::skip]
macro_rules! ensure_boxstream {
    ($cond:expr, $e:expr) => {
        if !($cond) {
            return $crate::StreamExt::boxify(::futures::stream::once(Err($e.into())));
        }
    };
}

/// Macro that can be used like `?` operator, but in the context where the expected return type is
///  a left future. The result of it is either Ok part of Result or immediate returning the Err
//part / converted into a  a left future.
#[macro_export]
#[rustfmt::skip]
macro_rules! try_left_future {
    ($e:expr) => {
        match $e {
            Ok(t) => t,
            Err(e) => return $crate::futures_reexport::future::err(e.into()).left_future(),
        }
    };
}

/// Take a future, and run it on its own task, returning the result to the caller. This permits
/// Rust to run the spawned future on a different thread to the task that spawned it, thus adding
/// parallelism if used sensibly.
/// Note that the spawning here is lazy - the new task will not be spawned if the returned future
/// is dropped before it's polled.
pub fn spawn_future<T, E, Fut, IntoFut>(f: IntoFut) -> impl Future<Item = T, Error = E>
where
    IntoFut: IntoFuture<Item = T, Error = E, Future = Fut>,
    Fut: Future<Item = T, Error = E> + Send + 'static,
    T: Send + 'static,
    E: From<futures::Canceled> + Send + 'static,
{
    let (tx, rx) = oneshot::channel();

    let fut = f.into_future().then(|res| {
        let _ = tx.send(res);
        Ok(())
    });

    future::lazy(move || {
        let _ = tokio::spawn(fut);
        rx.from_err().and_then(|v| v)
    })
}

/// Given an `FnMut` closure, create a `Future` that will eventually execute the closure using
/// Tokio's `blocking` mechanism, so that it is safe to call blocking code inside the closure
/// without preventing other tasks from making progress.
/// This returns a lazy future - it will not even attempt to run the blocking code until you poll
/// the future.
/// Note that this does not spawn the future onto its own task - use `asynchronize` below if you
/// need to run the blocking code on its own thread, rather than letting it block this task.
pub fn closure_to_blocking_future<T, E, Func>(f: Func) -> impl Future<Item = T, Error = E>
where
    Func: FnMut() -> Result<T, E>,
    E: From<tokio_threadpool::BlockingError>,
{
    let mut func = f;
    future::lazy(|| future::poll_fn(move || blocking(&mut func)))
        .map_err(E::from)
        .and_then(|res| res) // flatten Ok(res) => res
}

///  This method allows us to take synchronous code, schedule it on the default tokio thread pool
/// and convert it to the future. It's the combination of `spawn_future` (which runs a future on
/// another thread) and `closure_to_blocking_future` (which turns a closure into a future).
pub fn asynchronize<Func, T, E>(f: Func) -> impl Future<Item = T, Error = E>
where
    Func: FnMut() -> Result<T, E> + Send + 'static,
    T: Send + 'static,
    E: From<tokio_threadpool::BlockingError> + From<futures::Canceled> + Send + 'static,
{
    let fut = closure_to_blocking_future(f);

    spawn_future(fut)
}

/// Simple adapter from `Sink` interface to `AsyncWrite` interface.
/// It can be useful to convert from the interface that supports only AsyncWrite, and get
/// Stream as a result. See pseudocode below
///
///  ```
/// # use anyhow::Error;
/// # use futures::Future;
/// # use futures_ext::{BoxFuture, SinkToAsyncWrite};
/// # use tokio::io::AsyncWrite;
/// # use tokio;
/// fn async_write_interface(writer: &mut dyn AsyncWrite) -> BoxFuture<(), Error> {
///     unimplemented!()
/// }
///
/// fn foo() {
///     use futures::sync::mpsc;
///     let (sender, receiver) = mpsc::channel(1);
///
///     tokio::spawn(
///        async_write_interface(&mut SinkToAsyncWrite::new(sender))
///            .map_err(|err| {})
///     );
///
///     // receiver is a stream of values written from async_write_interface
/// }
/// # fn main() {}
///  ```
pub struct SinkToAsyncWrite<S> {
    sink: S,
}

impl<S> SinkToAsyncWrite<S> {
    /// Return an instance of [SinkToAsyncWrite] wrapping a Sink
    pub fn new(sink: S) -> Self {
        SinkToAsyncWrite { sink }
    }
}

fn create_std_error<E: Debug>(err: E) -> std_io::Error {
    std_io::Error::new(std_io::ErrorKind::Other, format!("{:?}", err))
}

impl<E, S> std_io::Write for SinkToAsyncWrite<S>
where
    S: Sink<SinkItem = Bytes, SinkError = E>,
    E: Debug,
{
    fn write(&mut self, buf: &[u8]) -> ::std::io::Result<usize> {
        let bytes = Bytes::from(buf);
        match self.sink.start_send(bytes) {
            Ok(AsyncSink::Ready) => Ok(buf.len()),
            Ok(AsyncSink::NotReady(_)) => Err(std_io::Error::new(
                std_io::ErrorKind::WouldBlock,
                "channel is busy",
            )),
            Err(err) => Err(create_std_error(err)),
        }
    }

    fn flush(&mut self) -> std_io::Result<()> {
        match self.sink.poll_complete() {
            Ok(Async::Ready(())) => Ok(()),
            Ok(Async::NotReady) => Err(std_io::Error::new(
                std_io::ErrorKind::WouldBlock,
                "channel is busy",
            )),
            Err(err) => Err(create_std_error(err)),
        }
    }
}

impl<E, S> AsyncWrite for SinkToAsyncWrite<S>
where
    S: Sink<SinkItem = Bytes, SinkError = E>,
    E: Debug,
{
    fn shutdown(&mut self) -> Poll<(), std_io::Error> {
        match self.sink.close() {
            Ok(res) => Ok(res),
            Err(err) => Err(create_std_error(err)),
        }
    }
}

/// It's a combinator that converts `Stream<A>` into `Stream<Vec<A>>`.
/// So interface is similar to `.chunks()` method, but there's an important difference:
/// BatchStream won't wait until the whole batch fills up i.e. as soon as underlying stream
/// return NotReady, then new batch is returned from BatchStream
pub struct BatchStream<S>
where
    S: Stream,
{
    inner: stream::Fuse<S>,
    err: Option<S::Error>,
    limit: usize,
}

impl<S: Stream> BatchStream<S> {
    /// Return an instance of [BatchStream] wrapping a Stream with the provided limit set
    pub fn new(s: S, limit: usize) -> Self {
        Self {
            inner: s.fuse(),
            err: None,
            limit,
        }
    }
}

impl<S: Stream> Stream for BatchStream<S> {
    type Item = Vec<S::Item>;
    type Error = S::Error;

    fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
        let mut batch = vec![];

        if let Some(err) = self.err.take() {
            return Err(err);
        }

        while batch.len() < self.limit {
            match self.inner.poll() {
                Ok(Async::Ready(Some(v))) => batch.push(v),
                Ok(Async::NotReady) | Ok(Async::Ready(None)) => break,
                Err(err) => {
                    self.err = Some(err);
                    break;
                }
            }
        }

        if batch.is_empty() {
            if let Some(err) = self.err.take() {
                return Err(err);
            }

            if self.inner.is_done() {
                Ok(Async::Ready(None))
            } else {
                Ok(Async::NotReady)
            }
        } else {
            Ok(Async::Ready(Some(batch)))
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    use std::time::{self, Duration};

    use anyhow::{Error, Result};
    use assert_matches::assert_matches;
    use futures::stream;
    use futures::sync::mpsc;
    use futures::Stream;

    use cloned::cloned;
    use futures::future::{err, ok};
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;
    use tokio::runtime::Runtime;

    #[derive(Debug)]
    struct MyErr;

    impl<T> From<mpsc::SendError<T>> for MyErr {
        fn from(_: mpsc::SendError<T>) -> Self {
            MyErr
        }
    }

    #[test]
    #[ignore]
    // In some cases it fails with a longer duration than specified
    fn asynchronize_parallel() {
        const SLEEP_TIME: Duration = time::Duration::from_millis(20);
        // Thread count must be bigger than 10 to prove parallelism
        const THREAD_COUNT: usize = 20;

        let mut runtime = tokio::runtime::Builder::new()
            .name_prefix("my-runtime-worker-")
            .core_threads(THREAD_COUNT)
            .build()
            .unwrap();
        fn sleep() -> Result<()> {
            std::thread::sleep(SLEEP_TIME);
            Ok(())
        }

        let futures: Vec<_> = std::iter::repeat_with(|| asynchronize(sleep))
            // This count needs to be much greater than 2, so that if we serialize operations, we see
            // an issue
            .take(THREAD_COUNT)
            .collect();
        let start = time::Instant::now();
        let _ = runtime.block_on(future::join_all(futures));
        let run_time = start.elapsed();
        assert!(
            run_time < SLEEP_TIME * 2,
            "Parallel sleep time {:#?} much greater than {:#?} for {:#?} threads - each thread sleeps for {:#?}",
            run_time,
            SLEEP_TIME * 2,
            THREAD_COUNT,
            SLEEP_TIME
        );
    }

    #[test]
    fn discard() {
        use futures::sync::mpsc;

        let mut runtime = Runtime::new().unwrap();

        let (tx, rx) = mpsc::channel(1);

        let xfer = stream::iter_ok::<_, MyErr>(vec![123]).forward(tx);

        runtime.spawn(xfer.discard());

        match runtime.block_on(rx.collect()) {
            Ok(v) => assert_eq!(v, vec![123]),
            bad => panic!("bad {:?}", bad),
        }
    }

    #[test]
    fn inspect_err() {
        let count = Arc::new(AtomicUsize::new(0));
        cloned!(count as count_cloned);
        let mut runtime = Runtime::new().unwrap();
        let work = err::<i32, i32>(42).inspect_err(move |e| {
            assert_eq!(42, *e);
            count_cloned.fetch_add(1, Ordering::SeqCst);
        });
        if runtime.block_on(work).is_ok() {
            panic!("future is supposed to fail");
        }
        assert_eq!(1, count.load(Ordering::SeqCst));
    }

    #[test]
    fn inspect_ok() {
        let count = Arc::new(AtomicUsize::new(0));
        cloned!(count as count_cloned);
        let mut runtime = Runtime::new().unwrap();
        let work = ok::<i32, i32>(42).inspect_err(move |_| {
            count_cloned.fetch_add(1, Ordering::SeqCst);
        });
        if runtime.block_on(work).is_err() {
            panic!("future is supposed to succeed");
        }
        assert_eq!(0, count.load(Ordering::SeqCst));
    }

    #[test]
    fn inspect_result() {
        let count = Arc::new(AtomicUsize::new(0));
        cloned!(count as count_cloned);
        let mut runtime = Runtime::new().unwrap();
        let work = err::<i32, i32>(42).inspect_result(move |res| {
            if let Err(e) = res {
                assert_eq!(42, *e);
                count_cloned.fetch_add(1, Ordering::SeqCst);
            } else {
                count_cloned.fetch_add(2, Ordering::SeqCst);
            }
        });
        if runtime.block_on(work).is_ok() {
            panic!("future is supposed to fail");
        }
        assert_eq!(1, count.load(Ordering::SeqCst));
    }

    #[test]
    fn enumerate() {
        let s = stream::iter_ok::<_, ()>(vec!["hello", "there", "world"]);
        let es = Enumerate::new(s);
        let v = es.collect().wait();

        assert_eq!(v, Ok(vec![(0, "hello"), (1, "there"), (2, "world")]));
    }

    #[test]
    fn empty() {
        let mut s = stream::empty::<(), ()>();
        // Ensure that the stream doesn't have to be consumed.
        assert!(s.by_ref().is_empty().wait().unwrap());
        assert!(!s.not_empty().wait().unwrap());

        let mut s = stream::once::<_, ()>(Ok("foo"));
        assert!(!s.by_ref().is_empty().wait().unwrap());
        // The above is_empty would consume the first element, so the stream has to be
        // reinitialized.
        let s = stream::once::<_, ()>(Ok("foo"));
        assert!(s.not_empty().wait().unwrap());
    }

    #[test]
    fn return_remainder() {
        use futures::future::poll_fn;

        let s = stream::iter_ok::<_, ()>(vec!["hello", "there", "world"]).fuse();
        let (mut s, mut remainder) = s.return_remainder();

        let mut runtime = Runtime::new().unwrap();
        let res: Result<(), ()> = runtime.block_on(poll_fn(move || {
            assert_matches!(
                remainder.poll(),
                Err(ConservativeReceiverError::ReceiveBeforeSend)
            );

            assert_eq!(s.poll(), Ok(Async::Ready(Some("hello"))));
            assert_matches!(
                remainder.poll(),
                Err(ConservativeReceiverError::ReceiveBeforeSend)
            );

            assert_eq!(s.poll(), Ok(Async::Ready(Some("there"))));
            assert_matches!(
                remainder.poll(),
                Err(ConservativeReceiverError::ReceiveBeforeSend)
            );

            assert_eq!(s.poll(), Ok(Async::Ready(Some("world"))));
            assert_matches!(
                remainder.poll(),
                Err(ConservativeReceiverError::ReceiveBeforeSend)
            );

            assert_eq!(s.poll(), Ok(Async::Ready(None)));
            match remainder.poll() {
                Ok(Async::Ready(s)) => assert!(s.is_done()),
                bad => panic!("unexpected result: {:?}", bad),
            }

            Ok(Async::Ready(()))
        }));

        assert_matches!(res, Ok(()));
    }

    fn assert_flush<E, S>(sink: &mut SinkToAsyncWrite<S>)
    where
        S: Sink<SinkItem = Bytes, SinkError = E>,
        E: Debug,
    {
        use std::io::Write;
        loop {
            let flush_res = sink.flush();
            if flush_res.is_ok() {
                break;
            }
            if let Err(ref e) = flush_res {
                assert_eq!(e.kind(), std_io::ErrorKind::WouldBlock);
            }
        }
    }

    fn assert_shutdown<E, S>(sink: &mut SinkToAsyncWrite<S>)
    where
        S: Sink<SinkItem = Bytes, SinkError = E>,
        E: Debug,
    {
        loop {
            let shutdown_res = sink.shutdown();
            if shutdown_res.is_ok() {
                break;
            }
            if let Err(ref e) = shutdown_res {
                assert_eq!(e.kind(), std_io::ErrorKind::WouldBlock);
            }
        }
    }

    #[test]
    fn sink_to_async_write() {
        use futures::sync::mpsc;
        use std::io::Write;
        let mut rt = tokio::runtime::Runtime::new().unwrap();

        let (tx, rx) = mpsc::channel::<Bytes>(1);

        let messages_num = 10;

        rt.spawn(Ok(()).into_future().map(move |()| {
            let mut async_write = SinkToAsyncWrite::new(tx);
            for i in 0..messages_num {
                loop {
                    let res = async_write.write(format!("{}", i).as_bytes());
                    if let Err(ref e) = res {
                        assert_eq!(e.kind(), std_io::ErrorKind::WouldBlock);
                        assert_flush(&mut async_write);
                    } else {
                        break;
                    }
                }
            }

            assert_flush(&mut async_write);
            assert_shutdown(&mut async_write);
        }));

        let res = rt.block_on(rx.collect()).unwrap();
        assert_eq!(res.len(), messages_num);
    }

    #[test]
    fn whole_stream_timeout_test() {
        use futures::Stream;
        use tokio::timer::Interval;

        let count = Arc::new(AtomicUsize::new(0));
        let mut runtime = Runtime::new().unwrap();
        let f = Interval::new(Instant::now(), Duration::new(1, 0))
            .map({
                let count = count.clone();
                move |item| {
                    count.fetch_add(1, Ordering::Relaxed);
                    item
                }
            })
            .map_err(|_| Error::msg("error"))
            .take(10)
            .whole_stream_timeout(Duration::new(3, 0))
            .collect();

        let res = runtime.block_on(f);
        assert!(res.is_err());
        match res {
            Err(StreamTimeoutError::Timeout) => {}
            _ => {
                panic!("expected timeout");
            }
        };

        assert!(count.load(Ordering::Relaxed) < 5);
    }

    #[test]
    fn test_buffered() {
        type TestStream = BoxStream<(BoxFuture<(), ()>, u64), ()>;

        fn create_stream() -> (Arc<AtomicUsize>, TestStream) {
            let s: TestStream = stream::iter_ok(vec![
                (future::ok(()).boxify(), 100),
                (future::ok(()).boxify(), 2),
            ])
            .boxify();

            let counter = Arc::new(AtomicUsize::new(0));

            (
                counter.clone(),
                s.inspect({
                    move |_val| {
                        counter.fetch_add(1, Ordering::SeqCst);
                    }
                })
                .boxify(),
            )
        }

        let mut runtime = tokio::runtime::Builder::new().build().unwrap();

        let (counter, s) = create_stream();
        let params = BufferedParams {
            weight_limit: 10,
            buffer_size: 10,
        };
        let s = s.buffered_weight_limited(params);
        if let Ok((Some(()), s)) = runtime.block_on(s.into_future()) {
            assert_eq!(counter.load(Ordering::SeqCst), 1);
            assert_eq!(runtime.block_on(s.collect()).unwrap().len(), 1);
            assert_eq!(counter.load(Ordering::SeqCst), 2);
        } else {
            panic!("failed to block on a stream");
        }

        let (counter, s) = create_stream();
        let params = BufferedParams {
            weight_limit: 200,
            buffer_size: 10,
        };
        let s = s.buffered_weight_limited(params);
        if let Ok((Some(()), s)) = runtime.block_on(s.into_future()) {
            assert_eq!(counter.load(Ordering::SeqCst), 2);
            assert_eq!(runtime.block_on(s.collect()).unwrap().len(), 1);
            assert_eq!(counter.load(Ordering::SeqCst), 2);
        } else {
            panic!("failed to block on a stream");
        }
    }

    use std::collections::HashSet;
    use std::iter::Iterator;

    fn assert_same_elements<I, T>(src: Vec<I>, iter: T)
    where
        I: Copy + Debug + Ord,
        T: IntoIterator<Item = I>,
    {
        let mut dst_sorted: Vec<I> = iter.into_iter().collect();
        dst_sorted.sort();

        let mut src_sorted = src;
        src_sorted.sort();

        assert_eq!(src_sorted, dst_sorted);
    }

    #[test]
    fn collect_into_vec() {
        let items = vec![1, 2, 3];
        let future = futures::stream::iter_ok::<_, ()>(items.clone()).collect_to();
        let mut runtime = Runtime::new().unwrap();
        match runtime.block_on::<_, Vec<i32>, _>(future) {
            Ok(collections) => assert_same_elements(items, collections),
            Err(()) => panic!("future is supposed to succeed"),
        }
    }

    #[test]
    fn collect_into_set() {
        let items = vec![1, 2, 3];
        let future = futures::stream::iter_ok::<_, ()>(items.clone()).collect_to();
        let mut runtime = Runtime::new().unwrap();
        match runtime.block_on::<_, HashSet<i32>, _>(future) {
            Ok(collections) => assert_same_elements(items, collections),
            Err(()) => panic!("future is supposed to succeed"),
        }
    }
}