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
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
//! Alternative implementation of many functions found in [`std::io`][stdio],
//! but suitable for blocking IO over networks.
//!
//! The main reason for this crate is the handling of [`ErrorKind::Interrupted`][errorkind] in
//! `std::io`.
//! Except for [`Read::read()`][readread] and [`Write::write()`][writewrite], 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 [`BufRead`][bufread] instead of [`Read`][read] to ensure that no
//! content is lost on retry.
//!
//! [stdio]: https://doc.rust-lang.org/nightly/std/io/index.html
//! [errorkind]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
//! [read]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html
//! [bufread]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html
//! [readread]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html#tymethod.read
//! [writewrite]: https://doc.rust-lang.org/nightly/std/io/trait.Write.html#tymethod.write

extern crate memchr;
extern crate buf_redux as br;

use std::{io, str};

mod impls;
mod adapt;
mod iter;

pub mod mock;

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

/// Copies the entire content of a buffered reader into a writer.
///
/// Similar to [`std::io::copy`][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`][fillbuf] or
/// [`write`][writewrite] returns any kind of error.
/// Instances of [`ErrorKind::Interrupted`][errorkind] 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`][errorkind].
/// - Uses [`BufRead`][bufread] instead of [`Read`][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`][bufread].
/// - Allows different buffer sizes by using [`BufReader::with_capacity`][withcap].
///
/// 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.
///
/// [copy]: https://doc.rust-lang.org/nightly/std/io/fn.copy.html
/// [errorkind]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
/// [fillbuf]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#tymethod.fill_buf
/// [writewrite]: https://doc.rust-lang.org/nightly/std/io/trait.Write.html#tymethod.write
/// [bufread]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html
/// [read]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html
/// [withcap]: https://doc.rust-lang.org/nightly/std/io/struct.BufReader.html#method.with_capacity
pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> io::Result<()>
    where R: io::BufRead,
          W: io::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`][fillbuf] or
/// [`write`][writewrite] returns any kind of error.
/// Instances of [`ErrorKind::Interrupted`][errorkind] 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.
///
/// [errorkind]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
/// [fillbuf]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#tymethod.fill_buf
/// [writewrite]: https://doc.rust-lang.org/nightly/std/io/trait.Write.html#tymethod.write
pub fn copy_until<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W, delim: u8) -> io::Result<()>
    where R: io::BufRead,
          W: io::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(());
        }
    }
}

/// 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`
/// - `by_ref`
/// - `chain`
///
/// Methods that provide a slightly different functionality than their counterparts in
/// `std::io::Read`:
///
/// - `take`
///
/// New methods that have no counterpart in `std::io::Read`:
///
/// - `buffer`
/// - `retry`
/// - `repeat`
///
/// Functions that were removed or moved to a different trait,
/// because they cannot be implemented with providing all desired guarantees:
///
/// - `read_to_end` -> moved to [`BufRead`]
/// - `read_to_string` -> moved to [`BufReadGrow`]
/// - `read_exact` -> moved to [`BufRead`]
/// - `bytes` -> moved to [`BufRead`]
/// - `chars` -> moved to [`BufReadGrow`]
///
/// [`std::io::Read`]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html
/// [`BufRead`]: trait.BufRead.html
/// [`BufReadGrow`]: trait.BufReadGrow.html
pub trait Read: io::Read {
    /// Pull some bytes from this source into the specified buffer, returning
    /// how many bytes were read.
    ///
    /// This is just a "reexport" of [`std::io::Read::read`][readread] provided for convenience.
    ///
    /// [readread]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html#tymethod.read
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        io::Read::read(self, buf)
    }

    /// Creates a "by reference" adaptor for this instance of `Read`.
    ///
    /// This is just a "reexport" of [`std::io::Read::by_ref`][byref] provided for convenience.
    ///
    /// [byref]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html#tymethod.by_ref
    #[inline]
    fn by_ref(&mut self) -> &mut Self
        where Self: Sized
    {
        io::Read::by_ref(self)
    }

    /// Creates an adaptor which will chain this stream with another.
    ///
    /// This is just a "reexport" of [`std::io::Read::chain`][chain] provided for convenience.
    ///
    /// [chain]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html#tymethod.chain
    #[inline]
    fn chain<R: io::Read>(self, next: R) -> io::Chain<Self, R>
        where Self: Sized
    {
        io::Read::chain(self, next)
    }

    /// Creates an adapter which will read at most `limit` bytes from it.
    ///
    /// This function returns a new instance of `Read` which will read at most
    /// `limit` bytes, after which it will always return EOF (`Ok(0)`). Any
    /// read errors will not count towards the number of bytes read and future
    /// calls to `read` may succeed.
    ///
    /// See also [`Write::take`].
    ///
    /// Differences to `std::io::Read::take`
    /// ====================================
    /// This function is equivalent to [`std::io::Read::take`][iotake] except that the returned
    /// adapter implements [`BufReadGrow`] and [`std::io::Write`] if possible.
    ///
    /// [`Write::take`]: trait.Write.html#method.take
    /// [iotake]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.take
    /// [`BufReadGrow`]: trait.BufReadGrow.html
    /// [`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)
    }

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

    /// Transforms this reader into a reader that automatically retries on interrupts
    ///
    /// The returned adapter will behave identically to the original reader, except that it retries
    /// the reading operation automatically if an error of kind
    /// [`ErrorKind::Interrupted`][errorkind] 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)
    }

    /// 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: io::Read> Read for R {}

/// 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`
/// - `by_ref`
///
/// Methods that provide a slightly different functionality than their counterparts in
/// `std::io::Write`:
///
/// - `write_all`
///
/// New methods that have no counterpart in `std::io::Write`:
///
/// - `retry`
/// - `take`
///
/// Functions that were removed or moved to a different trait,
/// because they cannot be implemented with providing all desired guarantees:
///
/// - `write_fmt`
pub trait Write: io::Write {
    /// Write a buffer into this object, returning how many bytes were written.
    ///
    /// This is just a "reexport" of [`std::io::Write::write`][write] provided for convenience.
    ///
    /// [write]: https://doc.rust-lang.org/nightly/std/io/trait.Write.html#tymethod.write
    #[inline]
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        io::Write::write(self, buf)
    }

    /// Flush this output stream, ensuring that all intermediately buffered
    /// contents reach their destination.
    ///
    /// This is just a "reexport" of [`std::io::Write::flush`][flush] provided for convenience.
    ///
    /// [flush]: https://doc.rust-lang.org/nightly/std/io/trait.Write.html#tymethod.flush
    #[inline]
    fn flush(&mut self) -> io::Result<()> {
        io::Write::flush(self)
    }

    /// Attempts to write an entire buffer into this write.
    ///
    /// Similarly to [`std::io::Write::write_all`][iowriteall],
    /// 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`][writewrite] returns
    /// any kind of error.
    /// Instances of [`ErrorKind::Interrupted`][errorkind] 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`][errorkind].
    /// - 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.
    ///
    /// [iowriteall]: https://doc.rust-lang.org/nightly/std/io/trait.Write.html#method.write_all
    /// [writewrite]: https://doc.rust-lang.org/nightly/std/io/trait.Write.html#tymethod.write
    /// [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)
    }

    /// Creates a "by reference" adaptor for this instance of `Write`.
    ///
    /// This is just a "reexport" of [`std::io::Write::by_ref`][byref] provided for convenience.
    ///
    /// [byref]: https://doc.rust-lang.org/nightly/std/io/trait.Write.html#tymethod.by_ref
    #[inline]
    fn by_ref(&mut self) -> &mut Self
        where Self: Sized
    {
        io::Write::by_ref(self)
    }

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

    /// Creates an adapter which will write at most `limit` bytes to it.
    ///
    /// This function returns a new instance of `Write` which will write at most
    /// `limit` bytes, after which it will always return Ok(0).
    /// Any write errors will not count towards the number of bytes written and future
    /// calls to `write` may succeed.
    ///
    /// This function is equivalent to `std::io::Read::take` but the returened adapter implements
    /// `Write`.
    ///
    /// See also [`Read::take`].
    ///
    /// [`Read::take`]: trait.Read.html#method.take
    #[inline]
    fn take(self, limit: u64) -> Take<Self>
        where Self: Sized
    {
        Take::new(self, limit)
    }
}

impl<W: io::Write> Write for W {}

/// 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 trait:
///
/// - `read_to_end` from [`std::io::Read`][ioread]
/// - `read_exact` from [`std::io::Read`][ioread]
/// - `bytes` from [`std::io::Read`][ioread]
///
/// 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` moved to [`BufReadGrow`]
///
/// [ioread]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html
/// [`BufReadGrow`]: trait.BufReadGrow.html
pub trait BufRead: io::BufRead {
    /// Fills the internal buffer of this object, returning the buffer contents.
    ///
    /// This is just a "reexport" of [`std::io::BufRead::fill_buf`][fillbuf] provided for
    /// convenience.
    ///
    /// [fillbuf]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#tymethod.fill_buf
    #[inline]
    fn fill_buf(&mut self) -> io::Result<&[u8]> {
        io::BufRead::fill_buf(self)
    }

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

    // ============================================================================================
    // Methods originally implemented in std::io::Read
    // ============================================================================================

    /// Read all bytes until EOF in this source, placing them into `buf`.
    ///
    /// Similar to [`std::io::Read::read_to_end`][readtoend], all bytes read from this source will
    /// be appended to the specified buffer `buf`.
    ///
    /// This function will continuously call [`fill_buf`][fillbuf] and [`consume`][consume] to
    /// append more data to `buf` until [`fill_buf`][fillbuf] returns either `Ok(&[])` or any kind
    /// of error.
    ///
    /// Errors
    /// ======
    /// This function will return an error immediately if any call to [`fill_buf`][fillbuf] returns
    /// any kind of error.
    /// Instances of [`ErrorKind::Interrupted`][errorkind] 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`][errorkind].
    /// - Uses [`BufRead`][bufread] instead of [`Read`][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`][bufread].
    /// - Allows different buffer sizes by using [`BufReader::with_capacity`][withcap].
    ///
    /// 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.
    ///
    /// [readtoend]: 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
    /// [fillbuf]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#tymethod.fill_buf
    /// [consume]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#tymethod.consume
    /// [bufread]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html
    /// [read]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html
    /// [withcap]:
    ///     https://doc.rust-lang.org/nightly/std/io/struct.BufReader.html#method.with_capacity
    #[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`][fillbuf] and [`consume`][consume] until
    /// [`fill_buf`][fillbuf] returns either `Ok(&[])` or any kind of error.
    ///
    /// Errors
    /// ======
    /// This function will return an error immediately if any call to [`fill_buf`][fillbuf] returns
    /// any kind of error.
    /// Instances of [`ErrorKind::Interrupted`][errorkind] are *not* handled by this function.
    ///
    /// [`read_to_end`]: #method.read_to_end
    /// [errorkind]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    /// [fillbuf]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#tymethod.fill_buf
    /// [consume]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#tymethod.consume
    #[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`][readexact], 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`][fillbuf] returns
    /// any kind of error.
    /// Instances of [`ErrorKind::Interrupted`][errorkind] 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`][errorkind].
    ///
    /// 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`][errorkind].
    /// - Uses [`BufRead`][bufread] instead of [`Read`][read].
    /// - In case of error the buffer contains all bytes read up to that point.
    /// - Takes a [`Cursor`][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.
    ///
    /// [readexact]: 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
    /// [fillbuf]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#tymethod.fill_buf
    /// [bufread]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html
    /// [read]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html
    /// [cursor]: https://doc.rust-lang.org/nightly/std/io/struct.Cursor.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 [`BufRead`][bufread] instance to an [`Iterator`][iterator] over its bytes.
    ///
    /// This method is approximately equivalent to [`std::io::Read::bytes`][bytes].
    ///
    /// The returned type implements [`Iterator`][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`][errorkind] are *not* handled by the iterator.
    ///
    /// Differences to `std::io::Read::bytes`
    /// =====================================
    /// - Uses [`BufRead`][bufread] instead of [`Read`][read].
    ///
    /// Advantages
    /// ----------
    /// - No accidentialy unbuffered reading of single bytes
    ///
    /// [iterator]: https://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html
    /// [bufread]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html
    /// [bytes]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.bytes
    /// [errorkind]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    /// [read]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html
    #[inline]
    fn bytes(self) -> Bytes<Self>
        where Self: Sized
    {
        Bytes::new(self)
    }

    // ============================================================================================
    // Methods originally implemented in std::io::BufRead
    // ============================================================================================

    /// Read all bytes into a buffer until a delimiter is reached.
    ///
    /// Similar to [`std::io::BufRead::read_until`][readuntil] ,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`][fillbuf] returns
    /// any kind of error.
    /// Instances of [`ErrorKind::Interrupted`][errorkind] are *not* handled by this function.
    ///
    /// If this reader has reached EOF then this function will return
    /// [`ErrorKind::UnexpectedEof`][errorkind].
    ///
    /// 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`][errorkind].
    /// - 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.
    ///
    /// [readuntil]: 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
    /// [fillbuf]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#tymethod.fill_buf
    #[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`][fillbuf] returns
    /// any kind of error.
    /// Instances of [`ErrorKind::Interrupted`][errorkind] are *not* handled by this function.
    ///
    /// If this reader has reached EOF then this function will return
    /// [`ErrorKind::UnexpectedEof`][errorkind].
    ///
    /// [`read_until`]: #method.read_until
    /// [errorkind]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    /// [fillbuf]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#tymethod.fill_buf
    #[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: io::BufRead> BufRead for R {}

fn utf8_valid_up_to(buf: &[u8]) -> io::Result<usize> {
    match str::from_utf8(buf) {
        Ok(_) => Ok(buf.len()),
        Err(e) if e.valid_up_to() > 0 => Ok(e.valid_up_to()),
        Err(_) if buf.len() > 4 => {
            Err(io::Error::new(io::ErrorKind::InvalidData,
                               "stream did not contain valid UTF-8"))
        } // TODO: improve UTF-8 validity test
        Err(_) => Ok(0),
    }
}

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 `BufRead::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`][errorkind] is returned.
    /// - If the internal buffer of is full, an appropriate error is returned.
    ///   Since there is no specific `ErrorKind` for this, [`ErrorKind::Other`][errorkind]
    ///   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`][errorkind] is returned.
    /// - If the internal buffer of is full, an appropriate error is returned.
    ///   See [`grow_buf`] for more details.
    ///
    /// [`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
    /// [`grow_buf`]: #tymethod.grow_buf
    fn fill_buf_min(&mut self, size: usize) -> io::Result<&[u8]> {
        match try!(self.fill_buf()).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`][fillbuf] returns
    /// any kind of error.
    /// Instances of [`ErrorKind::Interrupted`][errorkind] are *not* handled by this function.
    ///
    /// If this reader has reached EOF then this function will return
    /// [`ErrorKind::UnexpectedEof`][errorkind].
    ///
    /// 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.
    ///
    /// [errorkind]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    /// [fillbuf]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#tymethod.fill_buf
    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`][fillbuf] returns
    /// any kind of error.
    /// Instances of [`ErrorKind::Interrupted`][errorkind] are *not* handled by this function.
    ///
    /// If this reader has reached EOF then this function will return
    /// [`ErrorKind::UnexpectedEof`][errorkind].
    ///
    /// [errorkind]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    /// [fillbuf]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#tymethod.fill_buf
    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(());
            }
        }
    }

    /// Fills the internal buffer of this object, returning the buffer content as a string
    ///
    /// This function will return at least one valid `char` except when reaching EOF.
    /// If invalid or incomplete UTF-8 is encountered, the function returns all valid UTF-8 up to
    /// that point.
    ///
    /// If the function returns an empty slice, the unterlying reader has reached EOF and all data
    /// in the stream was valid UTF-8.
    ///
    /// Errors
    /// ======
    /// - If either `fill_buf` or `grow_buf` return an error, this error is returned immediately.
    /// - If invalid UTF-8 is encountered at the beginning of the buffer, an error of kind
    ///   [`ErrorKind::InvalidData`][errorkind] is returned.
    /// - If an incomplete UTF-8 character followed by EOF is encountered at the beginning of the
    ///   buffer, an error of kind [`ErrorKind::UnexpectedEof`][errorkind] is returned.
    ///
    /// Issues
    /// ======
    /// Currently there's no way to decide if the remaining data is an incomplete UTF-8 char or
    /// just plain invalid UTF-8 if the remaining buffer is smaller or equal than 4 bytes.
    /// (Issue [`rust-lang/rust#32584`][issue])
    ///
    /// This case is currently just interpreted as [`ErrorKind::UnexpectedEof`][errorkind].
    ///
    /// [errorkind]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    /// [issue]: https://github.com/rust-lang/rust/issues/32584
    fn fill_buf_str(&mut self) -> io::Result<&str> {
        let (buflen, mut valid_up_to) = {
            let buf = try!(self.fill_buf());
            (buf.len(), try!(utf8_valid_up_to(buf)))
        };
        if buflen != 0 {
            while valid_up_to == 0 {
                valid_up_to = try!(utf8_valid_up_to(try!(self.grow_buf())));
            }
        }
        let buf = try!(self.fill_buf());
        Ok(str::from_utf8(&buf[0..valid_up_to]).expect("Buffer content is not valid UTF-8"))
    }

    /// Grows the internal buffer of this object by at least one char,
    /// returning the buffer content as a string
    ///
    /// This function will return at least one additional valid `char` compared to a call to
    /// `fill_buf_str`.
    /// If invalid or incomplete UTF-8 is encountered, the function returns all valid UTF-8 up to
    /// that point.
    ///
    /// If the function returns an empty slice, the unterlying reader has reached EOF and all data
    /// in the stream was valid UTF-8.
    ///
    /// Errors
    /// ======
    /// - If either `fill_buf` or `grow_buf` return an error, this error is returned immediately.
    /// - If invalid UTF-8 is encountered at the beginning of the buffer s.t. no additional char
    ///   can be returned, an error of kind [`ErrorKind::InvalidData`][errorkind] is returned.
    /// - If EOF is encountered, such that no additional char can be returned, an error of kind
    ///   [`ErrorKind::UnexpectedEof`][errorkind] is returned.
    ///
    /// Issues
    /// ======
    /// Currently there's no way to decide if the remaining data is an incomplete UTF-8 char or
    /// just plain invalid UTF-8 if the remaining buffer is smaller or equal than 4 bytes.
    /// (Issue [`rust-lang/rust#32584`][issue])
    ///
    /// This case is currently just interpreted as [`ErrorKind::UnexpectedEof`][errorkind].
    ///
    /// [errorkind]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    /// [issue]: https://github.com/rust-lang/rust/issues/32584
    fn grow_buf_str(&mut self) -> io::Result<&str> {
        let start = try!(utf8_valid_up_to(try!(self.fill_buf())));
        let mut valid_up_to = start;
        while valid_up_to == start {
            let buf = try!(self.grow_buf());
            valid_up_to += try!(utf8_valid_up_to(&buf[valid_up_to..]));
        }
        let buf = try!(self.fill_buf());
        Ok(str::from_utf8(&buf[0..valid_up_to]).expect("Buffer content is not valid UTF-8"))
    }

    /// Read all bytes until EOF in this source, placing them into a string.
    ///
    /// This function will continuously call [`fill_buf`][fillbuf]/[`grow_buf`][growbuf] and
    /// [`consume`][consume] to append more data to `buf` until [`fill_buf`][fillbuf] returns
    /// either `Ok(&[])` or any kind of error occurs.
    ///
    /// Errors
    /// ======
    /// This function will return an error immediately if any call to [`fill_buf`][fillbuf] or
    /// [`grow_buf`][growbuf] returns any kind of error.
    /// Instances of [`ErrorKind::Interrupted`][errorkind] are *not* handled by this function.
    ///
    /// If invalid UTF-8 is encountered, an error of kind [`ErrorKind::InvalidData`][errorkind] is
    /// returned and the string will contain all valid UTF-8 up to that point.
    ///
    /// 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_string`
    /// ==============================================
    /// - Does not retry on [`ErrorKind::Interrupted`][errorkind].
    /// - Uses `BufReadGrow` instead of [`BufRead`][bufread].
    /// - Does not return the number of bytes that are copied.
    /// - On error, string will contain all valid UTF-8 up to that point.
    ///
    /// Advantages
    /// ----------
    /// - Function is interruptable, e.g. to allow graceful shutdown for server applications.
    /// - No data ist lost on error (e.g. invalid UTF-8).
    ///
    /// 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.
    ///
    /// [errorkind]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    /// [fillbuf]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#tymethod.fill_buf
    /// [growbuf]: ./trait.BufReadGrow.html#tymethod.grow_buf
    /// [consume]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#tymethod.consume
    /// [bufread]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html
    fn read_to_string(&mut self, buf: &mut String) -> io::Result<()> {
        loop {
            let written = {
                let available = try!(self.fill_buf_str());
                if available.is_empty() {
                    return Ok(());
                }
                buf.push_str(available);
                available.len()
            };
            self.consume(written);
        }
    }

    /// Read all bytes until a CRLF is reached, and append them to the provided buffer.
    ///
    /// This function will UTF-8 characters from the underlying stream and append them to the 'buf'
    /// until the CRLF delimiter (the 0xA 0xD bytes) is found.
    ///
    /// Errors
    /// ======
    /// Like `read_until2`, this function will return an error immediately if a call to
    /// [`fill_buf`][fillbuf] returns any kind of error.
    /// Instances of [`ErrorKind::Interrupted`][errorkind] are *not* handled by this function.
    ///
    /// This function will return an error of kind [`ErrorKind::InvalidData`][errorkind] if the
    /// read bytes are not valid UTF-8.
    /// If EOF is reached, an error of kind [`ErrorKind::UnexpectedEof`][errorkind] is returned.
    ///
    /// If any kind of error occurs, the buffer will contain all valid UTF-8 up to that point.
    ///
    /// 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.
    ///
    /// The read buffer will never contain a CR (`\r`) as last character, even in case of error.
    /// Doing so could lead to skipping a CRLF sequence in case of retry.
    /// In case of `ErrorKind::UnexpectedEof`, this behavior is a bit unexpected and may
    /// change in a future version.
    ///
    /// Differences to `std::io::BufRead::read_line`
    /// ============================================
    /// - Does not retry on [`ErrorKind::Interrupted`][errorkind].
    /// - Does not return the number of bytes that are read.
    /// - Returns an error on EOF instead of success.
    /// - Uses CRLF as line ending convention instead of just LF.
    ///
    /// Advantages
    /// ----------
    /// - Function is interruptable, e.g. to allow graceful shutdown for server applications.
    /// - Suitable for network protocols, because those usually use CRLF as line endings.
    ///
    /// 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.
    ///
    /// [fillbuf]: https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#tymethod.fill_buf
    /// [errorkind]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    fn read_line(&mut self, buf: &mut String) -> io::Result<()> {
        let mut extend = false;
        loop {
            let (done, used) = {
                let available = if extend {
                    try!(self.grow_buf_str())
                } else {
                    try!(self.fill_buf_str())
                };
                if available.is_empty() {
                    return Err(io::Error::new(io::ErrorKind::UnexpectedEof,
                                              "Stream did not contain the delimiters"));
                }
                extend = false;
                let found = find2((b'\r', b'\n'), available.as_bytes());
                let (done, used) = if found == available.len() {
                    (false, found)
                } else if found == available.len() - 1 {
                    extend = true;
                    (false, found)
                } else {
                    (true, found + 2)
                };
                buf.push_str(&available[..used]);
                (done, used)
            };
            self.consume(used);
            if done {
                return Ok(());
            }
        }
    }

    /// Transforms this reader to an `Iterator` over `char`s.
    ///
    /// Similar to `std::io::Read::chars`, this adaptor will attempt to interpret this reader
    /// as a UTF-8 encoded sequence of characters.
    /// The returned iterator will return `None` once
    /// EOF is reached for this reader. Otherwise each element yielded will be a
    /// `io::Result<char>`.
    ///
    /// Errors
    /// ======
    /// In any call to `fill_buf` or `grow_buf` returns any kind of error,
    /// this error is yielded by the iterator.
    /// If invalid UTF-8 is encountered an error of kind [`ErrorKind::InvalidData`][errorkind] is
    /// yielded.
    /// If the stream is reaching EOF in the middle of an otherwise valid UTF-8 characters,
    /// an error of kind [`ErrorKind::UnexpectedEof`][errorkind] is yielded.
    ///
    /// Errors of kind ErrorKind::Interrupted are *not* handled by the iterator itself but
    /// treated as any other kind of error.
    /// In case of an error, the iterator will not skip any data.
    /// Iterating further will simply retry the failed operation.
    ///
    /// *Note: Ignoring errors will most likely "end" in an endless loop*
    ///
    /// Differences to std::io::Read::Chars
    /// ===================================
    /// - Errors of kind [`ErrorKind::Interrupted`][errorkind] are not swallowed.
    /// - Uses the usual [`io::Error`] instead of a custom error type.
    /// - Invalid UTF-8 is not skipped.
    ///
    /// Issues
    /// ======
    /// Currently there's no way to decide if the remaining data is an incomplete but otherwise
    /// valid UTF-8 char or just plain invalid UTF-8.
    /// (Issue [`rust-lang/rust#32584`][issue])
    ///
    /// [errorkind]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html
    /// [`io::Error`]: https://doc.rust-lang.org/nightly/std/io/struct.Error.html
    /// [issue]: https://github.com/rust-lang/rust/issues/32584
    fn chars(self) -> Chars<Self>
        where Self: Sized
    {
        Chars::new(self)
    }
}

#[cfg(test)]
mod tests {
    use std::io;
    use 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_to_string() {
        let mut c = io::Cursor::new(&b""[..]);
        let mut v = String::new();
        c.read_to_string(&mut v).unwrap();
        assert_eq!(v, "");

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

        let mut c = io::Cursor::new(&b"\xff"[..]);
        let mut v = String::new();
        assert!(c.read_to_string(&mut v).is_err());
    }

    #[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");
    }

    #[test]
    fn read_line() {
        let mut buf = io::Cursor::new(&b"hihi\r\nhoho\rhaha\nhehe\n\rhrhr\r\n\r\r\n\r\n"[..]);
        let mut v = String::new();
        buf.read_line(&mut v).unwrap();
        assert_eq!(v, "hihi\r\n");
        v.truncate(0);
        buf.read_line(&mut v).unwrap();
        assert_eq!(v, "hoho\rhaha\nhehe\n\rhrhr\r\n");
        v.truncate(0);
        buf.read_line(&mut v).unwrap();
        assert_eq!(v, "\r\r\n");
        v.truncate(0);
        buf.read_line(&mut v).unwrap();
        assert_eq!(v, "\r\n");
        v.truncate(0);
        assert_eq!(buf.read_line(&mut v).unwrap_err().kind(),
                   io::ErrorKind::UnexpectedEof);
        assert_eq!(v, "");
    }
    
    #[test]
    fn fill_buf_str_unexpected_eof() {
        // Needs continuation character
        let testdata = [b'A', 0xC0];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::UnexpectedEof);

        // Needs continuation character
        let testdata = [b'A', 0xE0];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::UnexpectedEof);

        // Needs continuation character
        let testdata = [b'A', 0xE0, 0x80];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::UnexpectedEof);

        // Needs continuation character
        let testdata = [b'A', 0xF0];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::UnexpectedEof);

        // Needs continuation character
        let testdata = [b'A', 0xF0, 0x80];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::UnexpectedEof);

        // Needs continuation character
        let testdata = [b'A', 0xF0, 0x80, 0x80];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
    }
    
    #[test]
    fn fill_buf_str_invalid_data() {
        // cannot start with continuation character
        let testdata = [b'A', 0x80];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        testdata.fill_buf_str().unwrap_err();
        //assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::InvalidData);
        
        // cannot start with continuation characters
        let testdata = [b'A', 0x80, 0x80];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        testdata.fill_buf_str().unwrap_err();
        //assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::InvalidData);
        
        // cannot start with continuation characters
        let testdata = [b'A', 0x80, 0x80, 0x80];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        testdata.fill_buf_str().unwrap_err();
        //assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::InvalidData);
        
        // cannot start with continuation characters
        let testdata = [b'A', 0x80, 0x80, 0x80, 0x80];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        testdata.fill_buf_str().unwrap_err();
        //assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::InvalidData);
        
        // cannot start with continuation characters
        let testdata = [b'A', 0x80, 0x80, 0x80, 0x80, 0x80];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::InvalidData);

        // Invalid continuation character
        let testdata = [b'A', 0xC0, b'A'];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        testdata.fill_buf_str().unwrap_err();
        //assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::InvalidData);

        // Invalid continuation character
        let testdata = [b'A', 0xC0, b'A', b'A'];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        testdata.fill_buf_str().unwrap_err();
        //assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::InvalidData);

        // Invalid continuation character
        let testdata = [b'A', 0xC0, b'A', b'A', b'A'];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        testdata.fill_buf_str().unwrap_err();
        //assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::InvalidData);

        // Invalid continuation character
        let testdata = [b'A', 0xC0, b'A', b'A', b'A', b'A'];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::InvalidData);

        // Invalid continuation character
        let testdata = [b'A', 0xE0, b'A'];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        testdata.fill_buf_str().unwrap_err();
        //assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::InvalidData);

        // Invalid continuation character
        let testdata = [b'A', 0xE0, b'A', b'A'];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        testdata.fill_buf_str().unwrap_err();
        //assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::InvalidData);

        // Invalid continuation character
        let testdata = [b'A', 0xE0, b'A', b'A', b'A'];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        testdata.fill_buf_str().unwrap_err();
        //assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::InvalidData);

        // Invalid continuation character
        let testdata = [b'A', 0xE0, b'A', b'A', b'A', b'A'];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::InvalidData);

        // Invalid continuation character
        let testdata = [b'A', 0xF0, b'A'];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        testdata.fill_buf_str().unwrap_err();
        //assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::InvalidData);

        // Invalid continuation character
        let testdata = [b'A', 0xF0, b'A', b'A'];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        testdata.fill_buf_str().unwrap_err();
        //assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::InvalidData);

        // Invalid continuation character
        let testdata = [b'A', 0xF0, b'A', b'A', b'A'];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        testdata.fill_buf_str().unwrap_err();
        //assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::InvalidData);

        // Invalid continuation character
        let testdata = [b'A', 0xF0, b'A', b'A', b'A', b'A'];
        let mut testdata = io::Cursor::new(testdata);
        assert_eq!(testdata.fill_buf_str().unwrap(), "A");
        testdata.consume(1);
        assert_eq!(testdata.fill_buf_str().unwrap_err().kind(), io::ErrorKind::InvalidData);
    }
}