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
//! Alternative implementation of many functions found in [`std::io`],
//! but suitable for blocking IO over networks.
//!
//! The main reason for this crate is the handling of [`ErrorKind`]`::Interrupted` in
//! `std::io`.
//! Except for [`std::io::Read::read`] and [`std::io::Write::write`], almost all functions
//! will ignore interrupts and just retry.
//!
//! This crate provides alternative implementations using a similar API but allow for interrupts
//! whithout losing any content.
//!
//! Most functions are based on buffered readers instead of plain readers to ensure that no
//! content is lost on retry.
//!
//! [`std::io`]: https://doc.rust-lang.org/nightly/std/io/index.html
//! [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
//! [`std::io::Read::read`]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html#tymethod.read
//! [`std::io::Write::write`]:
//!     https://doc.rust-lang.org/nightly/std/io/trait.Write.html#tymethod.write

extern crate memchr;
pub extern crate buf_redux;

use std::io;

mod impls;
mod adapt;
mod iter;
mod utf8;

pub mod mock;

pub use buf_redux as buf_redux_reexport;
use buf_redux_reexport as br;

pub use adapt::{Retry, Take, Repeat};
pub use iter::{Bytes, Split, Collect};
pub use utf8::Utf8Reader;


/// Alternative to `std::io::BufReader`
pub type BufReader<R> = br::BufReader<R, br::DefaultReadStrategy, br::DefaultMoveStrategy>;

/// Copies the entire content of a buffered reader into a writer.
///
/// Similar to [`std::io::copy`], this function will continuously read data from reader and
/// then write it into writer in a streaming fashion until reader returns EOF.
///
/// Errors
/// ======
/// This function will return an error immediately if any call to [`fill_buf`] or
/// [`write`] returns any kind of error.
/// Instances of [`ErrorKind`]`::Interrupted` are *not* handled by this function.
///
/// All bytes consumed from the buffered reader will be written to the specified writer and vice
/// versa.
/// It is guaranteed that no data is lost in case of error.
///
/// Differences to `std::io::copy`
/// ==============================
/// - Does not retry on [`ErrorKind`]`::Interrupted`.
/// - Uses [`BufRead`] instead of [`Read`].
/// - Does not return the number of bytes that are copied.
///
/// Advantages
/// ----------
/// - Allows for reliable retry on errors.
/// - Function is interruptable, e.g. to allow graceful shutdown for server applications.
/// - Avoids double buffering if the source already implements [`BufRead`].
/// - Allows different buffer sizes by using [`BufReader::with_capacity`].
///
/// Disadvantages
/// -------------
/// The fact that it does not return the number of bytes copied stems from the fact that it cannot
/// return this information in case of error.
/// This would go against the goal of allowing reliable retry.
///
/// [`fill_buf`]: ./trait.BufRead.html#tymethod.fill_buf
/// [`write`]: ./trait.Write.html#tymethod.write
/// [`Read`]: ./trait.Read.html
/// [`BufRead`]: ./trait.BufRead.html
/// [`BufReader::with_capacity`]: ./buf_redux_reexport/struct.BufReader.html#method.with_capacity
/// [`std::io::copy`]: https://doc.rust-lang.org/nightly/std/io/fn.copy.html
/// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> io::Result<()>
    where R: BufRead,
          W: Write
{
    loop {
        let written = {
            let buf = try!(reader.fill_buf());
            if buf.len() == 0 {
                return Ok(());
            }
            try!(writer.write(buf))
        };
        if written == 0 {
            return Err(io::Error::new(io::ErrorKind::WriteZero, "no bytes could be written"));
        }
        reader.consume(written);
    }
}

/// Copies the content of a buffered reader into a writer until a delimiter is reached.
///
/// This function will continuously read data from reader and then write it into writer in a
/// streaming fashion until until the delimiter or EOF is found.
///
/// Errors
/// ======
/// This function will return an error immediately if any call to [`fill_buf`] or
/// [`write`] returns any kind of error.
/// Instances of [`ErrorKind`]`::Interrupted` are *not* handled by this function.
///
/// All bytes consumed from the buffered reader will be written to the specified writer and vice
/// versa.
/// It is guaranteed that no data is lost in case of error.
///
/// [`fill_buf`]: ./trait.BufRead.html#tymethod.fill_buf
/// [`write`]: ./trait.Write.html#tymethod.write
/// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
pub fn copy_until<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W, delim: u8) -> io::Result<()>
    where R: BufRead,
          W: Write
{
    loop {
        let (found, used) = {
            let buf = try!(reader.fill_buf());
            if buf.len() == 0 {
                return Err(io::Error::new(io::ErrorKind::UnexpectedEof,
                                          "Stream did not contain the delimiter"));
            }
            match memchr::memchr(delim, buf) {
                Some(i) => {
                    let written = try!(writer.write(&buf[..i + 1]));
                    (written == i + 1, written)
                }
                None => (false, try!(writer.write(buf))),
            }
        };
        if used == 0 {
            return Err(io::Error::new(io::ErrorKind::WriteZero, "no bytes could be written"));
        }
        reader.consume(used);
        if found {
            return Ok(());
        }
    }
}

/// Base trait for generic stream operations
///
/// Most of these function are generalizations of functions already present in [`std::io::Read`]
/// and/or [`std::io::Write`]:
///
/// - `by_ref` ← [`std::io::Read::by_ref`] and [`std::io::Write::by_ref`]
/// - `take` ← [`std::io::Read::take`]
///
/// New methods without counterpart in `std::io`
///
/// - `retry`
///
/// [`std::io::Read`]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html
/// [`std::io::Write`]: https://doc.rust-lang.org/nightly/std/io/trait.Write.html
/// [`std::io::Read::by_ref`]:
///     https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.by_ref
/// [`std::io::Read::take`]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.take
/// [`std::io::Write::by_ref`]:
///     https://doc.rust-lang.org/nightly/std/io/trait.Write.html#method.by_ref
pub trait Stream {
    /// Creates a "by reference" adaptor for this stream.
    ///
    /// This method is equivalent to [`std::io::Read::by_ref`] and [`std::io::Write::by_ref`]
    ///
    /// [`std::io::Read::by_ref`]:
    ///     https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.by_ref
    /// [`std::io::Write::by_ref`]:
    ///     https://doc.rust-lang.org/nightly/std/io/trait.Write.html#method.by_ref
    #[inline]
    fn by_ref(&mut self) -> &mut Self where Self: Sized {
        self
    }

    /// Creates an adapter which will limits the total number of bytes of this stream.
    ///
    /// This function returns a new stream instance of which will read write at most
    /// `limit` bytes, after which it will always return EOF (`Ok(0)`). Any
    /// errors will not count towards the number of bytes read and future
    /// calls to `read` or `write` may succeed.
    ///
    /// Differences to `std::io::Read::take`
    /// ====================================
    /// This function is equivalent to [`std::io::Read::take`] except that the returned
    /// adapter implements [`BufReadGrow`] and [`std::io::Write`] if possible.
    ///
    /// [`BufReadGrow`]: ./trait.BufReadGrow.html
    /// [`std::io::Read::take`]:
    ///     https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.take
    /// [`std::io::Write`]: https://doc.rust-lang.org/nightly/std/io/trait.Write.html
    #[inline]
    fn take(self, limit: u64) -> Take<Self>
        where Self: Sized
    {
        Take::new(self, limit)
    }

    /// Transforms this stream into a stream that automatically retries on interrupts
    ///
    /// The returned adapter will behave identically to the original stream, except that it retries
    /// all operations automatically if an error of kind
    /// [`ErrorKind`]`::Interrupted` occurs.
    ///
    /// Note
    /// ----
    /// Methods that are already expected to retry are forwarded directly to the underlying reader.
    ///
    /// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    #[inline]
    fn retry(self) -> Retry<Self>
        where Self: Sized
    {
        Retry::new(self)
    }
}

impl<R: ?Sized> Stream for R { }

/// Alternative to `std::io::Read`
///
/// This trait is automatically implemented for all types that implement [`std::io::Read`].
///
/// Diffrerences to `std::io::Read`
/// ===============================
/// Methods that are just wrappers around the equivalent methods of `std::io::Read`:
///
/// - `read`
/// - `chain`
///
/// New methods that have no counterpart in `std::io::Read`:
///
/// - `buffer`
/// - `repeat`
///
/// Functions that were removed or moved to a different place,
/// because they cannot be implemented with providing all desired guarantees:
///
/// - `read_to_end` → [`BufRead::read_to_end`]
/// - `read_to_string` → [`Utf8Reader::read_to_string`]
/// - `read_exact` → [`BufRead::read_exact`]
/// - `bytes` → [`BufRead::bytes`]
/// - `chars` → [`Utf8Reader::chars`]
///
/// [`BufRead::read_to_end`]: trait.BufRead.html#method.read_to_end
/// [`BufRead::read_exact`]: trait.BufRead.html#method.read_exact
/// [`BufRead::bytes`]: trait.BufRead.html#method.bytes
/// [`Utf8Reader::read_to_string`]: struct.Utf8Reader.html#method.read_to_string
/// [`Utf8Reader::chars`]: struct.Utf8Reader.html#method.chars
/// [`std::io::Read`]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html
pub trait Read : Stream {
    /// Pull some bytes from this source into the specified buffer, returning
    /// how many bytes were read.
    ///
    /// This methode is equivalent to [`std::io::Read::read`].
    ///
    /// [`std::io::Read::read`]:
    ///     https://doc.rust-lang.org/nightly/std/io/trait.Read.html#tymethod.read
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>;

    /// Creates an adaptor which will chain this stream with another.
    ///
    /// This method is equivalent to [`std::io::Read::chain`].
    ///
    /// [`std::io::Read::chain`]:
    ///     https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.chain
    fn chain<R: io::Read>(self, next: R) -> io::Chain<Self, R> where Self: Sized;

    /// Creates a buffered reader with default capacity and default strategies
    ///
    /// Please see the documentation of [`BufReader`] for more details
    ///
    /// [`BufReader`]: ./buf_redux_reexport/struct.BufReader.html
    #[inline]
    fn buffer(self) -> BufReader<Self>
        where Self: Sized
    {
        BufReader::new(self)
    }

    /// Transforms this reader into a reader that automatically restarts from the beginning after
    /// EOF is reached
    #[inline]
    fn repeat(self) -> Repeat<Self>
        where Self: Sized
    {
        Repeat::new(self)
    }
}

impl<R: ?Sized+io::Read> Read for R {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        io::Read::read(self, buf)
    }

    #[inline]
    fn chain<N: io::Read>(self, next: N) -> io::Chain<Self, N>
        where Self: Sized
    {
        io::Read::chain(self, next)
    }
}

/// Alternative to `std::io::Write`
///
/// This trait is automatically implemented for all types that implement `std::io::Write`.
///
/// Differences to `std::io::Write`
/// ===============================
/// Methods that are just wrappers around the equivalent methods of `std::io::Write`:
///
/// - `write`
/// - `flush`
///
/// Methods that provide a slightly different functionality than their counterparts in
/// `std::io::Write`:
///
/// - `write_all`
///
/// Functions that were removed or moved to a different trait,
/// because they cannot be implemented with providing all desired guarantees:
///
/// - `write_fmt` → removed
pub trait Write : Stream {
    /// Write a buffer into this object, returning how many bytes were written.
    ///
    /// This method is equivalent to [`std::io::Write::write`].
    ///
    /// [`std::io::Write::write`]:
    ///     https://doc.rust-lang.org/nightly/std/io/trait.Write.html#tymethod.write
    fn write(&mut self, buf: &[u8]) -> io::Result<usize>;

    /// Flush this output stream, ensuring that all intermediately buffered
    /// contents reach their destination.
    ///
    /// This method is equivalent to [`std::io::Write::flush`].
    ///
    /// [`std::io::Write::flush`]:
    ///     https://doc.rust-lang.org/nightly/std/io/trait.Write.html#tymethod.flush
    fn flush(&mut self) -> io::Result<()>;

    /// Attempts to write an entire buffer into this write.
    ///
    /// Similarly to [`std::io::Write::write_all`],
    /// this method will continuously call `write` while there is more data to write.
    /// This method will not return until the entire buffer has been
    /// successfully written or an error occurs. The first error generated from
    /// this method will be returned.
    ///
    /// The supplied buffer will be consumed by the writing operation.
    ///
    /// Errors
    /// ======
    /// This function will return an error immediately if any call to [`write`] returns
    /// any kind of error.
    /// Instances of [`ErrorKind`]`::Interrupted` are *not* handled by this function.
    ///
    /// All bytes consumed from the buffer will be written to the the writer and vice versa.
    /// It is guaranteed that no data is lost in case of error.
    ///
    /// Differences to `std::io::Write::write_all`
    /// ==========================================
    /// - Does not retry on [`ErrorKind`]`::Interrupted`.
    /// - Takes a `BufRead` instance instead of just a plain `&[u8]`.
    ///
    /// Advantages
    /// ----------
    /// - Function is interruptable, e.g. to allow graceful shutdown for server applications.
    /// - In case of error, it is always clear how much data was already written. No data is lost.
    ///
    /// [`write`]: ./trait.Write.html#tymethod.write
    /// [`std::io::Write::write_all`]:
    ///     https://doc.rust-lang.org/nightly/std/io/trait.Write.html#method.write_all
    /// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    #[inline]
    fn write_all<R: BufRead + ?Sized>(&mut self, buf: &mut R) -> io::Result<()> {
        copy(buf, self)
    }
}

impl<W: ?Sized+io::Write> Write for W {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        io::Write::write(self, buf)
    }

    #[inline]
    fn flush(&mut self) -> io::Result<()> {
        io::Write::flush(self)
    }
}

/// Alternative to `std::io::BufRead`
///
/// This trait is automatically implemented for all types that implement `std::io::BufRead`.
///
/// Differences to [`std::io::BufRead`]
/// ===================================
/// Methods that are just wrappers around the equivalent methods of [`std::io::BufRead`]:
///
/// - `fill_buf`
/// - `consume`
///
/// Methods that provide a slightly different functionality than their counterparts in
/// [`std::io::BufRead`]:
///
/// - `read_until`
/// - `split`
///
/// Methods originally implemented in a different place:
///
/// - `read_to_end` ← [`std::io::Read::read_to_end`]
/// - `read_exact` ← [`std::io::Read::read_exact`]
/// - `bytes` ← [`std::io::Read::bytes`]
///
/// New methods that have no counterpart in `std::io`:
///
/// - `skip_to_end`
/// - `skip_until`
///
/// Functions that were removed or moved to a different trait,
/// because they cannot be implemented with providing all desired guarantees:
///
/// - `read_line` → [`Utf8Reader::read_line`]
///
/// [`Utf8Reader::read_line`]: ./struct.Utf8Reader.html#method.read_line
/// [`std::io::Read::read_to_end`]:
///     https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.read_to_end
/// [`std::io::Read::read_exact`]:
///     https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.read_exact
/// [`std::io::Read::bytes`]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.bytes
/// [`std::io::Read`]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html
pub trait BufRead {
    /// Fills the internal buffer of this object, returning the buffer contents.
    ///
    /// This method is equivalent to [`std::io::BufRead::fill_buf`].
    ///
    /// [`std::io::BufRead::fill_buf`]:
    ///     https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#tymethod.fill_buf
    fn fill_buf(&mut self) -> io::Result<&[u8]>;

    /// Tells this buffer that `amt` bytes have been consumed from the buffer,
    /// so they should no longer be returned in calls to `read`.
    ///
    /// This method is equivalent to [`std::io::BufRead::consume`].
    ///
    /// [`std::io::BufRead::consume`]:
    ///     https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#tymethod.consume
    #[inline]
    fn consume(&mut self, amt: usize);

    /// Read all bytes until EOF in this source, placing them into `buf`.
    ///
    /// Similar to [`std::io::Read::read_to_end`], all bytes read from this source will
    /// be appended to the specified buffer `buf`.
    ///
    /// This function will continuously call [`fill_buf`] and [`consume`] to
    /// append more data to `buf` until [`fill_buf`] returns either `Ok(&[])` or any kind of error.
    ///
    /// Errors
    /// ======
    /// This function will return an error immediately if any call to [`fill_buf`] returns
    /// any kind of error.
    /// Instances of [`ErrorKind`]`::Interrupted` are *not* handled by this function.
    ///
    /// All bytes consumed from the reader will be written to the buffer and vice versa.
    /// It is guaranteed that no data is lost in case of error.
    ///
    /// Differences to `std::io::Read::read_to_end`
    /// ===========================================
    /// - Does not retry on [`ErrorKind`]`::Interrupted`.
    /// - Uses [`BufRead`] instead of [`Read`].
    /// - Does not return the number of bytes that are copied.
    /// - Works with all kind of writers, not just `Vec<u8>`
    ///
    /// Advantages
    /// ----------
    /// - Function is interruptable, e.g. to allow graceful shutdown for server applications.
    /// - Avoids double buffering if the source already implements [`BufRead`].
    /// - Allows different buffer sizes by using [`BufReader::with_capacity`].
    ///
    /// Disadvantages
    /// -------------
    /// The fact that it does not return the number of bytes copied stems from the fact that it
    /// cannot return this information in case of error.
    /// This would go against the goal of allowing reliable retry.
    ///
    /// [`fill_buf`]: ./trait.BufRead.html#tymethod.fill_buf
    /// [`consume`]: ./trait.BufRead.html#tymethod.consume
    /// [`BufRead`]: ./trait.BufRead.html
    /// [`Read`]: ./trait.Read.html
    /// [`BufReader::with_capacity`]:
    ///     ./buf_redux_reexport/struct.BufReader.html#method.with_capacity
    /// [`std::io::Read::read_to_end`]:
    ///     https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.read_to_end
    /// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    #[inline]
    fn read_to_end<R: Write + ?Sized>(&mut self, buf: &mut R) -> io::Result<()> {
        copy(self, buf)
    }

    /// Skip all bytes until EOF in this source.
    ///
    /// Acts like [`read_to_end`], but all bytes read from this source are
    /// discarded.
    ///
    /// This function will continuously call [`fill_buf`] and [`consume`] until
    /// [`fill_buf`] returns either `Ok(&[])` or any kind of error.
    ///
    /// Errors
    /// ======
    /// This function will return an error immediately if any call to [`fill_buf`] returns
    /// any kind of error.
    /// Instances of [`ErrorKind`]`::Interrupted` are *not* handled by this function.
    ///
    /// [`read_to_end`]: #method.read_to_end
    /// [`fill_buf`]: ./trait.BufRead.html#tymethod.fill_buf
    /// [`consume`]: ./trait.BufRead.html#tymethod.consume
    /// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    #[inline]
    fn skip_to_end(&mut self) -> io::Result<()> {
        copy(self, &mut io::sink())
    }

    /// Read the exact number of bytes required to fill `buf`.
    ///
    /// Similarliy to [`std::io::Read::read_exact`], this function reads as many bytes
    /// as necessary to completely fill the specified buffer `buf`.
    ///
    /// No guarantees are provided about the contents of `buf` when this
    /// function is called, implementations cannot rely on any property of the
    /// contents of `buf` being true. It is recommended that implementations
    /// only write data to `buf` instead of reading its contents.
    ///
    /// Errors
    /// ======
    /// This function will return an error immediately if any call to [`fill_buf`] returns
    /// any kind of error.
    /// Instances of [`ErrorKind`]`::Interrupted` are *not* handled by this function.
    ///
    /// If this function encounters an "end of file" before completely filling
    /// the buffer, it returns an error of the kind [`ErrorKind`]`::UnexpectedEof`.
    ///
    /// If this function returns an error, the buffer will contain all bytes read up to that point.
    /// The position of the cursor will point one byte past the last read byte.
    ///
    /// All bytes consumed from the reader will be written to the buffer and vice versa.
    /// It is guaranteed that no data is lost in case of error.
    ///
    /// Differences to `std::io::Read::read_exact`
    /// ==========================================
    /// - Does not retry on [`ErrorKind`]`::Interrupted`.
    /// - Uses [`BufRead`] instead of [`Read`].
    /// - In case of error the buffer contains all bytes read up to that point.
    /// - Takes a [`Cursor`] instead of plain buffer to track the current position.
    ///
    /// Advantages
    /// ----------
    /// - Function is interruptable, e.g. to allow graceful shutdown for server applications.
    /// - No data ist lost on error.
    ///
    /// Disadvantages
    /// -------------
    /// The function is slightly less ergonomic to use.
    ///
    /// [`fill_buf`]: ./trait.BufRead.html#tymethod.fill_buf
    /// [`BufRead`]: ./trait.BufRead.html
    /// [`Read`]: ./trait.Read.html
    /// [`Cursor`]: https://doc.rust-lang.org/nightly/std/io/struct.Cursor.html
    /// [`std::io::Read::read_exact`]:
    ///     https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.read_exact
    /// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    fn read_exact(&mut self, buf: &mut io::Cursor<&mut [u8]>) -> io::Result<()> {
        let mut remaining = buf.get_ref().len() - buf.position() as usize;
        while remaining > 0 {
            let written = {
                let available = try!(BufRead::fill_buf(self));
                if available.len() == 0 {
                    return Err(io::Error::new(io::ErrorKind::UnexpectedEof,
                                              "Stream is already at EOF"));
                }
                try!(buf.write(available))
            };
            remaining -= written;
            BufRead::consume(self, written);
        }
        Ok(())
    }

    /// Transforms this buffered reader into an iterator over its bytes.
    ///
    /// This method is approximately equivalent to [`std::io::Read::bytes`].
    ///
    /// The returned type implements [`std::iter::Iterator`]
    /// where the `Item` is `Result<u8, R::Err>`.
    /// The yielded item is `Ok` if a byte was successfully read and
    /// `Err` otherwise for I/O errors. EOF is mapped to returning `None` from
    /// this iterator.
    ///
    /// Errors
    /// ======
    /// If fill_buf returns any kind of error, the iterator yields `Some(Err)`. In case of error
    /// it is safe to iterate further to retry the reading operation.
    /// Instances of [`ErrorKind`]`::Interrupted` are *not* handled by the iterator.
    ///
    /// Differences to `std::io::Read::bytes`
    /// =====================================
    /// - Uses [`BufRead`] instead of [`Read`].
    ///
    /// Advantages
    /// ----------
    /// - No accidentialy unbuffered reading of single bytes
    ///
    /// [`Read`]: ./trait.Read.html
    /// [`BufRead`]: ./trait.BufRead.html
    /// [`std::io::Read::bytes`]:
    ///     https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.bytes
    /// [`std::iter::Iterator`]: https://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html
    /// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    #[inline]
    fn bytes(self) -> Bytes<Self>
        where Self: Sized
    {
        Bytes::new(self)
    }

    /// Read all bytes into a buffer until a delimiter is reached.
    ///
    /// Similar to [`std::io::BufRead::read_until`] ,this function will read bytes from
    /// the underlying stream and push them to the specified buffer `buf`, until the delimiter
    /// `delim` is found. If the delimiter is found, it is also part of the result.
    ///
    /// Errors
    /// ======
    /// This function will return an error immediately if any call to [`fill_buf`] returns
    /// any kind of error.
    /// Instances of [`ErrorKind`]`::Interrupted` are *not* handled by this function.
    ///
    /// If this reader has reached EOF then this function will return
    /// [`ErrorKind`]`::UnexpectedEof`.
    ///
    /// All bytes consumed from the buffered reader will be written to the specified buffer and
    /// vice versa.
    /// It is guaranteed that no data is lost in case of error.
    ///
    /// Differences to `std::io::BufRead::read_until`
    /// =============================================
    /// - Does not retry on [`ErrorKind`]`::Interrupted`.
    /// - Does not return the number of bytes that are read.
    /// - Returns an error on EOF instead of success.
    /// - Works with all kind of writers, not just `Vec<u8>`
    ///
    /// Advantages
    /// ----------
    /// - Function is interruptable, e.g. to allow graceful shutdown for server applications.
    ///
    /// Disadvantages
    /// -------------
    /// The fact that it does not return the number of bytes copied stems from the fact that it
    /// cannot return this information in case of error.
    /// This would go against the goal of allowing reliable retry.
    ///
    /// [`fill_buf`]: ./trait.BufRead.html#tymethod.fill_buf
    /// [`std::io::BufRead::read_until`]:
    ///     http://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#method.read_until
    /// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    #[inline]
    fn read_until<W: Write + ?Sized>(&mut self, delim: u8, buf: &mut W) -> io::Result<()> {
        copy_until(self, buf, delim)
    }

    /// Skips all bytes until a delimiter is reached.
    ///
    /// This function will discard bytes from the underlying stream until the delimiter `delim` is
    /// found.
    ///
    /// Acts like [`read_until`], but all bytes read from this source are
    /// discarded.
    ///
    /// Errors
    /// ======
    /// This function will return an error immediately if any call to [`fill_buf`] returns
    /// any kind of error.
    /// Instances of [`ErrorKind`]`::Interrupted` are *not* handled by this function.
    ///
    /// If this reader has reached EOF then this function will return
    /// [`ErrorKind`]`::UnexpectedEof`.
    ///
    /// [`read_until`]: #method.read_until
    /// [`fill_buf`]: ./trait.BufRead.html#tymethod.fill_buf
    /// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    #[inline]
    fn skip_until(&mut self, delim: u8) -> io::Result<()> {
        copy_until(self, &mut io::sink(), delim)
    }

    /// Returns an iterator over the contents of this reader split on a delimiter.
    ///
    /// The iterator returned from this function will return instances of
    /// `io::Result<Vec<u8>>`. Each vector returned will *not* have the
    /// delimiter byte at the end.
    ///
    /// Errors
    /// ======
    /// The iterator will yield an error whenever [`read_until`] would have also
    /// returned an error.
    ///
    /// [`read_until`]: #method.read_until
    #[inline]
    fn split(self, byte: u8) -> Split<Self>
        where Self: Sized
    {
        Split::new(self, byte)
    }
}

impl<R: ?Sized+io::BufRead> BufRead for R {
    #[inline]
    fn fill_buf(&mut self) -> io::Result<&[u8]> {
        io::BufRead::fill_buf(self)
    }

    #[inline]
    fn consume(&mut self, amt: usize) {
        io::BufRead::consume(self, amt)
    }
}

fn find2(delims: (u8, u8), buf: &[u8]) -> usize {
    let mut start = 0;
    while let Some(i) = memchr::memchr(delims.0, &buf[start..]) {
        let current = start + i;
        if (current == buf.len() - 1) || (buf[current + 1] == delims.1) {
            return current;
        }
        start = current + 1;
    }
    buf.len()
}

/// A `BufReadGrow` is a `BufRead`er that has the ability to read additional data even if the
/// buffer is not empty.
///
/// A `BufRead` guarantees an internal buffer of at only one byte with no possibility to read
/// additional data without consuming the already read data first.
/// With this limitation it is not possible to implement many functions in an interrupt-safe way.
///
/// Interrupt-safe function require that - when the function returns - all data is either left in
/// the stream or appended to the buffer.
/// But for example when read UTF-8 with a `BufRead`er,
/// this requirement can only be met by appending incomplete UTF-8 to the buffer which is also
/// unacceptable by itself.
///
/// For that reason, the `BufReadGrow` trait is introduced which extends `BufRead` by a method to
/// grow the internal buffer.
/// This requires the buffer to be able to relocate the data in the internal buffer.
pub trait BufReadGrow: io::BufRead {
    /// Grows the internal buffer of this object by at least one byte,
    /// returning the buffer contents.
    ///
    /// Like [`fill_buf`], this function is a lower-level call.
    /// It needs to be paired with the [`consume`] method to function properly.
    /// When calling this method, none of the contents will be "read" in the sense that later
    /// calling `read` may return the same contents. As such, `consume` must be
    /// called with the number of bytes that are consumed from this buffer to
    /// ensure that the bytes are never returned twice.
    ///
    /// Errors
    /// ======
    /// - Any error returned by the underlying call to `read` will be returned immediately.
    /// - If the stream has already reached EOF, an error of kind
    ///   [`ErrorKind`]`::UnexpectedEof` is returned.
    /// - If the internal buffer of is full, an appropriate error is returned.
    ///   Since there is no specific `ErrorKind` for this, [`ErrorKind`]`::Other`
    ///   should be used.
    ///
    /// [`fill_buf`]: trait.BufRead.html#tymethod.fill_buf
    /// [`consume`]: trait.BufRead.html#tymethod.consume
    /// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    fn grow_buf(&mut self) -> io::Result<&[u8]>;

    /// Fills the internal buffer to at least the specified amount,
    /// returning the buffer contents.
    ///
    /// Like [`BufRead::fill_buf`][`fill_buf`] and [`grow_buf`], this function is a lower-level call.
    /// It needs to be paired with the [`consume`] method to function properly.
    /// When calling this method, none of the contents will be "read" in the sense that later
    /// calling `read` may return the same contents. As such, `consume` must be
    /// called with the number of bytes that are consumed from this buffer to
    /// ensure that the bytes are never returned twice.
    ///
    /// Errors
    /// ======
    /// - Any I/O error will be returned immediately.
    /// - If the stream has already reached EOF, an error of kind
    ///   [`ErrorKind`]`::UnexpectedEof` is returned.
    /// - If the internal buffer of is full, an appropriate error is returned.
    ///   See [`grow_buf`] for more details.
    ///
    /// [`grow_buf`]: #tymethod.grow_buf
    /// [`fill_buf`]: trait.BufRead.html#tymethod.fill_buf
    /// [`consume`]: trait.BufRead.html#tymethod.consume
    /// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    fn fill_buf_min(&mut self, size: usize) -> io::Result<&[u8]> {
        let len = try!(self.fill_buf()).len();
        match len {
            0 => Err(io::Error::new(io::ErrorKind::UnexpectedEof, "Unexpected end of stream")),
            n if n == size - 1 => self.grow_buf(),
            n if n < size => {
                while try!(self.grow_buf()).len() < size { }
                self.fill_buf()
            }
            _ => self.fill_buf(),
        }
    }

    /// Read all bytes into a buffer until two consecutive delimiters are reached.
    ///
    /// This function will read bytes from the underlying stream and push them to the specified
    /// buffer `buf`, until the two consecutive delimiters `delims` are found.
    /// If the delimiters are found, they also part of the result.
    ///
    /// Errors
    /// ======
    /// This function will return an error immediately if a call to [`fill_buf`] returns
    /// any kind of error.
    /// Instances of [`ErrorKind`]`::Interrupted` are *not* handled by this function.
    ///
    /// If this reader has reached EOF then this function will return
    /// [`ErrorKind`]`::UnexpectedEof`.
    ///
    /// In case of an error, all bytes read up to that point are appended to the buffer and
    /// consumed from this buffered reader.
    /// There's one notable exception to that rule: If the last byte in the buffer would be the
    /// first delimiter, it is left in the buffered reader.
    /// Otherwise retrying on error would not work reliably.
    ///
    /// In any case, all bytes consumed from the buffered reader will be written to the specified
    /// buffer and vice versa.
    /// It is guaranteed that no data is lost in case of error.
    ///
    /// [`fill_buf`]: ./trait.BufRead.html#tymethod.fill_buf
    /// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    fn read_until2(&mut self, delims: (u8, u8), buf: &mut Vec<u8>) -> io::Result<()> {
        let mut extend = false;
        loop {
            let (done, used) = {
                let available = if extend {
                    try!(self.grow_buf())
                } else {
                    try!(self.fill_buf())
                };
                if available.len() == 0 {
                    return Err(io::Error::new(io::ErrorKind::UnexpectedEof,
                                              "Stream did not contain the delimiters"));
                }
                extend = false;
                let found = find2(delims, available);
                let (done, used) = if found == available.len() {
                    (false, found)
                } else if found == available.len() - 1 {
                    extend = true;
                    (false, found)
                } else {
                    (true, found + 2)
                };
                buf.extend_from_slice(&available[..used]);
                (done, used)
            };
            self.consume(used);
            if done {
                return Ok(());
            }
        }
    }

    /// Skip all bytes until two consecutive delimiters are reached.
    ///
    /// This function will discard bytes from the underlying stream until the two consecutive
    /// delimiters `delims` are found.
    ///
    /// Errors
    /// ======
    /// This function will return an error immediately if a call to [`fill_buf`] returns
    /// any kind of error.
    /// Instances of [`ErrorKind`]`::Interrupted` are *not* handled by this function.
    ///
    /// If this reader has reached EOF then this function will return
    /// [`ErrorKind`]`::UnexpectedEof`.
    ///
    /// [`fill_buf`]: ./trait.BufRead.html#tymethod.fill_buf
    /// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    fn skip_until2(&mut self, delims: (u8, u8)) -> io::Result<()> {
        let mut extend = false;
        loop {
            let (done, used) = {
                let available = if extend {
                    try!(self.grow_buf())
                } else {
                    try!(self.fill_buf())
                };
                if available.len() == 0 {
                    return Err(io::Error::new(io::ErrorKind::UnexpectedEof,
                                              "Stream did not contain the delimiters"));
                }
                extend = false;
                let found = find2(delims, available);
                let (done, used) = if found == available.len() {
                    (false, found)
                } else if found == available.len() - 1 {
                    extend = true;
                    (false, found)
                } else {
                    (true, found + 2)
                };
                (done, used)
            };
            self.consume(used);
            if done {
                return Ok(());
            }
        }
    }

    fn decode_utf8(self) -> utf8::Utf8Reader<Self>
        where Self : Sized
    {
        utf8::Utf8Reader::new(self)
    }
}

#[cfg(test)]
mod tests {
    use std::io;
    use buf_redux_reexport as br;

    use {Read, BufRead, BufReadGrow};

    #[test]
    fn read_until() {
        let mut buf = io::Cursor::new(&b"12"[..]);
        let mut v = Vec::new();
        assert_eq!(buf.read_until(b'3', &mut v).unwrap_err().kind(),
                   io::ErrorKind::UnexpectedEof);
        assert_eq!(v, b"12");

        let mut buf = io::Cursor::new(&b"1233"[..]);
        let mut v = Vec::new();
        buf.read_until(b'3', &mut v).unwrap();
        assert_eq!(v, b"123");
        v.truncate(0);
        buf.read_until(b'3', &mut v).unwrap();
        assert_eq!(v, b"3");
        v.truncate(0);
        assert_eq!(buf.read_until(b'3', &mut v).unwrap_err().kind(),
                   io::ErrorKind::UnexpectedEof);
        assert_eq!(v, b"");
    }

    #[test]
    fn read_to_end() {
        let mut c = io::Cursor::new(&b""[..]);
        let mut v = Vec::new();
        c.read_to_end(&mut v).unwrap();
        assert_eq!(v, b"");

        let mut c = io::Cursor::new(&b"1"[..]);
        let mut v = Vec::new();
        c.read_to_end(&mut v).unwrap();
        assert_eq!(v, b"1");

        let cap = 1024 * 1024;
        let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
        let mut v = Vec::new();
        let (a, b) = data.split_at(data.len() / 2);
        io::Cursor::new(a).read_to_end(&mut v).unwrap();
        io::Cursor::new(b).read_to_end(&mut v).unwrap();
        assert_eq!(v, data);
    }

    #[test]
    fn read_exact() {
        let mut buf = [0; 4];
        let mut buf = io::Cursor::new(&mut buf[..]);

        let mut c = io::Cursor::new(&b""[..]);
        assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
                   io::ErrorKind::UnexpectedEof);
        assert_eq!(buf.position(), 0);

        let mut c = io::Cursor::new(&b"123"[..]).chain(io::Cursor::new(&b"456789"[..]));
        buf.set_position(0);
        c.read_exact(&mut buf).unwrap();
        assert_eq!(buf.position(), 4);
        assert_eq!(buf.get_ref(), b"1234");
        buf.set_position(0);
        c.read_exact(&mut buf).unwrap();
        assert_eq!(buf.position(), 4);
        assert_eq!(buf.get_ref(), b"5678");
        buf.set_position(0);
        assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
                   io::ErrorKind::UnexpectedEof);
        assert_eq!(buf.position(), 1);
    }

    #[test]
    fn read_exact_slice() {
        let mut buf = [0; 4];
        let mut buf = io::Cursor::new(&mut buf[..]);

        let mut c = &b""[..];
        assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
                   io::ErrorKind::UnexpectedEof);

        let mut c = &b"123"[..];
        buf.set_position(0);
        assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
                   io::ErrorKind::UnexpectedEof);
        assert_eq!(buf.position(), 3);
        assert_eq!(buf.get_ref(), b"123\0");

        let mut c = &b"1234"[..];
        buf.set_position(0);
        c.read_exact(&mut buf).unwrap();
        assert_eq!(buf.position(), 4);
        assert_eq!(buf.get_ref(), b"1234");

        let mut c = &b"56789"[..];
        buf.set_position(0);
        c.read_exact(&mut buf).unwrap();
        assert_eq!(buf.position(), 4);
        assert_eq!(buf.get_ref(), b"5678");
        assert_eq!(c, b"9");
    }

    #[test]
    fn read_until2() {
        let mut buf = io::Cursor::new(&b"1234321234554"[..]);
        let mut v = Vec::new();
        assert_eq!(buf.read_until2((b'3', b'5'), &mut v).unwrap_err().kind(),
                   io::ErrorKind::UnexpectedEof);
        assert_eq!(v, b"1234321234554");

        let mut buf = io::Cursor::new(&b"1234321234554"[..]);
        let mut v = Vec::new();
        buf.read_until2((b'3', b'4'), &mut v).unwrap();
        assert_eq!(v, b"1234");
        v.truncate(0);
        buf.read_until2((b'3', b'4'), &mut v).unwrap();
        assert_eq!(v, b"321234");
        v.truncate(0);
        assert_eq!(buf.read_until2((b'3', b'4'), &mut v).unwrap_err().kind(),
                   io::ErrorKind::UnexpectedEof);
        assert_eq!(v, b"554");
    }

    #[test]
    fn read_until2_smallbuffer() {
        let mut buf = br::BufReader::with_capacity(3, io::Cursor::new(&b"12343212334554"[..]));
        let mut v = Vec::new();
        assert_eq!(buf.read_until2((b'3', b'5'), &mut v).unwrap_err().kind(),
                   io::ErrorKind::UnexpectedEof);
        assert_eq!(v, b"12343212334554");

        let mut buf = br::BufReader::with_capacity(3, io::Cursor::new(&b"12343212334554"[..]));
        let mut v = Vec::new();
        buf.read_until2((b'3', b'4'), &mut v).unwrap();
        assert_eq!(v, b"1234");
        v.truncate(0);
        buf.read_until2((b'3', b'4'), &mut v).unwrap();
        assert_eq!(v, b"3212334");
        v.truncate(0);
        assert_eq!(buf.read_until2((b'3', b'4'), &mut v).unwrap_err().kind(),
                   io::ErrorKind::UnexpectedEof);
        assert_eq!(v, b"554");
    }
}