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
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
// License: see LICENSE file at root directory of `master` branch

//! # Values

use std::cmp::Ordering;
use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::io::{self, Error, ErrorKind, Read, Write};
use std::mem;

/// # Null
pub const NULL: u8 = 0b_0000_0000;

/// # True
pub const TRUE: u8 = 0b_0000_0001;

/// # False
pub const FALSE: u8 = 0b_0000_0010;

/// # 8-bit unsigned integer
pub const U8: u8 = 0b_0010_0000;

/// # 8-bit signed integer
pub const I8: u8 = 0b_0010_0001;

/// # 16-bit unsigned integer
pub const U16: u8 = 0b_0100_0000;

/// # 16-bit signed integer
pub const I16: u8 = 0b_0100_0001;

/// # 32-bit unsigned integer
pub const U32: u8 = 0b_0110_0000;

/// # 32-bit signed integer
pub const I32: u8 = 0b_0110_0001;

/// # Float
pub const FLOAT: u8 = 0b_0110_0010;

/// # 64-bit unsigned integer
pub const U64: u8 = 0b_1000_0000;

/// # 64-bit signed integer
pub const I64: u8 = 0b_1000_0001;

/// # Double
pub const DOUBLE: u8 = 0b_1000_0010;

/// # Text
pub const TEXT: u8 = 0b_1010_0000;

/// # Date time
pub const DATE_TIME: u8 = 0b_1010_0001;

/// # Date
pub const DATE: u8 = 0b_1010_0010;

/// # Time
pub const TIME: u8 = 0b_1010_0011;

/// # Decimal string
pub const DECIMAL_STR: u8 = 0b_1010_0100;

/// # Blob
pub const BLOB: u8 = 0b_1100_0000;

/// # List
pub const LIST: u8 = 0b_1110_0000;

/// # Map
pub const MAP: u8 = 0b_1110_0001;

/// # Object
pub const OBJECT: u8 = 0b_1110_0010;

/// # Size mask
const SIZE_MASK: u32 = 0x_8000_0000_u32;

/// # Object key's max length
pub const OBJECT_KEY_MAX_LEN: usize = 255;

#[test]
fn test_object_key_max_len() {
    assert_eq!(cmp_integers!(OBJECT_KEY_MAX_LEN, ::std::u8::MAX), Ordering::Equal);
}

/// # Max data size, in bytes
pub const MAX_DATA_SIZE: u32 = ::std::i32::MAX as u32;

/// # Values
#[derive(Clone, PartialEq)]
pub enum Value {

    /// # Null
    Null,

    /// # True
    True,

    /// # False
    False,

    /// # 8-bit unsigned integer
    U8(u8),

    /// # 8-bit signed integer
    I8(i8),

    /// # 16-bit unsigned integer
    U16(u16),

    /// # 16-bit signed integer
    I16(i16),

    /// # 32-bit unsigned integer
    U32(u32),

    /// # 32-bit signed integer
    I32(i32),

    /// # Float
    Float(f32),

    /// # 64-bit unsigned integer
    U64(u64),

    /// # 64-bit signed integer
    I64(i64),

    /// # Double
    Double(f64),

    /// # Text
    Text(String),

    /// # Date time
    DateTime(String),

    /// # Date
    Date(String),

    /// # Time
    Time(String),

    /// # Decimal string
    DecimalStr(String),

    /// # Blob
    Blob(Vec<u8>),

    /// # List
    List(Vec<Value>),

    /// # Map
    Map(BTreeMap<i32, Value>),

    /// # Object
    Object(HashMap<String, Value>),

}

/// # Makes plural suffix
macro_rules! make_plural_suffix {
    ($size: expr, $one: expr, $other: expr) => {{
        match $size {
            1 => $one,
            _ => $other,
        }
    }};
    // This one makes 's' plural suffix
    ($size: expr) => {{
        make_plural_suffix!($size, "", "s")
    }};
}

/// # Displays a string in a formatter
///
/// If the string is too long, just displays a part of it.
///
/// Result: `Result<(), fmt::Error>`
macro_rules! display_str { ($formatter: ident, $prefix: expr, $s: ident, $suffix: expr) => {{
    write!($formatter, "{}", $prefix)?;

    let char_count = &$s.chars().count();
    let limit = 50;
    match char_count.checked_sub(limit) {
        Some(more) => write!($formatter, "\"{}...\" ({} more)", &$s.chars().take(limit).collect::<String>(), more)?,
        None => write!($formatter, "\"{}\"", &$s)?,
    };

    write!($formatter, "{}", $suffix)
}};}

/// # Max display items of list/map/object
const LIST_MAP_OBJECT_MAX_DISPLAY_ITEMS: usize = 10;

/// # Displays a list in a formatter
///
/// If the items are too much, just displays a part of them.
///
/// Result: `Result<(), fmt::Error>`
macro_rules! display_list { ($formatter: ident, $value: ident, $list: ident) => {{
    let item_count = $list.len();

    match $value.len() {
        Ok(len) => {
            write!($formatter, "List({} item{}, {} byte{}: [", &item_count, make_plural_suffix!(&item_count), &len, make_plural_suffix!(&len))?;
            for (index, item) in $list.iter().enumerate() {
                if index > 0 {
                    if index >= LIST_MAP_OBJECT_MAX_DISPLAY_ITEMS { break; }
                    write!($formatter, ", ")?;
                }
                write!($formatter, "{}", &item)?;
            }
            match item_count.checked_sub(LIST_MAP_OBJECT_MAX_DISPLAY_ITEMS) {
                Some(more) if more > 0 => write!($formatter, ",... {} more]", &more),
                _ => write!($formatter, "]"),
            }
        },
        Err(err) => write!($formatter, "List({} item{}, unknown size ({}))", &item_count, make_plural_suffix!(&item_count), &err),
    }
}};}

/// # Displays a map in a formatter
///
/// If the items are too much, just displays a part of them.
///
/// Result: `Result<(), fmt::Error>`
macro_rules! display_map { ($formatter: ident, $value: ident, $map: ident) => {{
    let item_count = $map.len();

    match $value.len() {
        Ok(len) => {
            write!($formatter, "Map({} item{}, {} byte{}: {{", &item_count, make_plural_suffix!(&item_count), &len, make_plural_suffix!(&len))?;
            for (index, (key, value)) in $map.iter().enumerate() {
                if index > 0 {
                    if index >= LIST_MAP_OBJECT_MAX_DISPLAY_ITEMS { break; }
                    write!($formatter, ", ")?;
                }
                write!($formatter, "{}: {}", &key, &value)?;
            }
            match item_count.checked_sub(LIST_MAP_OBJECT_MAX_DISPLAY_ITEMS) {
                Some(more) if more > 0 => write!($formatter, ",... {} more}}", &more),
                _ => write!($formatter, "}}"),
            }
        },
        Err(err) => write!($formatter, "Map({} item{}, unknown size ({}))", &item_count, make_plural_suffix!(&item_count), &err),
    }
}};}

/// # Displays an object in a formatter
///
/// If the items are too much, just displays a part of them.
///
/// Result: `Result<(), fmt::Error>`
macro_rules! display_object { ($formatter: ident, $value: ident, $object: ident) => {{
    let item_count = $object.len();

    match $value.len() {
        Ok(len) => {
            write!(
                $formatter, "Object({} item{}, {} byte{}: {{", &item_count, make_plural_suffix!(&item_count), &len, make_plural_suffix!(&len)
            )?;
            for (index, (key, value)) in $object.iter().enumerate() {
                if index > 0 {
                    if index >= LIST_MAP_OBJECT_MAX_DISPLAY_ITEMS { break; }
                    write!($formatter, ", ")?;
                }
                write!($formatter, "{:?}: {}", &key, &value)?;
            }
            match item_count.checked_sub(LIST_MAP_OBJECT_MAX_DISPLAY_ITEMS) {
                Some(more) if more > 0 => write!($formatter, ",... {} more}}", &more),
                _ => write!($formatter, "}}"),
            }
        },
        Err(err) => write!($formatter, "Object({} item{}, unknown size ({}))", &item_count, make_plural_suffix!(&item_count), &err),
    }
}};}

impl fmt::Display for Value {

    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match *self {
            Value::Null => write!(formatter, "Null"),
            Value::True => write!(formatter, "True"),
            Value::False => write!(formatter, "False"),
            Value::U8(ref u) => write!(formatter, "U8({})", &u),
            Value::I8(ref i) => write!(formatter, "I8({})", &i),
            Value::U16(ref u) => write!(formatter, "U16({})", &u),
            Value::I16(ref i) => write!(formatter, "I16({})", &i),
            Value::U32(ref u) => write!(formatter, "U32({})", &u),
            Value::I32(ref i) => write!(formatter, "I32({})", &i),
            Value::Float(ref f) => write!(formatter, "Float({})", &f),
            Value::U64(ref u) => write!(formatter, "U64({})", &u),
            Value::I64(ref i) => write!(formatter, "I64({})", &i),
            Value::Double(ref d) => write!(formatter, "Double({})", &d),
            Value::Text(ref s) => display_str!(formatter, "Text(", s, ')'),
            Value::DateTime(ref dt) => display_str!(formatter, "DateTime(", dt, ')'),
            Value::Date(ref d) => display_str!(formatter, "Date(", d, ')'),
            Value::Time(ref t) => display_str!(formatter, "Time(", t, ')'),
            Value::DecimalStr(ref ds) => display_str!(formatter, "DecimalStr(", ds, ')'),
            Value::Blob(ref blob) => {
                let len = blob.len();
                write!(formatter, "Blob({} byte{})", &len, make_plural_suffix!(&len))
            },
            Value::List(ref list) => display_list!(formatter, self, list),
            Value::Map(ref map) => display_map!(formatter, self, map),
            Value::Object(ref object) => display_object!(formatter, self, object),
        }
    }

}

impl fmt::Debug for Value {

    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(formatter, "\"")?;
        fmt::Display::fmt(self, formatter)?;
        write!(formatter, "\"")
    }

}

impl AsRef<Value> for Value {

    fn as_ref(&self) -> &Self {
        self
    }

}

impl From<()> for Value {

    /// # Converts input to a [`Null`]
    ///
    /// [`Null`]: enum.Value.html#variant.Null
    fn from(_: ()) -> Self {
        Value::Null
    }

}

impl From<bool> for Value {

    /// # Converts input to either [`True`] or [`False`]
    ///
    /// [`True`]: enum.Value.html#variant.True
    /// [`False`]: enum.Value.html#variant.False
    fn from(b: bool) -> Self {
        match b {
            true => Value::True,
            false => Value::False,
        }
    }

}

impl From<u8> for Value {

    /// # Converts input to a [`U8`]
    ///
    /// [`U8`]: enum.Value.html#variant.U8
    fn from(u: u8) -> Self {
        Value::U8(u)
    }

}

impl From<i8> for Value {

    /// # Converts input to an [`I8`]
    ///
    /// [`I8`]: enum.Value.html#variant.I8
    fn from(i: i8) -> Self {
        Value::I8(i)
    }

}

impl From<u16> for Value {

    /// # Converts input to a [`U16`]
    ///
    /// [`U16`]: enum.Value.html#variant.U16
    fn from(u: u16) -> Self {
        Value::U16(u)
    }

}

impl From<i16> for Value {

    /// # Converts input to an [`I16`]
    ///
    /// [`I16`]: enum.Value.html#variant.I16
    fn from(i: i16) -> Self {
        Value::I16(i)
    }

}

impl From<u32> for Value {

    /// # Converts input to a [`U32`]
    ///
    /// [`U32`]: enum.Value.html#variant.U32
    fn from(u: u32) -> Self {
        Value::U32(u)
    }

}

impl From<i32> for Value {

    /// # Converts input to an [`I32`]
    ///
    /// [`I32`]: enum.Value.html#variant.I32
    fn from(i: i32) -> Self {
        Value::I32(i)
    }

}

impl From<f32> for Value {

    /// # Converts input to a [`Float`]
    ///
    /// [`Float`]: enum.Value.html#variant.Float
    fn from(f: f32) -> Self {
        Value::Float(f)
    }

}

impl From<u64> for Value {

    /// # Converts input to a [`U64`]
    ///
    /// [`U64`]: enum.Value.html#variant.U64
    fn from(u: u64) -> Self {
        Value::U64(u)
    }

}

impl From<i64> for Value {

    /// # Converts input to an [`I64`]
    ///
    /// [`I64`]: enum.Value.html#variant.I64
    fn from(i: i64) -> Self {
        Value::I64(i)
    }

}

impl From<f64> for Value {

    /// # Converts input to a [`Double`]
    ///
    /// [`Double`]: enum.Value.html#variant.Double
    fn from(f: f64) -> Self {
        Value::Double(f)
    }

}

impl From<String> for Value {

    /// # Converts input to a [`Text`]
    ///
    /// [`Text`]: enum.Value.html#variant.Text
    fn from(s: String) -> Self {
        Value::Text(s)
    }

}

impl<'a> From<&'a str> for Value {

    /// # Converts input to a [`Text`]
    ///
    /// [`Text`]: enum.Value.html#variant.Text
    fn from(s: &'a str) -> Self {
        // Note that some variants also accept a String, so forward this call to implementation of `From<String> for Value`, let it decide.
        Self::from(s.to_owned())
    }

}

impl From<Vec<u8>> for Value {

    /// # Converts input to a [`Blob`]
    ///
    /// [`Blob`]: enum.Value.html#variant.Blob
    fn from(v: Vec<u8>) -> Self {
        Value::Blob(v)
    }

}

impl<'a> From<&'a Vec<u8>> for Value {

    /// # Converts input to a [`Blob`]
    ///
    /// [`Blob`]: enum.Value.html#variant.Blob
    fn from(v: &'a Vec<u8>) -> Self {
        Self::from(v.to_owned())
    }

}

impl<'a> From<&'a [u8]> for Value {

    /// # Converts input to a [`Blob`]
    ///
    /// [`Blob`]: enum.Value.html#variant.Blob
    fn from(v: &'a [u8]) -> Self {
        Self::from(v.to_owned())
    }

}

impl From<Vec<Value>> for Value {

    /// # Converts input to a [`List`]
    ///
    /// [`List`]: enum.Value.html#variant.List
    fn from(list: Vec<Value>) -> Self {
        Value::List(list)
    }

}

impl<'a> From<&'a Vec<Value>> for Value {

    /// # Converts input to a [`List`]
    ///
    /// [`List`]: enum.Value.html#variant.List
    fn from(list: &'a Vec<Value>) -> Self {
        Self::from(list.to_owned())
    }

}

impl From<BTreeMap<i32, Value>> for Value {

    /// # Converts input to a [`Map`]
    ///
    /// [`Map`]: enum.Value.html#variant.Map
    fn from(map: BTreeMap<i32, Value>) -> Self {
        Value::Map(map)
    }

}

impl<'a> From<&'a BTreeMap<i32, Value>> for Value {

    /// # Converts input to a [`Map`]
    ///
    /// [`Map`]: enum.Value.html#variant.Map
    fn from(map: &'a BTreeMap<i32, Value>) -> Self {
        Self::from(map.to_owned())
    }

}

impl From<HashMap<String, Value>> for Value {

    /// # Converts input to an [`Object`]
    ///
    /// [`Object`]: enum.Value.html#variant.Object
    fn from(object: HashMap<String, Value>) -> Self {
        Value::Object(object)
    }

}

impl<'a> From<&'a HashMap<String, Value>> for Value {

    /// # Converts input to an [`Object`]
    ///
    /// [`Object`]: enum.Value.html#variant.Object
    fn from(object: &'a HashMap<String, Value>) -> Self {
        Self::from(object.to_owned())
    }

}

/// # Converts a value to its underlying byte slice
///
/// ## Notes
///
/// - This macro is dangerous: <https://doc.rust-lang.org/std/mem/fn.transmute.html>
/// - Again, this macro is dangerous: <https://doc.rust-lang.org/nomicon/transmutes.html>
/// - TODO: when `::to_bytes()` is stable, switch to it.
macro_rules! as_bytes { ($ty: ty, $v: expr) => {{
    unsafe { mem::transmute::<$ty, [u8; mem::size_of::<$ty>()]>($v) }
}};}

#[test]
fn test_macro_as_bytes() {
    assert!(as_bytes!(u8, 1) == [0x01]);
    assert!(as_bytes!(i8, -0x01) == [0xFF]);
    assert!(as_bytes!(i8, -99) == [0x9D]);
    assert!(as_bytes!(u8, 100) == [0x64]);
    assert!(as_bytes!(i8, -0x64) == [0x9C]);

    assert_eq!(as_bytes!(u16, 0x_03E8_u16.to_be()), [0x03, 0xE8]);
    assert_eq!(as_bytes!(u16, 0x_270F_u16.to_be()), [0x27, 0x0F]);

    assert_eq!(as_bytes!(i16, (-9999 as i16).to_be()), [0xD8, 0xF1]);
    assert_eq!(as_bytes!(i16, (-2000 as i16).to_be()), [0xF8, 0x30]);
    assert_eq!(as_bytes!(i16, (-1234 as i16).to_be()), [0xFB, 0x2E]);

    assert_eq!(as_bytes!(u32, 0x_075B_CD15_u32.to_be()), [0x07, 0x5B, 0xCD, 0x15]);
    assert_eq!(as_bytes!(u32, 0x_3ADE_68B1_u32.to_be()), [0x3A, 0xDE, 0x68, 0xB1]);
    assert_eq!(as_bytes!(u32, 0x_AABB_FFEE_u32.to_be()), [0xAA, 0xBB, 0xFF, 0xEE]);

    assert_eq!(as_bytes!(u64, 0x_8000_0000_0000_0000_u64.to_be()), [0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
    assert_eq!(as_bytes!(u64, 0x_FFFF_FFFF_0000_0000_u64.to_be()), [0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00]);

    assert_eq!(as_bytes!(i64, (-3372036854775808 as i64).to_be()), [0xFF, 0xF4, 0x05, 0x26, 0x7D, 0x1A, 0x00, 0x00]);

    assert_eq!(
        as_bytes!(u128, 0x_AAFF_0000_CCDD_8899_1234_8678_BCCB_0000_u128.to_be()),
        [0xAA, 0xFF, 0x00, 0x00, 0xCC, 0xDD, 0x88, 0x99, 0x12, 0x34, 0x86, 0x78, 0xBC, 0xCB, 0x00, 0x00]
    );
}

/// # Converts an integer value to big-endian order and writes it into the buffer
///
/// Returns: number of bytes written, as `io::Result<u32>`.
macro_rules! write_int_be { ($ty: ty, $v: expr, $buf: ident) => {{
    let bytes = as_bytes!($ty, $v.to_be());
    match $buf.write(&bytes) {
        Ok(count) => match count == bytes.len() {
            true => Ok(count as u32),
            false => Err(Error::new(
                ErrorKind::Other, format!("value::write_int_be!() -> expected to write {} byte(s); result: {}", bytes.len(), count)
            )),
        },
        Err(err) => Err(err),
    }
}};}

/// # Reads an integer value in big-endian format from std::io::Read
///
/// Result: `io::Result<$ty>`.
macro_rules! read_int_be { ($ty: ty, $source: ident) => {{
    let mut buf = [0_u8; mem::size_of::<$ty>()];
    match $source.read_exact(&mut buf) {
        Ok(()) => Ok(<$ty>::from_be(unsafe { mem::transmute(buf) })),
        Err(err) => Err(err),
    }
}};}

/// # Writes size (u32) into the buffer
///
/// Result: number of bytes written - `io::Result<u32>`.
macro_rules! write_size { ($size: expr, $buf: ident) => {{
    let size = $size;
    match cmp_integers!(size, ::std::i8::MAX) {
        Ordering::Greater => write_int_be!(u32, size | SIZE_MASK, $buf),
        _ => write_int_be!(u8, size as u8, $buf),
    }
}};}

/// # Reads size from std::io::Read
///
/// Result: `io::Result<u32>`.
macro_rules! read_size { ($source: ident) => {{
    let first_byte = read_int_be!(u8, $source)?;
    match first_byte & 0b_1000_0000 {
        0b_1000_0000 => {
            let mut buf = [first_byte, 0, 0, 0];
            match $source.read_exact(&mut buf[1..]) {
                Ok(()) => {
                    let result = u32::from_be(unsafe { mem::transmute(buf) }) & !(SIZE_MASK);
                    match cmp_integers!(result, MAX_DATA_SIZE) {
                        Ordering::Greater => Err(Error::new(ErrorKind::InvalidData, format!("value::read_size!() -> too large: {}", &result))),
                        _ => Ok(result),
                    }
                },
                Err(err) => Err(err),
            }
        },
        _ => Ok(first_byte as u32),
    }
}};}

/// # Calculates sum of first value (`u32`) with integer(s)
///
/// Result: `io::Result<u32>`.
///
/// If result > [`MAX_DATA_SIZE`], an error is returned.
///
/// [`MAX_DATA_SIZE`]: constant.MAX_DATA_SIZE.html
macro_rules! sum {
    ($a: expr, $($b: expr),+) => {{
        // Do NOT nest multiple calls to cmp_integers(...); or the compiler will hang up!!!
        let mut result: io::Result<u32> = Ok($a);
        $(
            match result {
                Ok(current) => result = {
                    let b = $b;
                    match cmp_integers!(b, MAX_DATA_SIZE) {
                        Ordering::Greater => Err(Error::new(
                            ErrorKind::InvalidData,
                            format!("sum!() -> too large for: {} + {} (max allowed: {})", &current, &b, MAX_DATA_SIZE)
                        )),
                        _ => match current.checked_add(b as u32) {
                            Some(new) => match cmp_integers!(new, MAX_DATA_SIZE) {
                                Ordering::Greater => Err(Error::new(
                                    ErrorKind::InvalidData,
                                    format!("sum!() -> too large for: {} + {} (max allowed: {})", &current, &b, MAX_DATA_SIZE)
                                )),
                                _ => Ok(new),
                            },
                            None => Err(Error::new(ErrorKind::InvalidData, format!("sum!() -> can't add {} into {}", &b, &current))),
                        },
                    }
                },
                Err(_) => (),
            };
        )+

        result
    }};
}

/// # Makes new vector with capacity
///
/// Returns: `io::Result<Vec<_>>`
macro_rules! new_vec_with_capacity { ($capacity: expr) => {{
    let capacity = $capacity;
    match cmp_integers!(capacity, MAX_DATA_SIZE) {
        Ordering::Greater => Err(Error::new(
            ErrorKind::WriteZero,
            format!(
                "value::new_vec_with_capacity!() -> cannot allocate a vector with capacity: {} (max allowed: {})",
                &capacity, MAX_DATA_SIZE
            )
        )),
        _ => match cmp_integers!(capacity, ::std::usize::MAX) {
            Ordering::Greater => Err(Error::new(
                ErrorKind::WriteZero,
                format!(
                    "value::new_vec_with_capacity!() -> cannot allocate a vector with capacity: {} (max allowed: {})",
                    &capacity, ::std::usize::MAX
                )
            )),
            _ => Ok(Vec::with_capacity(capacity as usize)),
        },
    }
}};}

/// # Reads data into new vector
///
/// Returns: `io::Result<Vec<_>>`
macro_rules! read_into_new_vec { ($len: expr, $source: ident) => {{
    let len = $len;
    let mut result = new_vec_with_capacity!(len)?;

    // Notes:
    //
    // - `len` was verified via above call to `new_vec_with_capacity!()`, that it must be <= `MAX_DATA_SIZE`
    // - `MAX_DATA_SIZE` should be **tested** to be < `std::u64::MAX`
    match $source.take(len as u64).read_to_end(&mut result) {
        Ok(read) => match read == result.len() {
            true => Ok(result),
            false => Err(Error::new(
                ErrorKind::WriteZero, format!("value::read_into_new_vec!() -> expected to read {} bytes, but: {}", &len, &read)
            )),
        },
        Err(err) => Err(Error::new(ErrorKind::WriteZero, format!("value::read_into_new_vec!() -> failed to read {} bytes: {}", &len, &err))),
    }
}};}

/// # Reads a string from source
///
/// Returns: `io::Result<String>`
macro_rules! read_str { ($source: ident) => {{
    // Note that null terminator does NOT count
    let buf = read_into_new_vec!(read_size!($source)?, $source)?;
    match read_int_be!(u8, $source)? {
        0 => String::from_utf8(buf).map_err(|err|
            Error::new(ErrorKind::InvalidData, format!("value::read_str!() -> failed to decode UTF-8: {}", &err))
        ),
        other => Err(Error::new(
            ErrorKind::InvalidData, format!("value::read_str!() -> expected to read a null terminator ('\\0'), got: {}", &other)
        )),
    }
}};}

/// # Reads a list from source
///
/// Returns: `io::Result<Value>`
macro_rules! read_list { ($source: ident) => {{
    let size = read_size!($source)?;
    let item_count = read_size!($source)?;

    let mut result = vec![];
    let mut read: u32 = 0;
    for _ in 0..item_count {
        let value = Value::decode($source)?;
        read = match read.checked_add(value.len()?) {
            Some(v) => match cmp_integers!(size, v) {
                Ordering::Greater => v,
                _ => return Err(Error::new(
                    ErrorKind::InvalidData, format!("value::read_list!() -> expected to read less than {} bytes, got: {}", &size, &v)
                )),
            },
            None => return Err(Error::new(
                ErrorKind::InvalidData,
                format!("value::read_list!() -> invalid list size -> expected: {}, current: {}, new item: {:?}", &size, &read, &value)
            )),
        };
        result.push(value);
    }

    Ok(Value::List(result))
}};}

/// # Reads a map from source
///
/// Returns: `io::Result<Value>`
macro_rules! read_map { ($source: ident) => {{
    let size = read_size!($source)?;
    let item_count = read_size!($source)?;

    let mut result = BTreeMap::new();
    let mut read: u32 = 0;
    for _ in 0..item_count {
        let key = read_int_be!(i32, $source)?;
        let value = Value::decode($source)?;
        read = match read.checked_add(value.len()?) {
            Some(v) => match cmp_integers!(size, v) {
                Ordering::Greater => v,
                _ => return Err(Error::new(
                    ErrorKind::InvalidData, format!("value::read_map!() -> expected to read less than {} bytes, got: {}", &size, &v)
                )),
            },
            None => return Err(Error::new(
                ErrorKind::InvalidData,
                format!(
                    "value::read_map!() -> invalid map size -> expected: {}, current: {}, new item: {} -> {:?}",
                    &size, &read, &key, &value,
                )
            )),
        };
        result.insert(key, value);
    }

    Ok(Value::Map(result))
}};}

/// # Reads an object from source
///
/// Returns: `io::Result<Value>`
macro_rules! read_object { ($source: ident) => {{
    let size = read_size!($source)?;
    let item_count = read_size!($source)?;

    let mut result = HashMap::new();
    let mut read: u32 = 0;
    for _ in 0..item_count {
        // Read key (note that there's NO null terminator)
        let key_len = read_size!($source)?;
        match cmp_integers!(key_len, OBJECT_KEY_MAX_LEN) {
            Ordering::Greater => return Err(Error::new(
                ErrorKind::InvalidData,
                format!("value::read_object!() -> key length is limited to {} bytes, got: {}", OBJECT_KEY_MAX_LEN, key_len)
            )),
            _ => read = match read.checked_add(key_len) {
                Some(v) => match cmp_integers!(size, v) {
                    Ordering::Greater => v,
                    _ => return Err(Error::new(
                        ErrorKind::InvalidData, format!("value::read_object!() -> expected to read less than {} bytes, got: {}",
                        &size, &v)
                    )),
                },
                None => return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!(
                        "value::read_object!() -> invalid object size -> expected: {}, current: {}, new key length: {}",
                        &size, &read, &key_len,
                    )
                )),
            },
        };
        let key = String::from_utf8(read_into_new_vec!(key_len, $source)?).map_err(|err|
            Error::new(ErrorKind::InvalidData, format!("value::read_object!() -> failed to decode UTF-8: {}", &err))
        )?;

        // Read value
        let value = Value::decode($source)?;
        read = match read.checked_add(value.len()?) {
            Some(v) => match cmp_integers!(size, v) {
                Ordering::Greater => v,
                _ => return Err(Error::new(
                    ErrorKind::InvalidData, format!("value::read_object!() -> expected to read less than {} bytes, got: {}", &size, &v)
                )),
            },
            None => return Err(Error::new(
                ErrorKind::InvalidData,
                format!("value::read_object!() -> invalid object size -> expected: {}, current: {}, new value: {:?}",
                &size, &read, &value)
            )),
        };
        result.insert(key, value);
    }

    Ok(Value::Object(result))
}};}

impl Value {

    /// # Calculates length of this value
    pub fn len(&self) -> io::Result<u32> {
        match *self {
            Value::Null => Ok(1),
            Value::True => Ok(1),
            Value::False => Ok(1),
            Value::U8(_) => Ok(2),
            Value::I8(_) => Ok(2),
            Value::U16(_) => Ok(3),
            Value::I16(_) => Ok(3),
            Value::U32(_) => Ok(5),
            Value::I32(_) => Ok(5),
            Value::Float(_) => Ok(5),
            Value::U64(_) => Ok(9),
            Value::I64(_) => Ok(9),
            Value::Double(_) => Ok(9),
            // 1 byte for type, 1 byte for null terminator
            Value::Text(ref t) => sum!(bytes_for_len(t.len())?, 2, t.len()),
            // 1 byte for type, 1 byte for null terminator
            Value::DateTime(ref dt) => sum!(bytes_for_len(dt.len())?, 2, dt.len()),
            // 1 byte for type, 1 byte for null terminator
            Value::Date(ref d) => sum!(bytes_for_len(d.len())?, 2, d.len()),
            // 1 byte for type, 1 byte for null terminator
            Value::Time(ref t) => sum!(bytes_for_len(t.len())?, 2, t.len()),
            // 1 byte for type, 1 byte for null terminator
            Value::DecimalStr(ref ds) => sum!(bytes_for_len(ds.len())?, 2, ds.len()),
            // 1 byte for type
            Value::Blob(ref bytes) => sum!(bytes_for_len(bytes.len())?, 1, bytes.len()),
            Value::List(ref list) => list_len(list),
            Value::Map(ref map) => map_len(map),
            Value::Object(ref object) => object_len(object),
        }
    }

    /// # Encodes this value into a buffer
    ///
    /// Returns the number of bytes written.
    pub fn encode(&self, buf: &mut Write) -> io::Result<u32> {
        let expected_result = self.len()?;

        let result = match *self {
            Value::Null => write_int_be!(u8, NULL, buf)?,
            Value::True => write_int_be!(u8, TRUE, buf)?,
            Value::False => write_int_be!(u8, FALSE, buf)?,
            Value::U8(u) => sum!(write_int_be!(u8, U8, buf)?, write_int_be!(u8, u, buf)?)?,
            Value::I8(i) => sum!(write_int_be!(u8, I8, buf)?, write_int_be!(i8, i, buf)?)?,
            Value::U16(u) => sum!(write_int_be!(u8, U16, buf)?, write_int_be!(u16, u, buf)?)?,
            Value::I16(i) => sum!(write_int_be!(u8, I16, buf)?, write_int_be!(i16, i, buf)?)?,
            Value::U32(u) => sum!(write_int_be!(u8, U32, buf)?, write_int_be!(u32, u, buf)?)?,
            Value::I32(i) => sum!(write_int_be!(u8, I32, buf)?, write_int_be!(i32, i, buf)?)?,
            Value::Float(f) => sum!(write_int_be!(u8, FLOAT, buf)?, write_int_be!(u32, f.to_bits(), buf)?)?,
            Value::U64(u) => sum!(write_int_be!(u8, U64, buf)?, write_int_be!(u64, u, buf)?)?,
            Value::I64(i) => sum!(write_int_be!(u8, I64, buf)?, write_int_be!(i64, i, buf)?)?,
            Value::Double(f) => sum!(write_int_be!(u8, DOUBLE, buf)?, write_int_be!(u64, f.to_bits(), buf)?)?,
            Value::Text(ref t) => write_str(TEXT, t.as_str(), buf)?,
            Value::DateTime(ref dt) => write_str(DATE_TIME, dt.as_str(), buf)?,
            Value::Date(ref d) => write_str(DATE, d.as_str(), buf)?,
            Value::Time(ref t) => write_str(TIME, t.as_str(), buf)?,
            Value::DecimalStr(ref ds) => write_str(DECIMAL_STR, ds.as_str(), buf)?,
            Value::Blob(ref bytes) => write_blob(bytes.as_slice(), buf)?,
            Value::List(ref list) => write_list(expected_result, list, buf)?,
            Value::Map(ref map) => write_map(expected_result, map, buf)?,
            Value::Object(ref object) => write_object(expected_result, object, buf)?,
        };

        match result == expected_result {
            true => Ok(result),
            false => Err(Error::new(
                ErrorKind::Other, format!("Value::encode() -> expected to write {} bytes, result: {}", expected_result, result)
            )),
        }
    }

    /// # Decodes a value from source
    pub fn decode(source: &mut Read) -> io::Result<Self> {
        decode_value(None, source)
    }

}

/// # Decodes a value from source
///
/// If `filter` is provided, the function expects that next value from source is one of them, and returns an error if not.
///
/// If `filter` is `None`, the function decodes any value from source.
fn decode_value(filter: Option<&[u8]>, source: &mut Read) -> io::Result<Value> {
    let source_value = read_int_be!(u8, source)?;
    if let Some(ref expected_values) = filter {
        if expected_values.contains(&source_value) == false {
            return Err(Error::new(
                ErrorKind::InvalidData, format!("value::decode_value() -> expected one of: {:?}, got: {}", &expected_values, &source_value)
            ));
        }
    }

    match source_value {
        self::NULL => Ok(Value::Null),
        self::TRUE => Ok(Value::True),
        self::FALSE => Ok(Value::False),
        self::U8 => Ok(Value::U8(read_int_be!(u8, source)?)),
        self::I8 => Ok(Value::I8(read_int_be!(i8, source)?)),
        self::U16 => Ok(Value::U16(read_int_be!(u16, source)?)),
        self::I16 => Ok(Value::I16(read_int_be!(i16, source)?)),
        self::U32 => Ok(Value::U32(read_int_be!(u32, source)?)),
        self::I32 => Ok(Value::I32(read_int_be!(i32, source)?)),
        self::FLOAT => Ok(Value::Float(f32::from_bits(read_int_be!(u32, source)?))),
        self::U64 => Ok(Value::U64(read_int_be!(u64, source)?)),
        self::I64 => Ok(Value::I64(read_int_be!(i64, source)?)),
        self::DOUBLE => Ok(Value::Double(f64::from_bits(read_int_be!(u64, source)?))),
        self::TEXT => Ok(Value::Text(read_str!(source)?)),
        self::DATE_TIME => Ok(Value::DateTime(read_str!(source)?)),
        self::DATE => Ok(Value::Date(read_str!(source)?)),
        self::TIME => Ok(Value::Time(read_str!(source)?)),
        self::DECIMAL_STR => Ok(Value::DecimalStr(read_str!(source)?)),
        self::BLOB => Ok(Value::Blob(read_into_new_vec!(read_size!(source)?, source)?)),
        self::LIST => read_list!(source),
        self::MAP => read_map!(source),
        self::OBJECT => read_object!(source),
        _ => Err(Error::new(
            ErrorKind::InvalidData, format!("Value::decode() -> data type is either invalid or not supported: {}", &source_value)
        )),
    }
}

/// # Calculates bytes needed for a length
fn bytes_for_len(len: usize) -> io::Result<u32> {
    match cmp_integers!(len, ::std::i8::MAX) {
        Ordering::Greater => match cmp_integers!(len, MAX_DATA_SIZE) {
            Ordering::Greater => Err(Error::new(ErrorKind::InvalidData, format!("value::bytes_for_len() -> too large: {} bytes", len))),
            _ => Ok(4),
        },
        _ => Ok(1),
    }
}

/// # Calculates list length
fn list_len(list: &Vec<Value>) -> io::Result<u32> {
    // Type + count
    let mut result: u32 = sum!(bytes_for_len(list.len())?, 1)?;
    // Items
    for v in list {
        result = sum!(result, v.len()?)?;
    }
    // The len value itself:
    // First, assume that it needs just 1 byte
    result = sum!(result, 1)?;
    match cmp_integers!(result, ::std::i8::MAX) {
        // Now we need 3 more bytes
        Ordering::Greater => result = sum!(result, 3)?,
        _ => (),
    };
    match result <= MAX_DATA_SIZE {
        true => Ok(result),
        false => Err(Error::new(ErrorKind::InvalidData, format!("value::list_len() -> data too large: {} bytes", result))),
    }
}

/// # Calculates map length
fn map_len(map: &BTreeMap<i32, Value>) -> io::Result<u32> {
    // Type + count
    let mut result = sum!(bytes_for_len(map.len())?, 1)?;
    // Items
    for v in map.values() {
        result = sum!(result, mem::size_of::<i32>(), v.len()?)?;
    }
    // The len value itself:
    // First, assume that it needs just 1 byte
    result = sum!(result, 1)?;
    match cmp_integers!(result, ::std::i8::MAX) {
        // Now we need 3 more bytes
        Ordering::Greater => result = sum!(result, 3)?,
        _ => (),
    };
    match result <= MAX_DATA_SIZE {
        true => Ok(result),
        false => Err(Error::new(ErrorKind::InvalidData, format!("value::map_len() -> data too large: {} bytes", result))),
    }
}

/// # Calculates object length
fn object_len(object: &HashMap<String, Value>) -> io::Result<u32> {
    // Type + count
    let mut result = sum!(bytes_for_len(object.len())?, 1)?;
    // Items
    for (key, value) in object {
        // Key has NO null terminator
        let key_len = key.len();
        if key_len > OBJECT_KEY_MAX_LEN {
            return Err(Error::new(
                ErrorKind::InvalidData,
                format!("value::object_len() -> key size is limited to {} bytes; got: {}", OBJECT_KEY_MAX_LEN, &key_len)
            ));
        }
        result = sum!(result, key_len, value.len()?, 1)?;
    }
    // The len value itself:
    // First, assume that it needs just 1 byte
    result = sum!(result, 1)?;
    match cmp_integers!(result, ::std::i8::MAX) {
        // Now we need 3 more bytes
        Ordering::Greater => result = sum!(result, 3)?,
        _ => (),
    };
    match result <= MAX_DATA_SIZE {
        true => Ok(result),
        false => Err(Error::new(ErrorKind::InvalidData, format!("len() -> data too large: {} bytes", result))),
    }
}

/// # Writes a string into the buffer
fn write_str(ty: u8, s: &str, buf: &mut Write) -> io::Result<u32> {
    let bytes = s.as_bytes();
    let str_len = {
        let tmp = bytes.len();
        match cmp_integers!(tmp, MAX_DATA_SIZE) {
            Ordering::Greater => return Err(Error::new(
                ErrorKind::Other, format!("value::write_str() -> string too large ({} bytes)", &tmp)
            )),
            _ => tmp as u32,
        }
    };

    let total_size = sum!(
        str_len,
        // 1 for type, 1 for null terminator
        2 + if cmp_integers!(str_len, ::std::i8::MAX) == Ordering::Greater { 4 } else { 1 }
    )?;

    // Type
    match buf.write(&[ty])? {
        1 => (),
        other => return Err(Error::new(ErrorKind::Other, format!("value::write_str() -> expected to write 1 byte; result: {}", &other))),
    };

    // Size
    // Note that null terminator does NOT count
    write_size!(str_len, buf)?;

    // Data
    let written = buf.write(bytes)?;
    match cmp_integers!(written, str_len) {
        Ordering::Equal => (),
        _ => return Err(Error::new(
            ErrorKind::Other, format!("value::write_str() -> expected to write {} byte(s); result: {}", str_len, written)
        )),
    };

    // Null terminator
    match buf.write(&[0])? {
        1 => (),
        other => return Err(Error::new(ErrorKind::Other, format!("value::write_str() -> expected to write 1 byte; result: {}", &other))),
    };

    Ok(total_size)
}

/// # Writes blob into the buffer
fn write_blob(bytes: &[u8], buf: &mut Write) -> io::Result<u32> {
    let len = {
        let tmp = bytes.len();
        match cmp_integers!(tmp, MAX_DATA_SIZE) {
            Ordering::Greater => return Err(Error::new(ErrorKind::Other, format!("value::write_blob() -> too large: {} byte(s)", tmp))),
            _ => tmp as u32,
        }
    };

    // Type
    let mut bytes_written = match buf.write(&[BLOB])? {
        1 => 1 as u32,
        other => return Err(Error::new(ErrorKind::Other, format!("value::write_blob() -> expected to write 1 byte; result: {}", &other))),
    };

    // Size
    bytes_written = sum!(write_size!(len, buf)?, bytes_written)?;

    // Data
    let written = buf.write(bytes)?;
    match cmp_integers!(written, len) {
        Ordering::Equal => (),
        _ => return Err(Error::new(
            ErrorKind::Other, format!("value::write_blob() -> expected to write {} byte(s); result: {}", &len, &written)
        )),
    };
    bytes_written = sum!(bytes_written, written)?;

    Ok(bytes_written)
}

/// # Writes a list into the buffer
fn write_list(size: u32, list: &Vec<Value>, buf: &mut Write) -> io::Result<u32> {
    let mut result = sum!(
        // Type
        write_int_be!(u8, LIST, buf)?,
        // Size
        write_size!(size, buf)?,
        // Count
        // We don't have to verify this value. Since at the beginning of Value::encode(), we already called ::len(), which verified the whole
        // container's size.
        write_size!(list.len() as u32, buf)?
    )?;

    // Items
    for v in list {
        result = sum!(result, v.encode(buf)?)?;
    }

    Ok(result)
}

/// # Writes a map into the buffer
fn write_map(size: u32, map: &BTreeMap<i32, Value>, buf: &mut Write) -> io::Result<u32> {
    let mut result = sum!(
        // Type
        write_int_be!(u8, MAP, buf)?,
        // Size
        write_size!(size, buf)?,
        // Count
        // We don't have to verify this value. Since at the beginning of Value::encode(), we already called ::len(), which verified the whole
        // container's size.
        write_size!(map.len() as u32, buf)?
    )?;

    // Items
    for (key, value) in map {
        result = sum!(result, write_int_be!(i32, key, buf)?, value.encode(buf)?)?;
    }

    Ok(result)
}

/// # Writes an object into the buffer
///
/// [`len()`]: enum.Value.html#method.len
fn write_object(size: u32, object: &HashMap<String, Value>, buf: &mut Write) -> io::Result<u32> {
    let mut result = sum!(
        // Type
        write_int_be!(u8, OBJECT, buf)?,
        // Size
        write_size!(size, buf)?,
        // Count
        // We don't have to verify this value. Since at the beginning of Value::encode(), we already called ::len(), which verified the whole
        // container's size.
        write_size!(object.len() as u32, buf)?
    )?;

    // Items
    for (key, value) in object {
        let key_len = key.len();
        result = match key_len <= OBJECT_KEY_MAX_LEN {
            true => sum!(result, write_int_be!(u8, key_len as u8, buf)?)?,
            false => return Err(Error::new(
                ErrorKind::InvalidData,
                format!("value::write_object() -> key length is limited to {} bytes, got: {}", OBJECT_KEY_MAX_LEN, &key_len)
            )),
        };

        let written = buf.write(key.as_bytes())?;
        match cmp_integers!(written, key_len) {
            Ordering::Equal => result = sum!(result, written)?,
            _ => return Err(Error::new(
                ErrorKind::Other, format!("value::write_object() -> expected to write {} byte(s) of key; result: {}", &key_len, &written)
            )),
        }

        result = sum!(result, value.encode(buf)?)?;
    }

    Ok(result)
}

/// # Encoder
///
/// ---
///
/// Default implementors are copied from [`Write`]'s.
///
/// [`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
pub trait Encoder: Write + Sized {

    /// # Encodes a value
    ///
    /// Result: total bytes that have been written.
    fn encode(&mut self, value: impl AsRef<Value>) -> io::Result<u32> {
        value.as_ref().encode(self)
    }

    /// # Encodes a [`Null`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`Null`]: enum.Value.html#variant.Null
    fn encode_null(&mut self) -> io::Result<u32> {
        Value::Null.encode(self)
    }

    /// # Encodes a `bool` via [`True`] or [`False`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`True`]: enum.Value.html#variant.True
    /// [`False`]: enum.Value.html#variant.False
    fn encode_bool(&mut self, b: impl Into<bool>) -> io::Result<u32> {
        match b.into() {
            true => Value::True.encode(self),
            false => Value::False.encode(self),
        }
    }

    /// # Encodes a [`U8`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`U8`]: enum.Value.html#variant.U8
    fn encode_u8(&mut self, u: impl Into<u8>) -> io::Result<u32> {
        Value::U8(u.into()).encode(self)
    }

    /// # Encodes an [`I8`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`I8`]: enum.Value.html#variant.I8
    fn encode_i8(&mut self, i: impl Into<i8>) -> io::Result<u32> {
        Value::I8(i.into()).encode(self)
    }

    /// # Encodes a [`U16`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`U16`]: enum.Value.html#variant.U16
    fn encode_u16(&mut self, u: impl Into<u16>) -> io::Result<u32> {
        Value::U16(u.into()).encode(self)
    }

    /// # Encodes an [`I16`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`I16`]: enum.Value.html#variant.I16
    fn encode_i16(&mut self, i: impl Into<i16>) -> io::Result<u32> {
        Value::I16(i.into()).encode(self)
    }

    /// # Encodes a [`U32`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`U32`]: enum.Value.html#variant.U32
    fn encode_u32(&mut self, u: impl Into<u32>) -> io::Result<u32> {
        Value::U32(u.into()).encode(self)
    }

    /// # Encodes an [`I32`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`I32`]: enum.Value.html#variant.I32
    fn encode_i32(&mut self, i: impl Into<i32>) -> io::Result<u32> {
        Value::I32(i.into()).encode(self)
    }

    /// # Encodes a [`U64`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`U64`]: enum.Value.html#variant.U64
    fn encode_u64(&mut self, u: impl Into<u64>) -> io::Result<u32> {
        Value::U64(u.into()).encode(self)
    }

    /// # Encodes an [`I64`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`I64`]: enum.Value.html#variant.I64
    fn encode_i64(&mut self, i: impl Into<i64>) -> io::Result<u32> {
        Value::I64(i.into()).encode(self)
    }

    /// # Encodes a [`Float`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`Float`]: enum.Value.html#variant.Float
    fn encode_float(&mut self, f: impl Into<f32>) -> io::Result<u32> {
        Value::Float(f.into()).encode(self)
    }

    /// # Encodes a [`Double`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`Double`]: enum.Value.html#variant.Double
    fn encode_double(&mut self, f: impl Into<f64>) -> io::Result<u32> {
        Value::Double(f.into()).encode(self)
    }

    /// # Encodes a [`Text`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`Text`]: enum.Value.html#variant.Text
    fn encode_text(&mut self, s: impl Into<String>) -> io::Result<u32> {
        Value::Text(s.into()).encode(self)
    }

    /// # Encodes a [`DateTime`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`DateTime`]: enum.Value.html#variant.DateTime
    fn encode_date_time(&mut self, s: impl Into<String>) -> io::Result<u32> {
        Value::DateTime(s.into()).encode(self)
    }

    /// # Encodes a [`Date`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`Date`]: enum.Value.html#variant.Date
    fn encode_date(&mut self, s: impl Into<String>) -> io::Result<u32> {
        Value::Date(s.into()).encode(self)
    }

    /// # Encodes a [`Time`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`Time`]: enum.Value.html#variant.Time
    fn encode_time(&mut self, s: impl Into<String>) -> io::Result<u32> {
        Value::Time(s.into()).encode(self)
    }

    /// # Encodes a [`DecimalStr`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`DecimalStr`]: enum.Value.html#variant.DecimalStr
    fn encode_decimal_str(&mut self, s: impl Into<String>) -> io::Result<u32> {
        Value::DecimalStr(s.into()).encode(self)
    }

    /// # Encodes a [`Blob`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`Blob`]: enum.Value.html#variant.Blob
    fn encode_blob(&mut self, bytes: impl Into<Vec<u8>>) -> io::Result<u32> {
        Value::Blob(bytes.into()).encode(self)
    }

    /// # Encodes a [`List`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`List`]: enum.Value.html#variant.List
    fn encode_list(&mut self, list: impl Into<Vec<Value>>) -> io::Result<u32> {
        Value::List(list.into()).encode(self)
    }

    /// # Encodes a [`Map`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`Map`]: enum.Value.html#variant.Map
    fn encode_map(&mut self, map: impl Into<BTreeMap<i32, Value>>) -> io::Result<u32> {
        Value::Map(map.into()).encode(self)
    }

    /// # Encodes an [`Object`]
    ///
    /// Result: total bytes that have been written.
    ///
    /// [`Object`]: enum.Value.html#variant.Object
    fn encode_object(&mut self, object: impl Into<HashMap<String, Value>>) -> io::Result<u32> {
        Value::Object(object.into()).encode(self)
    }

}

impl Encoder for ::std::fs::File {}
impl<'a> Encoder for &'a ::std::fs::File {}
impl<W: Write> Encoder for ::std::io::BufWriter<W> {}
impl<'a> Encoder for ::std::io::Cursor<&'a mut [u8]> {}
impl<'a> Encoder for ::std::io::Cursor<&'a mut Vec<u8>> {}
impl Encoder for ::std::io::Cursor<Vec<u8>> {}
impl Encoder for ::std::io::Cursor<Box<[u8]>> {}
impl<W: Write + ?Sized> Encoder for Box<W> {}
impl<'a> Encoder for &'a mut [u8] {}
impl Encoder for Vec<u8> {}
impl Encoder for ::std::io::Sink {}
impl Encoder for ::std::io::Stdout {}
impl<'a> Encoder for ::std::io::StdoutLock<'a> {}
impl Encoder for ::std::io::Stderr {}
impl<'a> Encoder for ::std::io::StderrLock<'a> {}
impl Encoder for ::std::net::TcpStream {}
impl<'a> Encoder for &'a ::std::net::TcpStream {}
impl Encoder for ::std::process::ChildStdin {}
#[cfg(unix)]
impl Encoder for ::std::os::unix::net::UnixStream {}
#[cfg(unix)]
impl<'a> Encoder for &'a ::std::os::unix::net::UnixStream {}

/// # Decoder
///
/// ## Usage
///
/// ### Decoding any values
///
/// You can use [`::decode()`] and a `match` to filter values. This function will hand you the values after _finishing_ decoding process.
///
/// ### Decoding desired values
///
/// You can use `::decode_*()`. However, please note that: if an un-expected value is detected, the whole decoding operation _might_ be
/// **broken**. It's because those functions just decode the header of a value, and stop if not matched. So at that point, data stream _might_
/// already be broken.
///
/// In contrast, with [`::decode()`], when you expect an [`Object`] but get a [`List`], you can still continue decoding next values.
///
/// ---
///
/// Default implementors are copied from [`Read`]'s.
///
/// [`decode()`]: trait.Decoder.html#method.decode
/// [`Object`]: enum.Value.html#variant.Object
/// [`List`]: enum.Value.html#variant.List
/// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
pub trait Decoder: Read + Sized {

    /// # Decodes a value
    fn decode(&mut self) -> io::Result<Value> {
        Value::decode(self)
    }

    /// # Decodes a [`Null`]
    ///
    /// [`Null`]: enum.Value.html#variant.Null
    fn decode_null(&mut self) -> io::Result<()> {
        match decode_value(Some(&[NULL]), self)? {
            Value::Null => Ok(()),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_null() -> got: {:?}", &other))),
        }
    }
    /// # Decodes a boolean value
    fn decode_bool(&mut self) -> io::Result<bool> {
        match decode_value(Some(&[TRUE, FALSE]), self)? {
            Value::True => Ok(true),
            Value::False => Ok(false),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_bool() -> got: {:?}", &other))),
        }
    }

    /// # Decodes a `u8` value
    fn decode_u8(&mut self) -> io::Result<u8> {
        match decode_value(Some(&[U8]), self)? {
            Value::U8(u) => Ok(u),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_u8() -> got: {:?}", &other))),
        }
    }

    /// # Decodes an `i8` value
    fn decode_i8(&mut self) -> io::Result<i8> {
        match decode_value(Some(&[I8]), self)? {
            Value::I8(i) => Ok(i),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_i8() -> got: {:?}", &other))),
        }
    }

    /// # Decodes a `u16` value
    fn decode_u16(&mut self) -> io::Result<u16> {
        match decode_value(Some(&[U16]), self)? {
            Value::U16(u) => Ok(u),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_u16() -> got: {:?}", &other))),
        }
    }

    /// # Decodes an `i16` value
    fn decode_i16(&mut self) -> io::Result<i16> {
        match decode_value(Some(&[I16]), self)? {
            Value::I16(i) => Ok(i),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_i16() -> got: {:?}", &other))),
        }
    }

    /// # Decodes a `u32` value
    fn decode_u32(&mut self) -> io::Result<u32> {
        match decode_value(Some(&[U32]), self)? {
            Value::U32(u) => Ok(u),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_u32() -> got: {:?}", &other))),
        }
    }
    /// # Decodes an `i32` value
    fn decode_i32(&mut self) -> io::Result<i32> {
        match decode_value(Some(&[I32]), self)? {
            Value::I32(i) => Ok(i),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_i32() -> got: {:?}", &other))),
        }
    }

    /// # Decodes a `u64` value
    fn decode_u64(&mut self) -> io::Result<u64> {
        match decode_value(Some(&[U64]), self)? {
            Value::U64(u) => Ok(u),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_u64() -> got: {:?}", &other))),
        }
    }

    /// # Decodes an `i64` value
    fn decode_i64(&mut self) -> io::Result<i64> {
        match decode_value(Some(&[I64]), self)? {
            Value::I64(i) => Ok(i),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_i64() -> got: {:?}", &other))),
        }
    }

    /// # Decodes a [`Float`] value
    ///
    /// [`Float`]: enum.Value.html#variant.Float
    fn decode_float(&mut self) -> io::Result<f32> {
        match decode_value(Some(&[FLOAT]), self)? {
            Value::Float(f) => Ok(f),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_float() -> got: {:?}", &other))),
        }
    }

    /// # Decodes a [`Double`] value
    ///
    /// [`Double`]: enum.Value.html#variant.Double
    fn decode_double(&mut self) -> io::Result<f64> {
        match decode_value(Some(&[DOUBLE]), self)? {
            Value::Double(d) => Ok(d),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_double() -> got: {:?}", &other))),
        }
    }

    /// # Decodes a [`Text`]
    ///
    /// [`Text`]: enum.Value.html#variant.Text
    fn decode_text(&mut self) -> io::Result<String> {
        match decode_value(Some(&[TEXT]), self)? {
            Value::Text(t) => Ok(t),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_text() -> got: {:?}", &other))),
        }
    }

    /// # Decodes a [`DateTime`]
    ///
    /// [`DateTime`]: enum.Value.html#variant.DateTime
    fn decode_date_time(&mut self) -> io::Result<String> {
        match decode_value(Some(&[DATE_TIME]), self)? {
            Value::DateTime(dt) => Ok(dt),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_date_time() -> got: {:?}", &other))),
        }
    }

    /// # Decodes a [`Date`]
    ///
    /// [`Date`]: enum.Value.html#variant.Date
    fn decode_date(&mut self) -> io::Result<String> {
        match decode_value(Some(&[DATE]), self)? {
            Value::Date(d) => Ok(d),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_date() -> got: {:?}", &other))),
        }
    }

    /// # Decodes a [`Time`]
    ///
    /// [`Time`]: enum.Value.html#variant.Time
    fn decode_time(&mut self) -> io::Result<String> {
        match decode_value(Some(&[TIME]), self)? {
            Value::Time(t) => Ok(t),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_time() -> got: {:?}", &other))),
        }
    }

    /// # Decodes a [`DecimalStr`]
    ///
    /// [`DecimalStr`]: enum.Value.html#variant.DecimalStr
    fn decode_decimal_str(&mut self) -> io::Result<String> {
        match decode_value(Some(&[DECIMAL_STR]), self)? {
            Value::DecimalStr(ds) => Ok(ds),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_decimal_str() -> got: {:?}", &other))),
        }
    }

    /// # Decodes a [`Blob`]
    ///
    /// [`Blob`]: enum.Value.html#variant.Blob
    fn decode_blob(&mut self) -> io::Result<Vec<u8>> {
        match decode_value(Some(&[BLOB]), self)? {
            Value::Blob(bytes) => Ok(bytes),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_blob() -> got: {:?}", &other))),
        }
    }

    /// # Decodes a [`List`]
    ///
    /// [`List`]: enum.Value.html#variant.List
    fn decode_list(&mut self) -> io::Result<Vec<Value>> {
        match decode_value(Some(&[LIST]), self)? {
            Value::List(list) => Ok(list),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_list() -> got: {:?}", &other))),
        }
    }

    /// # Decodes a [`Map`]
    ///
    /// [`Map`]: enum.Value.html#variant.Map
    fn decode_map(&mut self) -> io::Result<BTreeMap<i32, Value>> {
        match decode_value(Some(&[MAP]), self)? {
            Value::Map(map) => Ok(map),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_map() -> got: {:?}", &other))),
        }
    }

    /// # Decodes an [`Object`]
    ///
    /// [`Object`]: enum.Value.html#variant.Object
    fn decode_object(&mut self) -> io::Result<HashMap<String, Value>> {
        match decode_value(Some(&[OBJECT]), self)? {
            Value::Object(object) => Ok(object),
            other => Err(Error::new(ErrorKind::InvalidData, format!("Decoder::decode_object() -> got: {:?}", &other))),
        }
    }

}

impl Decoder for ::std::fs::File {}
impl<'a> Decoder for &'a ::std::fs::File {}
impl<R: Read> Decoder for ::std::io::BufReader<R> {}
impl<T> Decoder for ::std::io::Cursor<T> where T: AsRef<[u8]> {}
impl<'a, R: Read + ?Sized> Decoder for &'a mut R {}
impl<R: Read + ?Sized> Decoder for Box<R> {}
impl<'a> Decoder for &'a [u8] {}
impl Decoder for ::std::io::Empty {}
impl Decoder for ::std::io::Repeat {}
impl Decoder for ::std::io::Stdin {}
impl<'a> Decoder for ::std::io::StdinLock<'a> {}
impl<T: Read, U: Read> Decoder for ::std::io::Chain<T, U> {}
impl<T: Read> Decoder for ::std::io::Take<T> {}
impl Decoder for ::std::net::TcpStream {}
impl<'a> Decoder for &'a ::std::net::TcpStream {}
impl Decoder for ::std::process::ChildStdout {}
impl Decoder for ::std::process::ChildStderr {}
#[cfg(unix)]
impl Decoder for ::std::os::unix::net::UnixStream {}
#[cfg(unix)]
impl<'a> Decoder for &'a ::std::os::unix::net::UnixStream {}