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
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788

use std::io::Write;
use std::io::Error as IoError;
use std::ascii::AsciiExt;
use super::{Parsable, Streamable, ParseError};

// RFC 5234, B.1  Core Rules
//const CR: u8 = 0x0D;     //   CR             =  %x0D      ; carriage return
//const LF: u8 = 0x0A;     //   LF             =  %x0A      ; linefeed
const SP: u8 = 0x20;     //   SP             =  %x20
const HTAB: u8 = 0x09;   //   HTAB           =  %x09      ; horizontal tab
//const DQUOTE: u8 = 0x22; //   DQUOTE         =  %x22      ; " (Double Quote)

// RFC 5234, B.1  Core Rules
// VCHAR           =  %x21-7E   ; visible (printing) characters)
#[inline]
pub fn is_vchar(c: u8) -> bool { c>=0x21 && c<=0x7E }
def_cclass!(VChar, is_vchar);
impl_display!(VChar);

// RFC 5234, B.1  Core Rules  WSP            =  SP / HTAB ; white space
#[inline]
pub fn is_wsp(c: u8) -> bool { c==SP || c==HTAB }
def_cclass!(WSP, is_wsp);
impl_display!(WSP);

// RFC 5234, B.1  Core Rules  CHAR           =  %x01-7F ; any 7-bit US-ASCII character,
//                                                      ;  excluding NUL
#[inline]
pub fn is_ascii(c: u8) -> bool { c>=1 && c<=127 }
def_cclass!(ASCII, is_ascii);
impl_display!(ASCII);

// RFC 5234, B.1  Core Rules  DIGIT          =  %x30-39   ; 0-9
#[inline]
pub fn is_digit(c: u8) -> bool { c>=0x30 && c<=0x39 }
def_cclass!(Digit, is_digit);
impl_display!(Digit);

// RFC 5234, B.1  Core Rules  ALPHA          = %x41-5A / %x61-7A   ; A-Z / a-z
#[inline]
pub fn is_alpha(c: u8) -> bool { (c>=0x41 && c<=0x5A) || (c>=0x61 && c<=0x7A) }
def_cclass!(Alpha, is_alpha);
impl_display!(Alpha);

// 3.2.1
// quoted-pair     =   ("\" (VCHAR / WSP)) / obs-qp
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct QuotedPair(pub u8);
impl Parsable for QuotedPair {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        let mut pos: usize = 0;
        if pos >= input.len() { return Err(ParseError::Eof("Quoted Pair")); }
        if pos + 1 >= input.len() { return Err(ParseError::NotFound("Quoted Pair")); }
        if input[pos]!=b'\\' { return Err(ParseError::NotFound("Quoted Pair")); }
        if is_vchar(input[pos + 1]) || is_wsp(input[pos + 1]) {
            pos += 2;
            let qp = QuotedPair(input[pos - 1]);
            return Ok((qp, &input[pos..]));
        }
        Err(ParseError::NotFound("Quoted Pair"))
    }
}
impl Streamable for QuotedPair {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        Ok(try!(w.write(b"\\"))
           + try!(w.write(&[self.0])))
    }
}
impl_display!(QuotedPair);

// 3.2.2
// FWS             =   ([*WSP CRLF] 1*WSP) /  obs-FWS
//                                        ; Folding white space
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FWS;
impl Parsable for FWS {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        let mut rem = input;
        if rem.len() == 0 { return Err(ParseError::Eof("Folding White Space")); }
        while rem.len() > 0 {
            if is_wsp(rem[0]) {
                rem = &rem[1..];
            }
            else if rem.len() > 2 && &rem[0..2]==b"\r\n" && is_wsp(rem[2]) {
                rem = &rem[3..];
            }
            else {
                break;
            }
        }
        if rem.len() == input.len() { Err(ParseError::NotFound("Folding White Space")) }
        else { Ok((FWS, rem)) }
    }
}
impl Streamable for FWS {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        Ok(try!(w.write(b" "))) // FIXME - fold?
    }
}
impl_display!(FWS);

// 3.2.2
// ctext           =   %d33-39 /          ; Printable US-ASCII
//                     %d42-91 /          ;  characters not including
//                     %d93-126 /         ;  "(", ")", or "\"
//                     obs-ctext
#[inline]
pub fn is_ctext(c: u8) -> bool { (c>=33 && c<=39) || (c>=42 && c<=91) || (c>=93 && c<=126) }
def_cclass!(CText, is_ctext);
impl_display!(CText);

// 3.2.2
// ccontent        =   ctext / quoted-pair / comment
#[derive(Debug, Clone, PartialEq)]
pub enum CContent {
    CText(CText),
    QuotedPair(QuotedPair),
    Comment(Comment),
}
impl Parsable for CContent {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if let Ok((na, rem)) = CText::parse(input) {
            Ok((CContent::CText(na), rem))
        }
        else if let Ok((asp, rem)) = QuotedPair::parse(input) {
            Ok((CContent::QuotedPair(asp), rem))
        }
        else if let Ok((c, rem)) = Comment::parse(input) {
            Ok((CContent::Comment(c), rem))
        }
        else {
            Err(ParseError::NotFound("CContent"))
        }
    }
}
impl Streamable for CContent {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        match *self {
            CContent::CText(ref x) => x.stream(w),
            CContent::QuotedPair(ref x) => x.stream(w),
            CContent::Comment(ref x) => x.stream(w),
        }
    }
}
impl_display!(CContent);

// 3.2.2
// comment         =   "(" *([FWS] ccontent) [FWS] ")"
#[derive(Debug, Clone, PartialEq)]
pub struct Comment {
    pub ccontent: Vec<(bool, CContent)>, // bool representing if whitespace preceeds it
    pub trailing_ws: bool,
}
impl Parsable for Comment {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        let mut rem: &[u8] = input;
        if rem.len() == 0 { return Err(ParseError::Eof("Comment")); }
        req!(rem, b"(", input);
        let mut ccontent: Vec<(bool, CContent)> = Vec::new();
        let mut ws: bool = false;
        while rem.len() > 0 {
            let t = parse!(FWS, rem);
            ws = t.is_ok();
            if let Ok(cc) = parse!(CContent, rem) {
                ccontent.push((ws, cc));
                continue;
            }
            break;
        }
        req!(rem, b")", input);
        return Ok((Comment {
            ccontent: ccontent,
            trailing_ws: ws,
        }, rem));
    }
}
impl Streamable for Comment {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let mut count: usize = 0;
        count += try!(w.write(b"("));
        for &(ws, ref cc) in &self.ccontent {
            if ws { count += try!(w.write(b" ")) }
            count += try!(cc.stream(w));
        }
        if self.trailing_ws { count += try!(w.write(b" ")) }
        count += try!(w.write(b")"));
        Ok(count)
    }
}
impl_display!(Comment);

// 3.2.2
// CFWS            =   (1*([FWS] comment) [FWS]) / FWS
#[derive(Debug, Clone, PartialEq)]
pub struct CFWS {
    pub comments: Vec<(bool, Comment)>, // bool representing if whitespace preceeds it
    pub trailing_ws: bool,
}
impl Parsable for CFWS {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Comment Folding White Space")); }
        let mut comments: Vec<(bool, Comment)> = Vec::new();
        let mut rem = input;
        let mut ws: bool = false;
        while rem.len() > 0 {
            let w = parse!(FWS, rem);
            ws = w.is_ok();
            if let Ok(comment) = parse!(Comment, rem) {
                comments.push((ws, comment));
                continue;
            }
            break;
        }
        if comments.len() > 0 || ws {
            Ok((CFWS {
                comments: comments,
                trailing_ws: ws,
            }, rem))
        } else {
            Err(ParseError::NotFound("Comment Folding White Space"))
        }
    }
}
impl Streamable for CFWS {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let mut count: usize = 0;
        for &(ws, ref comment) in &self.comments {
            if ws { count += try!(w.write(b" ")) }
            count += try!(comment.stream(w));
        }
        if self.trailing_ws { count += try!(w.write(b" ")) }
        Ok(count)
    }
}
impl_display!(CFWS);

// 3.2.3
// atext           =   ALPHA / DIGIT /    ; Printable US-ASCII
//                     "!" / "#" /        ;  characters not including
//                     "$" / "%" /        ;  specials.  Used for atoms.
//                     "&" / "'" /
//                     "*" / "+" /
//                     "-" / "/" /
//                     "=" / "?" /
//                     "^" / "_" /
//                     "`" / "{" /
//                     "|" / "}" /
//                     "~"
#[inline]
pub fn is_atext(c: u8) -> bool {
    is_alpha(c) || is_digit(c)
        || c==b'!' || c==b'#'  || c==b'$' || c==b'%'
        || c==b'&' || c==b'\'' || c==b'*' || c==b'+'
        || c==b'-' || c==b'/'  || c==b'=' || c==b'?'
        || c==b'^' || c==b'_'  || c==b'`' || c==b'{'
        || c==b'|' || c==b'}'  || c==b'~'
}
def_cclass!(AText, is_atext);
impl_display!(AText);

// 3.2.3
// atom            =   [CFWS] 1*atext [CFWS]
#[derive(Debug, Clone, PartialEq)]
pub struct Atom {
    pub pre_cfws: Option<CFWS>,
    pub atext: AText,
    pub post_cfws: Option<CFWS>,
}
impl Parsable for Atom {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len()==0 { return Err(ParseError::Eof("Atom")); }
        let mut rem = input;
        let pre_cfws = parse!(CFWS, rem);
        if let Ok(atext) = parse!(AText, rem) {
            let post_cfws = parse!(CFWS, rem);
            return Ok((Atom {
                pre_cfws: pre_cfws.ok(),
                atext: atext,
                post_cfws: post_cfws.ok(),
            }, rem));
        }
        Err(ParseError::NotFound("Atom"))
    }
}
impl Streamable for Atom {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let mut count: usize = 0;
        if let Some(ref cfws) = self.pre_cfws {
            count += try!(cfws.stream(w));
        }
        count += try!(self.atext.stream(w));
        if let Some(ref cfws) = self.post_cfws {
            count += try!(cfws.stream(w));
        }
        Ok(count)
    }
}
impl_display!(Atom);

// 3.2.3
// dot-atom-text   =   1*atext *("." 1*atext)
#[derive(Debug, Clone, PartialEq)]
pub struct DotAtomText(pub Vec<AText>);
impl Parsable for DotAtomText {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        let mut rem = input;
        let mut parts: Vec<AText> = Vec::new();
        match parse!(AText, rem) {
            Ok(part) => parts.push(part),
            Err(e) => return Err(e),
        }
        while rem.len() > 0 {
            if rem[0]!=b'.' { break; };
            let rem2 = &rem[1..];
            if let Ok((part, r)) = AText::parse(rem2) {
                rem = r;
                parts.push(part);
                continue;
            } else {
                break;
            }
        }
        Ok((DotAtomText(parts), rem))
    }
}
impl Streamable for DotAtomText {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let mut count: usize = 0;
        let mut virgin: bool = true;
        for part in &self.0 {
            if !virgin { count += try!(w.write(b".")) }
            count += try!(part.stream(w));
            virgin = false;
        }
        Ok(count)
    }
}
impl_display!(DotAtomText);

// 3.2.3
// dot-atom        =   [CFWS] dot-atom-text [CFWS]
#[derive(Debug, Clone, PartialEq)]
pub struct DotAtom {
    pub pre_cfws: Option<CFWS>,
    pub dot_atom_text: DotAtomText,
    pub post_cfws: Option<CFWS>,
}
impl Parsable for DotAtom {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        let mut rem = input;
        if rem.len() == 0 { return Err(ParseError::Eof("DotAtom")); }
        let pre_cfws = parse!(CFWS, rem);
        if let Ok(dat) = parse!(DotAtomText, rem) {
            let post_cfws = parse!(CFWS, rem);
            Ok((DotAtom {
                pre_cfws: pre_cfws.ok(),
                dot_atom_text: dat,
                post_cfws: post_cfws.ok(),
            }, rem))
        } else {
            Err(ParseError::NotFound("DotAtom"))
        }
    }
}
impl Streamable for DotAtom {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let mut count: usize = 0;
        if let Some(ref cfws) = self.pre_cfws {
            count += try!(cfws.stream(w));
        }
        count += try!(self.dot_atom_text.stream(w));
        if let Some(ref cfws) = self.post_cfws {
            count += try!(cfws.stream(w));
        }
        Ok(count)
    }
}
impl_display!(DotAtom);

// 3.2.3 (we don't need to parse this one, it is not used.  could be used as a tokenization
//        point in lexical analysis)
// specials            = "(" / ")" /        ; Special characters that do
//                       "<" / ">" /        ;  not appear in atext
//                       "[" / "]" /
//                       ":" / ";" /
//                       "@" / "\" /
//                       "," / "." /
//                       DQUOTE

// 3.2.4
// qtext           =   %d33 /             ; Printable US-ASCII
//                     %d35-91 /          ;  characters not including
//                     %d93-126 /         ;  "\" or the quote character
//                     obs-qtext
#[inline]
pub fn is_qtext(c: u8) -> bool { c==33 || (c>=35 && c<=91) || (c>=93 && c<=126) }
def_cclass!(QText, is_qtext);
impl_display!(QText);

// 3.2.4
// qcontent        =   qtext / quoted-pair
#[derive(Debug, Clone, PartialEq)]
pub enum QContent {
    QText(QText),
    QuotedPair(QuotedPair),
}
impl Parsable for QContent {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("QContent")); }
        if let Ok((x, rem)) = QText::parse(input) {
            Ok((QContent::QText(x), rem))
        }
        else if let Ok((x, rem)) = QuotedPair::parse(input) {
            Ok((QContent::QuotedPair(x), rem))
        }
        else {
            Err(ParseError::NotFound("QContent"))
        }
    }
}
impl Streamable for QContent {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        match *self {
            QContent::QText(ref x) => x.stream(w),
            QContent::QuotedPair(ref x) => x.stream(w),
        }
    }
}
impl_display!(QContent);

// 3.2.4
// quoted-string   =   [CFWS]
//                     DQUOTE *([FWS] qcontent) [FWS] DQUOTE
//                     [CFWS]
#[derive(Debug, Clone, PartialEq)]
pub struct QuotedString {
    pub pre_cfws: Option<CFWS>,
    pub qcontent: Vec<(bool, QContent)>, // bool representing if whitespace preceeds it
    pub trailing_ws: bool,
    pub post_cfws: Option<CFWS>,
}
impl Parsable for QuotedString {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("QuotedString")); }
        let mut rem = input;
        let pre_cfws = parse!(CFWS, rem);
        req!(rem, b"\"", input);
        let mut qcontent: Vec<(bool, QContent)> = Vec::new();
        let mut ws: bool = false;
        while rem.len() > 0 {
            let t = parse!(FWS, rem);
            ws = t.is_ok();
            if let Ok(qc) = parse!(QContent, rem) {
                qcontent.push((ws, qc));
                continue;
            }
            break;
        }
        req!(rem, b"\"", input);
        let post_cfws = parse!(CFWS, rem);
        Ok((QuotedString {
            pre_cfws: pre_cfws.ok(),
            qcontent: qcontent,
            trailing_ws: ws,
            post_cfws: post_cfws.ok() }, rem))
    }
}
impl Streamable for QuotedString {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let mut count: usize = 0;
        if let Some(ref cfws) = self.pre_cfws {
            count += try!(cfws.stream(w));
        }
        count += try!(w.write(b"\""));
        for &(ws, ref qc) in &self.qcontent {
            if ws {
                count += try!(w.write(b" "));
            }
            count += try!(qc.stream(w));
        }
        if self.trailing_ws {
            count += try!(w.write(b" "));
        }
        count += try!(w.write(b"\""));
        if let Some(ref cfws) = self.post_cfws {
            count += try!(cfws.stream(w));
        }
        Ok(count)
    }
}
impl_display!(QuotedString);

// 3.2.5
// word            =   atom / quoted-string
#[derive(Debug, Clone, PartialEq)]
pub enum Word {
    Atom(Atom),
    QuotedString(QuotedString),
}
impl Parsable for Word {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Word")); }
        if let Ok((x, rem)) = Atom::parse(input) {
            Ok((Word::Atom(x), rem))
        }
        else if let Ok((x, rem)) = QuotedString::parse(input) {
            Ok((Word::QuotedString(x), rem))
        }
        else {
            Err(ParseError::NotFound("Word"))
        }
    }
}
impl Streamable for Word {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        match *self {
            Word::Atom(ref x) => x.stream(w),
            Word::QuotedString(ref x) => x.stream(w),
        }
    }
}
impl_display!(Word);

// 3.2.5
// phrase          =   1*word / obs-phrase
#[derive(Debug, Clone, PartialEq)]
pub struct Phrase(pub Vec<Word>);
impl Parsable for Phrase {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Phrase")); }
        let mut rem = input;
        let mut output: Vec<Word> = Vec::new();
        while let Ok(word) = parse!(Word, rem) {
            output.push(word);
        }
        if output.len() == 0 {
            Err(ParseError::NotFound("Phrase"))
        } else {
            Ok((Phrase(output), rem))
        }
    }
}
impl Streamable for Phrase {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let mut count: usize = 0;
        for word in &self.0 {
            count += try!(word.stream(w));
        }
        Ok(count)
    }
}
impl_display!(Phrase);

// 3.2.5
// unstructured    = (*([FWS] VCHAR) *WSP) / obs-unstruct
#[derive(Debug, Clone, PartialEq)]
pub struct Unstructured {
    pub leading_ws: bool,
    pub parts: Vec<VChar>, // always separated by whitespace
    pub trailing_ws: bool,
}
impl Parsable for Unstructured {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Unstructured")); }
        let mut rem = input;
        let mut output: Vec<VChar> = Vec::new();
        let t = parse!(FWS, rem);
        let leading_ws: bool = t.is_ok();
        while rem.len() > 0 {
            let mut rem2 = match FWS::parse(rem) {
                Ok((_, rem2)) => rem2,
                Err(_) => rem,
            };
            if let Ok(vchar) = parse!(VChar, rem2) {
                rem = rem2;
                output.push(vchar);
                continue;
            }
            break;
        }
        if output.len() == 0 { return Err(ParseError::NotFound("Unstructured")); }
        let t = parse!(WSP, rem);
        Ok((Unstructured {
            leading_ws: leading_ws,
            parts: output,
            trailing_ws: t.is_ok()
        }, rem))
    }
}
impl Streamable for Unstructured {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let mut count: usize = 0;
        if self.leading_ws { count += try!(w.write(b" ")); }
        let mut first: bool = true;
        for vc in &self.parts {
            if !first {
                count += try!(w.write(b" "));
            }
            count += try!(vc.stream(w));
            first = false;
        }
        if self.trailing_ws { count += try!(w.write(b" ")); }
        Ok(count)
    }
}
impl_display!(Unstructured);

// 3.4.1
// local-part      =   dot-atom / quoted-string / obs-local-part
#[derive(Debug, Clone, PartialEq)]
pub enum LocalPart {
    DotAtom(DotAtom),
    QuotedString(QuotedString),
}
impl Parsable for LocalPart {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("LocalPart")); }
        if let Ok((x, rem)) = DotAtom::parse(input) {
            Ok((LocalPart::DotAtom(x), rem))
        }
        else if let Ok((x, rem)) = QuotedString::parse(input) {
            Ok((LocalPart::QuotedString(x), rem))
        }
        else {
            Err(ParseError::NotFound("LocalPart"))
        }
    }
}
impl Streamable for LocalPart {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        match *self {
            LocalPart::DotAtom(ref x) => x.stream(w),
            LocalPart::QuotedString(ref x) => x.stream(w),
        }
    }
}
impl_display!(LocalPart);

// 3.4.1
// dtext           =   %d33-90 /          ; Printable US-ASCII
//                     %d94-126 /         ;  characters not including
//                     obs-dtext          ;  "[", "]", or "\"
#[inline]
pub fn is_dtext(c: u8) -> bool { (c>=33 && c<=90) || (c>=94 && c<=126) }
def_cclass!(DText, is_dtext);
impl_display!(DText);

// 3.4.1
// domain-literal  =   [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
#[derive(Debug, Clone, PartialEq)]
pub struct DomainLiteral {
    pub pre_cfws: Option<CFWS>,
    pub dtext: Vec<(bool, DText)>, // bool representing if whitespace preceeds it
    pub trailing_ws: bool,
    pub post_cfws: Option<CFWS>,
}
impl Parsable for DomainLiteral {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("DomainLiteral")); }
        let mut rem = input;
        let mut dtext: Vec<(bool, DText)> = Vec::new();
        let pre_cfws = parse!(CFWS, rem);
        req!(rem, b"[", input);
        let mut ws: bool = false;
        while rem.len() > 0 {
            let t = parse!(FWS, rem);
            ws = t.is_ok();
            if let Ok(d) = parse!(DText, rem) {
                dtext.push((ws,d));
                continue;
            }
            break;
        }
        req!(rem, b"]", input);
        let post_cfws = parse!(CFWS, rem);
        Ok((DomainLiteral {
            pre_cfws: pre_cfws.ok(),
            dtext: dtext,
            trailing_ws: ws,
            post_cfws: post_cfws.ok(),
        }, rem))
    }
}
impl Streamable for DomainLiteral {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let mut count: usize = 0;
        if let Some(ref cfws) = self.pre_cfws {
            count += try!(cfws.stream(w));
        }
        count += try!(w.write(b"["));
        for &(ws, ref dt) in &self.dtext {
            if ws {  count += try!(w.write(b" ")); }
            count += try!(dt.stream(w));
        }
        count += try!(w.write(b"]"));
        if let Some(ref cfws) = self.post_cfws {
            count += try!(cfws.stream(w));
        }
        Ok(count)
    }
}
impl_display!(DomainLiteral);

// 3.4.1
// domain          =   dot-atom / domain-literal / obs-domain
#[derive(Debug, Clone, PartialEq)]
pub enum Domain {
    DotAtom(DotAtom),
    DomainLiteral(DomainLiteral),
}
impl Parsable for Domain {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Domain")); }
        if let Ok((x, rem)) = DotAtom::parse(input) {
            Ok((Domain::DotAtom(x), rem))
        }
        else if let Ok((x, rem)) = DomainLiteral::parse(input) {
            Ok((Domain::DomainLiteral(x), rem))
        }
        else {
            Err(ParseError::NotFound("Domain"))
        }
    }
}
impl Streamable for Domain {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        match *self {
            Domain::DotAtom(ref x) => x.stream(w),
            Domain::DomainLiteral(ref x) => x.stream(w),
        }
    }
}
impl_display!(Domain);

// 3.4.1
// addr-spec       =   local-part "@" domain
#[derive(Debug, Clone, PartialEq)]
pub struct AddrSpec {
    pub local_part: LocalPart,
    pub domain: Domain,
}
impl Parsable for AddrSpec {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("AddrSpec")); }
        if let Ok((lp, rem)) = LocalPart::parse(input) {
            if rem.len() > 0 && rem[0]==b'@' {
                if let Ok((d, rem)) = Domain::parse(&rem[1..]) {
                    return Ok((AddrSpec {
                        local_part: lp,
                        domain: d
                    }, rem));
                }
            }
        }
        Err(ParseError::NotFound("AddrSpec"))
    }
}
impl Streamable for AddrSpec {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        Ok(try!(self.local_part.stream(w))
           + try!(w.write(b"@"))
           + try!(self.domain.stream(w)))
    }
}
impl_display!(AddrSpec);

// 3.4
// angle-addr      =   [CFWS] "<" addr-spec ">" [CFWS] /
//                     obs-angle-addr
#[derive(Debug, Clone, PartialEq)]
pub struct AngleAddr{
    pub pre_cfws: Option<CFWS>,
    pub addr_spec: AddrSpec,
    pub post_cfws: Option<CFWS>,
}
impl Parsable for AngleAddr {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("AngleAddr")); }
        let mut rem = input;
        let pre_cfws = parse!(CFWS, rem);
        req!(rem, b"<", input);
        if let Ok(aspec) = parse!(AddrSpec, rem) {
            req!(rem, b">", input);
            let post_cfws = parse!(CFWS, rem);
            return Ok((AngleAddr {
                pre_cfws: pre_cfws.ok(),
                addr_spec: aspec,
                post_cfws: post_cfws.ok(),
            }, rem));
        }
        Err(ParseError::NotFound("AngleAddr"))
    }
}
impl Streamable for AngleAddr {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let mut count: usize = 0;
        if let Some(ref cfws) = self.pre_cfws {
            count += try!(cfws.stream(w))
        }
        count += try!(w.write(b"<"));
        count += try!(self.addr_spec.stream(w));
        count += try!(w.write(b">"));
        if let Some(ref cfws) = self.post_cfws {
            count += try!(cfws.stream(w))
        }
        Ok(count)
    }
}
impl_display!(AngleAddr);

// 3.4
// display-name    =   phrase
#[derive(Debug, Clone, PartialEq)]
pub struct DisplayName(pub Phrase);
impl Parsable for DisplayName {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        Phrase::parse(input).map(|(p,rem)| (DisplayName(p),rem))
    }
}
impl Streamable for DisplayName {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        self.0.stream(w)
    }
}
impl_display!(DisplayName);

// 3.4
// name-addr       =   [display-name] angle-addr
#[derive(Debug, Clone, PartialEq)]
pub struct NameAddr {
    pub display_name: Option<DisplayName>,
    pub angle_addr: AngleAddr
}
impl Parsable for NameAddr {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("NameAddr")); }
        let mut rem = input;
        let maybe_dn = parse!(DisplayName, rem);
        if let Ok(aa) = parse!(AngleAddr, rem) {
            return Ok((NameAddr {
                display_name: maybe_dn.ok(),
                angle_addr: aa,
            }, rem));
        }
        Err(ParseError::NotFound("NameAddr"))
    }
}
impl Streamable for NameAddr {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let mut count: usize = 0;
        if self.display_name.is_some() {
            count += try!(self.display_name.as_ref().unwrap().stream(w));
        }
        count += try!(self.angle_addr.stream(w));
        Ok(count)
    }
}
impl_display!(NameAddr);

// 3.4
// mailbox         =   name-addr / addr-spec
#[derive(Debug, Clone, PartialEq)]
pub enum Mailbox {
    NameAddr(NameAddr),
    AddrSpec(AddrSpec),
}
impl Parsable for Mailbox {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Mailbox")); }
        if let Ok((x, rem)) = NameAddr::parse(input) {
            Ok((Mailbox::NameAddr(x), rem))
        }
        else if let Ok((x, rem)) = AddrSpec::parse(input) {
            Ok((Mailbox::AddrSpec(x), rem))
        }
        else {
            Err(ParseError::NotFound("Mailbox"))
        }
    }
}
impl Streamable for Mailbox {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        match *self {
            Mailbox::NameAddr(ref na) => na.stream(w),
            Mailbox::AddrSpec(ref asp) => asp.stream(w),
        }
    }
}
impl_display!(Mailbox);

// 3.4
// mailbox-list    =   (mailbox *("," mailbox)) / obs-mbox-list
#[derive(Debug, Clone, PartialEq)]
pub struct MailboxList(pub Vec<Mailbox>);
impl Parsable for MailboxList {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Mailbox List")); }
        let mut rem = input;
        let mut output: Vec<Mailbox> = Vec::new();
        let mut savedrem = rem;
        while let Ok(mailbox) = parse!(Mailbox, rem) {
            savedrem = rem;
            output.push(mailbox);
            if rem.len()==0 || rem[0]!=b',' {
                break;
            }
            rem = &rem[1..];
        }
        rem = savedrem;
        if output.len() == 0 {
            Err(ParseError::NotFound("MailboxList"))
        } else {
            Ok((MailboxList(output), rem))
        }
    }
}
impl Streamable for MailboxList {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let mut count: usize = 0;
        let mut virgin: bool = true;
        for mb in &self.0 {
            if ! virgin {
                count += try!(w.write(b","));
            }
            count += try!(mb.stream(w));
            virgin = false;
        }
        Ok(count)
    }
}
impl_display!(MailboxList);

// 3.4
// group-list      =   mailbox-list / CFWS / obs-group-list
#[derive(Debug, Clone, PartialEq)]
pub enum GroupList {
    MailboxList(MailboxList),
    CFWS(CFWS),
}
impl Parsable for GroupList {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Group List")); }
        if let Ok((x, rem)) = MailboxList::parse(input) {
            Ok((GroupList::MailboxList(x), rem))
        }
        else if let Ok((x, rem)) = CFWS::parse(input) {
            Ok((GroupList::CFWS(x), rem))
        }
        else {
            Err(ParseError::NotFound("GroupList"))
        }
    }
}
impl Streamable for GroupList {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        match *self {
            GroupList::MailboxList(ref na) => na.stream(w),
            GroupList::CFWS(ref asp) => asp.stream(w),
        }
    }
}
impl_display!(GroupList);

// 3.4
// group           =   display-name ":" [group-list] ";" [CFWS]
#[derive(Debug, Clone, PartialEq)]
pub struct Group {
    pub display_name: DisplayName,
    pub group_list: Option<GroupList>,
    pub cfws: Option<CFWS>,
}
impl Parsable for Group {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Group")); }
        let mut rem = input;
        if let Ok(dn) = parse!(DisplayName, rem) {
            req!(rem, b":", input);
            let group_list = parse!(GroupList, rem);
            req!(rem, b";", input);
            let cfws = parse!(CFWS, rem);
            return Ok((Group {
                display_name: dn,
                group_list: group_list.ok(),
                cfws: cfws.ok(),
            }, rem));
        }
        Err(ParseError::NotFound("Group"))
    }
}
impl Streamable for Group {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let mut count: usize = 0;
        count += try!(self.display_name.stream(w));
        count += try!(w.write(b":"));
        if let Some(ref gl) = self.group_list {
            count += try!(gl.stream(w));
        }
        count += try!(w.write(b";"));
        if let Some(ref cfws) = self.cfws {
            count += try!(cfws.stream(w));
        }
        Ok(count)
    }
}
impl_display!(Group);

// 3.4
// address         =   mailbox / group
#[derive(Debug, Clone, PartialEq)]
pub enum Address {
    Mailbox(Mailbox),
    Group(Group),
}
impl Parsable for Address {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Address")); }
        if let Ok((x, rem)) = Mailbox::parse(input) {
            Ok((Address::Mailbox(x), rem))
        }
        else if let Ok((x, rem)) = Group::parse(input) {
            Ok((Address::Group(x), rem))
        }
        else {
            Err(ParseError::NotFound("Address"))
        }
    }
}
impl Streamable for Address {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        match *self {
            Address::Mailbox(ref x) => x.stream(w),
            Address::Group(ref x) => x.stream(w),
        }
    }
}
impl_display!(Address);

// 3.4
// address-list    =   (address *("," address)) / obs-addr-list
#[derive(Debug, Clone, PartialEq)]
pub struct AddressList(pub Vec<Address>);
impl Parsable for AddressList {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Address List")); }
        let mut rem = input;
        let mut output: Vec<Address> = Vec::new();
        let mut savedrem = rem;
        while let Ok(mailbox) = parse!(Address, rem) {
            savedrem = rem;
            output.push(mailbox);
            if rem.len()==0 || rem[0]!=b',' {
                break;
            }
            rem = &rem[1..];
        }
        rem = savedrem;
        if output.len() == 0 {
            Err(ParseError::NotFound("AddressList"))
        } else {
            Ok((AddressList(output), rem))
        }
    }
}
impl Streamable for AddressList {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let mut count: usize = 0;
        let mut virgin: bool = true;
        for a in &self.0 {
            if ! virgin {
                count += try!(w.write(b","));
            }
            count += try!(a.stream(w));
            virgin = false;
        }
        Ok(count)
    }
}
impl_display!(AddressList);

// 3.3
// zone            =   (FWS ( "+" / "-" ) 4DIGIT) / obs-zone
#[derive(Debug, Clone, PartialEq)]
pub struct Zone(pub i32);
impl Parsable for Zone {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Zone")); }
        let mut rem = input;
        let fws = parse!(FWS, rem);
        if fws.is_err() { return Err(ParseError::NotFound("Zone")); }
        if rem.len() < 5 { return Err(ParseError::NotFound("Zone")); }
        let sign: i32 = match rem[0] {
            b'+' => 1,
            b'-' => -1,
            _ => return Err(ParseError::NotFound("Zone")),
        };
        if !is_digit(rem[1]) || !is_digit(rem[2]) || !is_digit(rem[3]) || !is_digit(rem[4]) {
            return Err(ParseError::NotFound("Zone"));
        }
        let v: i32 = (1000 * ((rem[1]-48) as i32)
                      + 100 * ((rem[2]-48) as i32)
                      + 10 * ((rem[3]-48) as i32)
                      + ((rem[4]-48) as i32)) * sign;
        Ok((Zone(v), &rem[5..]))
    }
}
impl Streamable for Zone {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let v = if self.0 < 0 {
            try!(w.write(b" -"));
            -self.0
        } else {
            try!(w.write(b" +"));
            self.0
        };
        try!(write!(w, "{:04}", v));
        Ok(6)
    }
}
impl_display!(Zone);

// 3.3
// second          =   2DIGIT / obs-second
#[derive(Debug, Clone, PartialEq)]
pub struct Second(pub u8);
impl Parsable for Second {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Second")); }
        if input.len() < 2 { return Err(ParseError::NotFound("Second")); }
        if !is_digit(input[0]) || !is_digit(input[1]) {
            return Err(ParseError::NotFound("Second"));
        }
        let v: u8 = (10 * (input[0]-48)) + (input[1]-48);
        Ok((Second(v), &input[2..]))
    }
}
impl Streamable for Second {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        try!(write!(w, "{:02}", self.0));
        Ok(2)
    }
}
impl_display!(Second);

// 3.3
// minute          =   2DIGIT / obs-minute
#[derive(Debug, Clone, PartialEq)]
pub struct Minute(pub u8);
impl Parsable for Minute {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Minute")); }
        if input.len() < 2 { return Err(ParseError::NotFound("Minute")); }
        if !is_digit(input[0]) || !is_digit(input[1]) {
            return Err(ParseError::NotFound("Minute"));
        }
        let v: u8 = (10 * (input[0]-48)) + (input[1]-48);
        Ok((Minute(v), &input[2..]))
    }
}
impl Streamable for Minute {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        try!(write!(w, "{:02}", self.0));
        Ok(2)
    }
}
impl_display!(Minute);

// 3.3
// hour          =   2DIGIT / obs-hour
#[derive(Debug, Clone, PartialEq)]
pub struct Hour(pub u8);
impl Parsable for Hour {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Hour")); }
        if input.len() < 2 { return Err(ParseError::NotFound("Hour")); }
        if !is_digit(input[0]) || !is_digit(input[1]) {
            return Err(ParseError::NotFound("Hour"));
        }
        let v: u8 = (10 * (input[0]-48)) + (input[1]-48);
        Ok((Hour(v), &input[2..]))
    }
}
impl Streamable for Hour {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        try!(write!(w, "{:02}", self.0));
        Ok(2)
    }
}
impl_display!(Hour);

// 3.3
// time-of-day     =   hour ":" minute [ ":" second ]
#[derive(Debug, Clone, PartialEq)]
pub struct TimeOfDay {
    pub hour: Hour,
    pub minute: Minute,
    pub second: Option<Second>
}
impl Parsable for TimeOfDay {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("TimeOfDay")); }
        let mut rem = input;
        if let Ok(hour) = parse!(Hour, rem) {
            req!(rem, b":", input);
            if let Ok(minute) = parse!(Minute, rem) {
                let saved = rem;
                if rem.len() > 0 && rem[0]==b':' {
                    rem = &rem[1..];
                    if let Ok(second) = parse!(Second, rem) {
                        return Ok((TimeOfDay {
                            hour: hour,
                            minute: minute,
                            second: Some(second),
                        }, rem));
                    }
                }
                return Ok((TimeOfDay {
                    hour: hour,
                    minute: minute,
                    second: None,
                }, saved));
            }
        }
        Err(ParseError::NotFound("TimeOfDay"))
    }
}
impl Streamable for TimeOfDay {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        if self.second.is_some() {
            try!(write!(w, "{:02}:{:02}:{:02}", self.hour.0, self.minute.0,
                        self.second.as_ref().unwrap().0));
            Ok(8)
        } else {
            try!(write!(w, "{:02}:{:02}", self.hour.0, self.minute.0));
            Ok(5)
        }
    }
}
impl_display!(TimeOfDay);

// 3.3
// time            =   time-of-day zone
#[derive(Debug, Clone, PartialEq)]
pub struct Time {
    pub time_of_day: TimeOfDay,
    pub zone: Zone,
}
impl Parsable for Time {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Time")); }
        let mut rem = input;
        if let Ok(tod) = parse!(TimeOfDay, rem) {
            if let Ok(zone) = parse!(Zone, rem) {
                return Ok((Time {
                    time_of_day: tod,
                    zone: zone
                }, rem));
            }
        }
        Err(ParseError::NotFound("Time"))
    }
}
impl Streamable for Time {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        Ok(try!(self.time_of_day.stream(w))
           + try!(self.zone.stream(w)))
    }
}
impl_display!(Time);

// 3.3
// year            =   (FWS 4*DIGIT FWS) / obs-year
#[derive(Debug, Clone, PartialEq)]
pub struct Year(pub u32);
impl Parsable for Year {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Year")); }
        let mut rem = input;
        let fws = parse!(FWS, rem);
        if fws.is_err() { return Err(ParseError::NotFound("Year")); }
        if rem.len() < 5 { return Err(ParseError::NotFound("Year")); }
        if !is_digit(rem[0]) || !is_digit(rem[1]) || !is_digit(rem[2]) || !is_digit(rem[3]) {
            return Err(ParseError::NotFound("Year"));
        }
        let v: u32 = 1000 * ((rem[0]-48) as u32)
                      + 100 * ((rem[1]-48) as u32)
                      + 10 * ((rem[2]-48) as u32)
                      + ((rem[3]-48) as u32);
        rem = &rem[4..];
        let fws = parse!(FWS, rem);
        if fws.is_err() { return Err(ParseError::NotFound("Year")); }
        Ok((Year(v), rem))
    }
}
impl Streamable for Year {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        try!(write!(w, " {:04} ", self.0));
        Ok(6)
    }
}
impl_display!(Year);

// 3.3
// month           =   "Jan" / "Feb" / "Mar" / "Apr" /
//                     "May" / "Jun" / "Jul" / "Aug" /
//                     "Sep" / "Oct" / "Nov" / "Dec"
#[derive(Debug, Clone, PartialEq)]
pub struct Month(pub u8);
impl Parsable for Month {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Month")); }
        if input.len() < 3 { return Err(ParseError::NotFound("Month")); }
        let three = &input[0..3].to_ascii_lowercase();
        let rem = &input[3..];
        if three==b"jan" { Ok((Month(1), rem)) }
        else if three==b"feb" { Ok((Month(2), rem)) }
        else if three==b"mar" { Ok((Month(3), rem)) }
        else if three==b"apr" { Ok((Month(4), rem)) }
        else if three==b"may" { Ok((Month(5), rem)) }
        else if three==b"jun" { Ok((Month(6), rem)) }
        else if three==b"jul" { Ok((Month(7), rem)) }
        else if three==b"aug" { Ok((Month(8), rem)) }
        else if three==b"sep" { Ok((Month(9), rem)) }
        else if three==b"oct" { Ok((Month(10), rem)) }
        else if three==b"nov" { Ok((Month(11), rem)) }
        else if three==b"dec" { Ok((Month(12), rem)) }
        else { Err(ParseError::NotFound("Month")) }
    }
}
impl Streamable for Month {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        match self.0 {
            1 => Ok(try!(w.write(b"Jan"))),
            2 => Ok(try!(w.write(b"Feb"))),
            3 => Ok(try!(w.write(b"Mar"))),
            4 => Ok(try!(w.write(b"Apr"))),
            5 => Ok(try!(w.write(b"May"))),
            6 => Ok(try!(w.write(b"Jun"))),
            7 => Ok(try!(w.write(b"Jul"))),
            8 => Ok(try!(w.write(b"Aug"))),
            9 => Ok(try!(w.write(b"Sep"))),
            10 => Ok(try!(w.write(b"Oct"))),
            11 => Ok(try!(w.write(b"Nov"))),
            12 => Ok(try!(w.write(b"Dec"))),
            _ => Err(IoError::new(::std::io::ErrorKind::InvalidData, "Month out of range"))
        }
    }
}
impl_display!(Month);

// 3.3
// day             =   ([FWS] 1*2DIGIT FWS) / obs-day
#[derive(Debug, Clone, PartialEq)]
pub struct Day(pub u8);
impl Parsable for Day {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Day")); }
        let mut rem = input;
        let _ = parse!(FWS, rem);
        if rem.len() < 3 { return Err(ParseError::NotFound("Day")); }
        if !is_digit(rem[0]) || (!is_digit(rem[1]) && !is_wsp(rem[1])) {
            return Err(ParseError::NotFound("Day"));
        }
        let mut v: u8 = rem[0] - 48;
        let mut num_consumed = 1;
        // the day field may be 1 or 2 digits
        if is_digit(rem[1]) {
            v = 10 * v + rem[1] - 48;
            num_consumed += 1;
        }
        rem = &rem[num_consumed..];
        let fws = parse!(FWS, rem);
        if fws.is_err() { return Err(ParseError::NotFound("Day")); }
        Ok((Day(v), rem))
    }
}
impl Streamable for Day {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        try!(write!(w, " {} ", self.0));
        Ok(4)
    }
}
impl_display!(Day);

// 3.3
// date            =   day month year
#[derive(Debug, Clone, PartialEq)]
pub struct Date {
    pub day: Day,
    pub month: Month,
    pub year: Year,
}
impl Parsable for Date {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Date")); }
        let mut rem = input;
        if let Ok(day) = parse!(Day, rem) {
            if let Ok(month) = parse!(Month, rem) {
                if let Ok(year) = parse!(Year, rem) {
                    return Ok((Date {
                        day: day,
                        month: month,
                        year: year,
                    }, rem));
                }
            }
        }
        Err(ParseError::NotFound("Date"))
    }
}
impl Streamable for Date {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        Ok(try!(self.day.stream(w))
           + try!(self.month.stream(w))
           + try!(self.year.stream(w)))
    }
}
impl_display!(Date);

// 3.3
// day-name        =   "Mon" / "Tue" / "Wed" / "Thu" /
//                     "Fri" / "Sat" / "Sun"
#[derive(Debug, Clone, PartialEq)]
pub struct DayName(pub u8);
impl Parsable for DayName {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("DayName")); }
        if input.len() < 3 { return Err(ParseError::NotFound("DayName")); }
        let three = &input[0..3].to_ascii_lowercase();
        let rem = &input[3..];
        if three==b"sun" { Ok((DayName(1), rem)) }
        else if three==b"mon" { Ok((DayName(2), rem)) }
        else if three==b"tue" { Ok((DayName(3), rem)) }
        else if three==b"wed" { Ok((DayName(4), rem)) }
        else if three==b"thu" { Ok((DayName(5), rem)) }
        else if three==b"fri" { Ok((DayName(6), rem)) }
        else if three==b"sat" { Ok((DayName(7), rem)) }
        else { Err(ParseError::NotFound("DayName")) }
    }
}
impl Streamable for DayName {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        match self.0 {
            1 => Ok(try!(w.write(b"Sun"))),
            2 => Ok(try!(w.write(b"Mon"))),
            3 => Ok(try!(w.write(b"Tue"))),
            4 => Ok(try!(w.write(b"Wed"))),
            5 => Ok(try!(w.write(b"Thu"))),
            6 => Ok(try!(w.write(b"Fri"))),
            7 => Ok(try!(w.write(b"Sat"))),
            _ => Err(IoError::new(::std::io::ErrorKind::InvalidData, "Day out of range"))
        }
    }
}
impl_display!(DayName);

// 3.3
// day-of-week     =   ([FWS] day-name) / obs-day-of-week
#[derive(Debug, Clone, PartialEq)]
pub struct DayOfWeek {
    pub pre_fws: Option<FWS>,
    pub day_name: DayName,
}
impl Parsable for DayOfWeek {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("DayOfWeek")); }
        let mut rem = input;
        let pre_fws = parse!(FWS, rem);
        if let Ok(dn) = parse!(DayName, rem) {
            Ok((DayOfWeek {
                pre_fws: pre_fws.ok(),
                day_name: dn,
            }, rem))
        } else {
            Err(ParseError::NotFound("DayOfWeek"))
        }
    }
}
impl Streamable for DayOfWeek {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let mut count: usize = 0;
        if let Some(ref fws) = self.pre_fws {
            count += try!(fws.stream(w));
        }
        count += try!(self.day_name.stream(w));
        Ok(count)
    }
}
impl_display!(DayOfWeek);

// 3.3
// date-time       =   [ day-of-week "," ] date time [CFWS]
#[derive(Debug, Clone, PartialEq)]
pub struct DateTime {
    pub day_of_week: Option<DayOfWeek>,
    pub date: Date,
    pub time: Time,
    pub post_cfws: Option<CFWS>
}
impl Parsable for DateTime {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("DateTime")); }
        let mut rem = input;
        let mut day_of_week: Option<DayOfWeek> = None;
        if let Ok(dow) = parse!(DayOfWeek, rem) {
            if rem.len() != 0 && rem[0]==b',' {
                rem = &rem[1..];
                day_of_week = Some(dow);
            } else {
                rem = input;
            }
        }
        if let Ok(date) = parse!(Date, rem) {
            if let Ok(time) = parse!(Time, rem) {
                let post_cfws = parse!(CFWS, rem);
                return Ok((DateTime {
                    day_of_week: day_of_week,
                    date: date,
                    time: time,
                    post_cfws: post_cfws.ok()
                }, rem));
            }
        }
        Err(ParseError::NotFound("DateTime"))
    }
}
impl Streamable for DateTime {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let mut count: usize = 0;
        if let Some(ref dow) = self.day_of_week {
            count += try!(dow.stream(w));
            count += try!(w.write(b","));
        }
        count += try!(self.date.stream(w));
        count += try!(self.time.stream(w));
        if let Some(ref cfws) = self.post_cfws {
            count += try!(cfws.stream(w));
        }
        Ok(count)
    }
}
impl_display!(DateTime);

// 3.6.4
// no-fold-literal =   "[" *dtext "]"
#[derive(Debug, Clone, PartialEq)]
pub struct NoFoldLiteral(pub DText);
impl Parsable for NoFoldLiteral {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("No-Fold Literal")); }
        let mut rem = input;
        req!(rem, b"[", input);
        if let Ok(dtext) = parse!(DText, rem) {
            req!(rem, b"]", input);
            return Ok((NoFoldLiteral(dtext), rem));
        }
        Err(ParseError::NotFound("No-Fold Literal"))
    }
}
impl Streamable for NoFoldLiteral {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        Ok(try!(w.write(b"["))
           + try!(self.0.stream(w))
           + try!(w.write(b"]")))
    }
}
impl_display!(NoFoldLiteral);

// 3.6.4
// id-right        =   dot-atom-text / no-fold-literal / obs-id-right
#[derive(Debug, Clone, PartialEq)]
pub enum IdRight {
    DotAtomText(DotAtomText),
    NoFoldLiteral(NoFoldLiteral),
}
impl Parsable for IdRight {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Id-right")); }
        if let Ok((x, rem)) = DotAtomText::parse(input) {
            Ok((IdRight::DotAtomText(x), rem))
        }
        else if let Ok((x, rem)) = NoFoldLiteral::parse(input) {
            Ok((IdRight::NoFoldLiteral(x), rem))
        }
        else {
            Err(ParseError::NotFound("Id-right"))
        }
    }
}
impl Streamable for IdRight {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        match *self {
            IdRight::DotAtomText(ref x) => x.stream(w),
            IdRight::NoFoldLiteral(ref x) => x.stream(w),
        }
    }
}
impl_display!(IdRight);

// 3.6.4
// id-left         =   dot-atom-text / obs-id-left
#[derive(Debug, Clone, PartialEq)]
pub struct IdLeft(pub DotAtomText);
impl Parsable for IdLeft {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Id-left")); }
        let mut rem = input;
        if let Ok(dat) = parse!(DotAtomText, rem) {
            return Ok((IdLeft(dat), rem));
        }
        Err(ParseError::NotFound("Id-left"))
    }
}
impl Streamable for IdLeft {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        Ok(try!(self.0.stream(w)))
    }
}
impl_display!(IdLeft);

// 3.6.4
// msg-id          =   [CFWS] "<" id-left "@" id-right ">" [CFWS]
#[derive(Debug, Clone, PartialEq)]
pub struct MsgId {
    pub pre_cfws: Option<CFWS>,
    pub id_left: IdLeft,
    pub id_right: IdRight,
    pub post_cfws: Option<CFWS>,
}
impl Parsable for MsgId {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("MsgId")); }
        let mut rem = input;
        let pre_cfws = parse!(CFWS, rem);
        req!(rem, b"<", input);
        let idl = match parse!(IdLeft, rem) {
            Err(e) => return Err(e),
            Ok(idl) => idl
        };
        req!(rem, b"@", input);
        let idr = match parse!(IdRight, rem) {
            Err(e) => return Err(e),
            Ok(idr) => idr
        };
        req!(rem, b">", input);
        let post_cfws = parse!(CFWS, rem);
        Ok((MsgId {
            pre_cfws: pre_cfws.ok(),
            id_left: idl,
            id_right: idr,
            post_cfws: post_cfws.ok(),
        }, rem))
    }
}
impl Streamable for MsgId {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        let mut count: usize = 0;
        if let Some(ref cfws) = self.pre_cfws {
            count += try!(cfws.stream(w));
        }
        count += try!(w.write(b"<"));
        count += try!(self.id_left.stream(w));
        count += try!(w.write(b"@"));
        count += try!(self.id_right.stream(w));
        count += try!(w.write(b">"));
        if let Some(ref cfws) = self.post_cfws {
            count += try!(cfws.stream(w));
        }
        Ok(count)
    }
}
impl_display!(MsgId);

// 3.6.7
// received-token  =   word / angle-addr / addr-spec / domain
#[derive(Debug, Clone, PartialEq)]
pub enum ReceivedToken {
    Word(Word),
    AngleAddr(AngleAddr),
    AddrSpec(AddrSpec),
    Domain(Domain),
}
impl Parsable for ReceivedToken {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        if input.len() == 0 { return Err(ParseError::Eof("Received Token")); }
        if let Ok((x, rem)) = Word::parse(input) {
            Ok((ReceivedToken::Word(x), rem))
        }
        else if let Ok((x, rem)) = AngleAddr::parse(input) {
            Ok((ReceivedToken::AngleAddr(x), rem))
        }
        else if let Ok((x, rem)) = AddrSpec::parse(input) {
            Ok((ReceivedToken::AddrSpec(x), rem))
        }
        else if let Ok((x, rem)) = Domain::parse(input) {
            Ok((ReceivedToken::Domain(x), rem))
        }
        else {
            Err(ParseError::NotFound("Received Token"))
        }
    }
}
impl Streamable for ReceivedToken {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        match *self {
            ReceivedToken::Word(ref x) => x.stream(w),
            ReceivedToken::AngleAddr(ref x) => x.stream(w),
            ReceivedToken::AddrSpec(ref x) => x.stream(w),
            ReceivedToken::Domain(ref x) => x.stream(w),
        }
    }
}
impl_display!(ReceivedToken);

// 3.6.7
// path            =   angle-addr / ([CFWS] "<" [CFWS] ">" [CFWS])
#[derive(Debug, Clone, PartialEq)]
pub enum Path {
    AngleAddr(AngleAddr),
    Other(Option<CFWS>, Option<CFWS>, Option<CFWS>),
}
impl Parsable for Path {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        let mut rem = input;
        if let Ok(aa) = parse!(AngleAddr, rem) {
            return Ok((Path::AngleAddr(aa), rem));
        }
        let c1 = parse!(CFWS, rem).ok();
        req!(rem, b"<", input);
        let c2 = parse!(CFWS, rem).ok();
        req!(rem, b">", input);
        let c3 = parse!(CFWS, rem).ok();
        Ok((Path::Other(c1,c2,c3), rem))
    }
}
impl Streamable for Path {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        match *self {
            Path::AngleAddr(ref aa) => aa.stream(w),
            Path::Other(ref c1, ref c2, ref c3) => {
                let mut count: usize = 0;
                if let &Some(ref c) = c1 {
                    count += try!(c.stream(w));
                }
                count += try!(w.write(b"<"));
                if let &Some(ref c) = c2 {
                    count += try!(c.stream(w));
                }
                count += try!(w.write(b">"));
                if let &Some(ref c) = c3 {
                    count += try!(c.stream(w));
                }
                Ok(count)
            }
        }
    }
}
impl_display!(Path);

// 3.6.8
// ftext           =   %d33-57 /          ; Printable US-ASCII
//                     %d59-126           ;  characters not including
//                                        ;  ":".
#[inline]
pub fn is_ftext(c: u8) -> bool { (c>=33 && c<=57) || (c>=59 && c<=126) }
def_cclass!(FText, is_ftext);
impl_display!(FText);

// 3.6.8
// field-name      =   1*ftext
#[derive(Debug, Clone, PartialEq)]
pub struct FieldName(pub FText);
impl Parsable for FieldName {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        let mut rem = input;
        if let Ok(ftext) = parse!(FText, rem) {
            Ok((FieldName(ftext), rem))
        } else {
            Err(ParseError::NotFound("Field Name"))
        }
    }
}
impl Streamable for FieldName {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        self.0.stream(w)
    }
}
impl_display!(FieldName);