utf8conv 0.1.0

A UTF8 / Unicode Converter for no_std
Documentation
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
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
// Copyright 2022 Thomas Wang and utf8conv contributors
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// This is the representation of the replacement character in UTF8 encoding.

/// replacement character (UTF32)
pub const REPLACE_UTF32:u32 = 0xFFFD;

/// byte 1 of replacement char in UTF8
pub const REPLACE_PART1:u8 = 0xEFu8;

/// byte 2 of replacement char in UTF8
pub const REPLACE_PART2:u8 = 0xBFu8;

/// byte 3 of replacement char in UTF8
pub const REPLACE_PART3:u8 = 0xBDu8;

/// leading bits of byte 1 for type 2 decode
const TYPE2_PREFIX:u32 = 0b1100_0000u32;

/// leading bits of byte 1 for type 3 decode
const TYPE3_PREFIX:u32 = 0b1110_0000u32;

/// leading bits of byte 1 for type 4 decode
const TYPE4_PREFIX:u32 = 0b1111_0000u32;

/// leading bits of byte 2 and onwards
const BYTE2_PREFIX:u32 = 0b1000_0000u32;

/// Unicode Byte Order Marker character
const BOM:char = '\u{FEFF}';

/// carriage return character
const CR:char = '\r';

/// new-line character
const NL:char = '\n';

// (v & SIX_ONES) << 6 is the same as
// (v << 6) & SIX_ONES_SHIFTED
// This breaks up the pattern of using shift units in the same cycle.

/// 6 bits shifted 6 digits
const SIX_ONES_SHIFTED:u32 = 0b111111000000u32;

/// 0x3F bit mask
const SIX_ONES:u32 = 0b111111u32;

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
/// Indication for needing more data when parameter value greater than 0,
/// or end of data condition when parameter value is 0.
///
/// (These are not really error conditions.)
pub enum MoreEnum {

    /// 0: end of data, greater than 0: need more data
    More(u32),
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
/// Indication for the type of UTF8 decoding when converting
/// from UTF32 to UTF8
pub enum Utf8TypeEnum {
    /// 1 byte type
    Type1(u8),

    /// 2 byte type
    Type2((u8,u8)),

    /// 3 byte type
    Type3((u8,u8,u8)),

    /// 4 byte type
    Type4((u8,u8,u8,u8)),

    /// invalid codepoint; substituted with replacement characters
    Type0((u8,u8,u8)),
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
/// Utf8EndEnum is the result container for the UTF8 to char
/// finite state machine.
pub enum Utf8EndEnum {

    /// bad decode with failure sequence length: 1, 2, or 3
    BadDecode(u32),

    /// Finished state with a valid codepoint
    Finish(u32),

    /// not enough characters: type unknown
    TypeUnknown,
}


#[inline]
/// Classify an UTF32 value into the type of UTF8 it belongs.
///
/// Returning Utf8TypeEnum::Type 1 to 4 indicates the sequence length.
///
/// Returning Utf8TypeEnum::Type0 indicates error.
/// # Arguments
/// * `code` - the codepoint to be classified
pub fn classify_utf32(code: u32) -> Utf8TypeEnum {
    if code < 0x80u32 {
        Utf8TypeEnum::Type1(code as u8)
    }
    else if code < 0x800u32 {
        let v1:u8 = ((code >> 6) + TYPE2_PREFIX) as u8;
        let v2:u8 = ((code & SIX_ONES) + BYTE2_PREFIX) as u8;
        Utf8TypeEnum::Type2((v1,v2))
    }
    else if (code >= 0xD800u32) && (code < 0xE000u32) {
        // Illegal UTF16 surrogate range
        Utf8TypeEnum::Type0((REPLACE_PART1, REPLACE_PART2, REPLACE_PART3))
    }
    else if code < 0x10000u32 {
        if code == REPLACE_UTF32 {
            // Treat it the same whether it is a fresh invalid codepoint
            // or an old one from the past.
            Utf8TypeEnum::Type0((REPLACE_PART1, REPLACE_PART2, REPLACE_PART3))
        }
        else {
            let v1:u8 = ((code >> 12) + TYPE3_PREFIX) as u8;
            let v2:u8 = (((code & SIX_ONES_SHIFTED) >> 6) + BYTE2_PREFIX) as u8;
            let v3:u8 = ((code & SIX_ONES) + BYTE2_PREFIX) as u8;
            Utf8TypeEnum::Type3((v1,v2,v3))
        }
    }
    else if code < 0x110000u32 {
        let v1:u8 = ((code >> 18) + TYPE4_PREFIX) as u8;
        let v2:u8 = (((code >> 12) & SIX_ONES) + BYTE2_PREFIX) as u8;
        let v3:u8 = (((code & SIX_ONES_SHIFTED) >> 6) + BYTE2_PREFIX) as u8;
        let v4:u8 = ((code & SIX_ONES) + BYTE2_PREFIX) as u8;
        Utf8TypeEnum::Type4((v1,v2,v3,v4))
    }
    else {
        // beyond valid UTF32 range
        Utf8TypeEnum::Type0((REPLACE_PART1, REPLACE_PART2, REPLACE_PART3))
    }
}


/*
Technical notes written by Henri Sivonen, selectely quoted

Unicode 9.0.0 (page 127) says: “An ill-formed subsequence consisting of more
than one code unit could be treated as a single error or as multiple errors.
For example, in processing the UTF-8 code unit sequence <F0 80 80 41>,
the only formal requirement mandated by Unicode conformance for a converter
is that the <41> be processed and correctly interpreted as <U+0041>.
The converter could return <U+FFFD, U+0041>, handling <F0 80 80> as a single
error, or <U+FFFD, U+FFFD, U+FFFD, U+0041>, handling each byte of <F0 80 80>
as a separate error, or could take other approaches to signalling <F0 80 80>
as an ill-formed code unit subsequence.” So as far as Unicode is concerned,
any number from one to the number of bytes in the number of bogus bytes
(inclusive) is OK. In other words, the precise number is
implementation-defined as far as Unicode is concerned.

> However, for the best compatibility with existing software, implementing
> the conversion with a finite state machine was the typical approach.

Code Points         First Byte   Second Byte  Third Byte  Fourth Byte
U+0000..U+007F      00..7F
>                   action 0

U+0080..U+07FF      C2..DF       80..bf
>                   action 1     action 9

U+0800..U+0FFF      E0           A0..bf       80..bf
>                   action 2     action 14    action 17

U+1000..U+CFFF      E1..EC       80..bf       80..bf
>                   action 3     action 10    action (17)

U+D000..U+D7FF      ED           80..9F       80..bf
>                   action 4     action 15    action (17)

U+E000..U+FFFF      EE..EF       80..bf       80..bf
>                   action 5     action 11    action 20 (containing FFFD)

U+10000..U+3FFFF    F0           90..bf       80..bf      80..bf
>                   action 6     action 16    action 21   action 24

U+40000..U+FFFFF    F1..F3       80..bf       80..bf      80..bf
>                   action 7     action 12    action (21) action (24)

U+100000..U+10FFFF  F4           80..8F       80..bf      80..bf
>                   action 8     action 13    action (21) action (24)

> The action number with parenthesis are duplicated actions.
> action 0: out = v1
> action 1: out = v1 & ox1F;
> action 2 to 5: out = v1 & 0xF;
> action 6 to 8: out = v1 & 0x7;
> action 9 to 13: out = (arg << 6)+(v2 & 0x3F)
> action 14: out = (arg << 6)+(v2 & 0x3F)
> action 15: out = (arg << 6)+(v2 & 0x3F)
> action 16: out = (arg << 6)+(v2 & 0x3F)
> action 17: out = (arg << 6)+(v3 & 0x3F)
> action 20: out = (arg << 6)+(v3 & 0x3F)
> action 21: out = (arg << 6)+(v3 & 0x3F)
> action 24: out = (arg << 6)+(v4 & 0x3F)
>
>
> If buffer is empty then it could be 'end of data' or need to signal
> for more data.
>
> We need to ensure the required number of bytes are available when
> the first byte is checked.  Otherwise it is TypeUnknown. (partial data)
>
> Different tituation when at the last buffer - we go in to process the
> remaining bytes even when we could run out mid-stream.
> This avoids a quote escaping attack, such as quote - F0 - quote - newline

*/

use core::iter::Iterator;

use crate::utf8conv::buf::EightBytes;


// Action 9 and 10 are different; action 9 can be an end state, while
// action 10 cannot.

#[inline]
/// Finite state machine action 9; expect 80 to bf
fn byte2_action9(mybuf: & mut EightBytes, arg: u32) -> Utf8EndEnum {
    match mybuf.front() {
        Option::Some(v) => {
            let v2 = v as u32;
            // println!("in action 9 with v2={:#02x}", v2);
            if (v2 >= 0x80) && (v2 <= 0xbf) {
                mybuf.pop_front(); // advance
                Utf8EndEnum::Finish((arg << 6)+(v2 & 0x3F))
            }
            else {
                // println!("not within 0x80 and 0xbf");
                Utf8EndEnum::BadDecode(1)
            }
        }
        Option::None => {
            // println!("TypeUnknown");
            Utf8EndEnum::TypeUnknown
        }
    }
}

// Action 10 and 12 are different; action 10 is for a 3 byte sequence,
// while action 12 is for a 4 byte sequence.

/// Finite state machine action 10; expect 80 to bf
fn byte2_action10(mybuf: & mut EightBytes, arg: u32) -> Utf8EndEnum {
    match mybuf.front() {
        Option::Some(v) => {
            let v2 = v as u32;
            // println!("in action 10 with v2={:#02x}", v2);
            if (v2 >= 0x80) && (v2 <= 0xbf) {
                mybuf.pop_front(); // advance
                byte3_action17(mybuf, (arg << 6)+(v2 & 0x3F))
            }
            else {
                // println!("not within 0x80 and 0xbf");
                Utf8EndEnum::BadDecode(1)
            }
        }
        Option::None => {
            // println!("TypeUnknown");
            Utf8EndEnum::TypeUnknown
        }
    }
}

/// Finite state machine action 11; expect 80 to bf
/// Codepoint E000 to FFFF
fn byte2_action11(mybuf: & mut EightBytes, arg: u32) -> Utf8EndEnum {
    match mybuf.front() {
        Option::Some(v) => {
            let v2 = v as u32;
            // println!("in action 10 with v2={:#02x}", v2);
            if (v2 >= 0x80) && (v2 <= 0xbf) {
                mybuf.pop_front(); // advance
                byte3_action20(mybuf, (arg << 6)+(v2 & 0x3F))
            }
            else {
                // println!("not within 0x80 and 0xbf");
                Utf8EndEnum::BadDecode(1)
            }
        }
        Option::None => {
            // println!("TypeUnknown");
            Utf8EndEnum::TypeUnknown
        }
    }
}

/// Finite state machine action 12; expect 80 to bf
fn byte2_action12(mybuf: & mut EightBytes, arg: u32) -> Utf8EndEnum {
    match mybuf.front() {
        Option::Some(v) => {
            let v2 = v as u32;
            // println!("in action 12 with v2={:#02x}", v2);
            if (v2 >= 0x80) && (v2 <= 0xbf) {
                mybuf.pop_front(); // advance
                byte3_action21(mybuf, (arg << 6)+(v2 & 0x3F))
            }
            else {
                // println!("not within 0x80 and 0xbf");
                Utf8EndEnum::BadDecode(1)
            }
        }
        Option::None => {
            // println!("TypeUnknown");
            Utf8EndEnum::TypeUnknown
        }
    }
}

/// Finite state machine action 13; expect 80 to 8F
fn byte2_action13(mybuf: & mut EightBytes, arg: u32) -> Utf8EndEnum {
    match mybuf.front() {
        Option::Some(v) => {
            let v2 = v as u32;
            // println!("in action 13 with v2={:#02x}", v2);
            if (v2 >= 0x80) && (v2 <= 0x8F) {
                mybuf.pop_front(); // advance
                byte3_action21(mybuf, (arg << 6)+(v2 & 0x3F))
            }
            else {
                // println!("not within 0x80 and 0x8F");
                Utf8EndEnum::BadDecode(1)
            }
        }
        Option::None => {
            // println!("TypeUnknown");
            Utf8EndEnum::TypeUnknown
        }
    }
}

#[inline]
/// Finite state machine action 14; expect A0 to bf
fn byte2_action14(mybuf: & mut EightBytes, arg: u32) -> Utf8EndEnum {
    match mybuf.front() {
        Option::Some(v) => {
            let v2 = v as u32;
            // println!("in action 14 with v2={:#02x}", v2);
            if (v2 >= 0xA0) && (v2 <= 0xbf) {
                mybuf.pop_front(); // advance
                byte3_action17(mybuf, (arg << 6)+(v2 & 0x3F))
            }
            else {
                // println!("not within 0xA0 and 0xbf");
                Utf8EndEnum::BadDecode(1)
            }
        }
        Option::None => {
            // println!("TypeUnknown");
            Utf8EndEnum::TypeUnknown
        }
    }
}

/// Finite state machine action 15; expect 80 to 9F
fn byte2_action15(mybuf: & mut EightBytes, arg: u32) -> Utf8EndEnum {
    match mybuf.front() {
        Option::Some(v) => {
            let v2 = v as u32;
            // println!("in action 15 with v2={:#02x}", v2);
            if (v2 >= 0x80) && (v2 <= 0x9F) {
                mybuf.pop_front(); // advance
                byte3_action17(mybuf, (arg << 6)+(v2 & 0x3F))
            }
            else {
                // println!("not within 0x80 and 0x9F");
                Utf8EndEnum::BadDecode(1)
            }
        }
        Option::None => {
            // println!("TypeUnknown");
            Utf8EndEnum::TypeUnknown
        }
    }
}

/// Finite state machine action 16; expect 90 to bf
fn byte2_action16(mybuf: & mut EightBytes, arg: u32) -> Utf8EndEnum {
    match mybuf.front() {
        Option::Some(v) => {
            let v2 = v as u32;
            // println!("in action 16 with v2={:#02x}", v2);
            if (v2 >= 0x90) && (v2 <= 0xbf) {
                mybuf.pop_front(); // advance
                byte3_action21(mybuf, (arg << 6)+(v2 & 0x3F))
            }
            else {
                // println!("not within 0x90 and 0xbf");
                Utf8EndEnum::BadDecode(1)
            }
        }
        Option::None => {
            // println!("TypeUnknown");
            Utf8EndEnum::TypeUnknown
        }
    }
}

#[inline]
/// Finite state machine action 17; expect 80 to bf
fn byte3_action17(mybuf: & mut EightBytes, arg: u32) -> Utf8EndEnum {
    match mybuf.front() {
        Option::Some(v) => {
            let v3 = v as u32;
            // println!("in action 17 with v3={:#02x}", v3);
            if (v3 >= 0x80) && (v3 <= 0xbf) {
                mybuf.pop_front(); // advance
                Utf8EndEnum::Finish((arg << 6)+(v3 & 0x3F))
            }
            else {
                // println!("not within 0x80 and 0xbf");
                Utf8EndEnum::BadDecode(2)
            }
        }
        Option::None => {
            // println!("TypeUnknown");
            Utf8EndEnum::TypeUnknown
        }
    }
}

#[inline]
/// Finite state machine action 20 expect 80 to bf
/// Codepoint E000 to FFFF
fn byte3_action20(mybuf: & mut EightBytes, arg: u32) -> Utf8EndEnum {
    match mybuf.front() {
        Option::Some(v) => {
            let v3 = v as u32;
            // println!("in action 20 with v3={:#02x}", v3);
            if (v3 >= 0x80) && (v3 <= 0xbf) {
                mybuf.pop_front(); // advance
                let codepoint = (arg << 6) + (v3 & 0x3F);
                if codepoint == REPLACE_UTF32 {
                    // special processing logic for replacement character:
                    //
                    // Logic was that a replacement character represents a
                    // former invalid encoding or decoding of a codepoint.
                    // We treat them the same whether this was triggered
                    // fresh or from historical data source.
                    //
                    // BadDecode(3) means this event was detected after
                    // parsing 3 bytes. (EF, BF, BD)
                    Utf8EndEnum::BadDecode(3)
                }
                else {
                    Utf8EndEnum::Finish(codepoint)
                }
            }
            else {
                // println!("not within 0x80 and 0xbf");
                Utf8EndEnum::BadDecode(2)
            }
        }
        Option::None => {
            // println!("TypeUnknown");
            Utf8EndEnum::TypeUnknown
        }
    }
}

#[inline]
/// Finite state machine action 21; expect 80 to bf
fn byte3_action21(mybuf: & mut EightBytes, arg: u32) -> Utf8EndEnum {
    match mybuf.front() {
        Option::Some(v) => {
            let v3 = v as u32;
            // println!("in action 21 with v3={:#02x}", v3);
            if (v3 >= 0x80) && (v3 <= 0xbf) {
                mybuf.pop_front(); // advance
                byte4_action24(mybuf, (arg << 6)+(v3 & 0x3F))
            }
            else {
                // println!("not within 0x80 and 0xbf");
                Utf8EndEnum::BadDecode(2)
            }
        }
        Option::None => {
            // println!("TypeUnknown");
            Utf8EndEnum::TypeUnknown
        }
    }
}

#[inline]
/// Finite state machine action 24; expect 80 to bf
fn byte4_action24(mybuf: & mut EightBytes, arg: u32) -> Utf8EndEnum {
    match mybuf.front() {
        Option::Some(v) => {
            let v4 = v as u32;
            // println!("in action 24 with v4={:#02x}", v4);
            if (v4 >= 0x80) && (v4 <= 0xbf) {
                mybuf.pop_front(); // advance
                Utf8EndEnum::Finish((arg << 6)+(v4 & 0x3F))
            }
            else {
                // println!("not within 0x80 and 0xbf");
                Utf8EndEnum::BadDecode(3)
            }
        }
        Option::None => {
            // println!("TypeUnknown");
            Utf8EndEnum::TypeUnknown
        }
    }
}

/// Decode from UTF8 to Unicode code point using a finate state machine.
///
/// # Arguments
///
/// * `mybuf` - contains the bytes to be decoded
///
/// * `last_buffer` - is true when we are working on the last byte buffer.
///
/// When 'last_buffer' is false, with additional buffers to be processed,
/// then the parser would refuse to work on potential partial decodes,
/// and returns Utf8EndEnum::TypeUnknown to ask for more data.
///
/// When 'last_buffer' is true, with no more data to process than
/// what is available in 'mybuf', then partial decodes results in
/// Utf8EndEnum:BadDecode(n) where n is length of error from 1 to 3 bytes.
pub fn utf8_decode(mybuf: & mut EightBytes, last_buffer: bool) -> Utf8EndEnum {
    match mybuf.front() {
        Option::Some(v) => {
            let v1 = v as u32;
            // println!("in start state with v1={:#02x} and len()={}", v1, mybuf.len());
            if v1 < 0xE0 {
                if v1 < 0xC2 {
                    mybuf.pop_front();
                    if v1 < 0x80 {
                        // Action 0
                        // 1 byte format: code point from 0x0 to 0x7F
                        // println!("in action 0 with v1={:#02x}", v1);
                        Utf8EndEnum::Finish(v1)
                    }
                    else {
                        // 80 to C1: not valid first byte
                        // println!("80 to C1 bad decode");
                        Utf8EndEnum::BadDecode(1)
                    }
                }
                else {
                    // Byte 1 is between 0xC2 and 0xDF
                    // 2 byte format
                    if (mybuf.len() < 2) && ! last_buffer {
                        // We wait for more bytes if not the last buffer.
                        // Our design cannot back-out procesed bytes.
                        // println!("TypeUnknown");
                        Utf8EndEnum::TypeUnknown
                    }
                    else {
                        // Action 1
                        // println!("in action 1 with v1={:#02x}", v1);
                        mybuf.pop_front();
                        byte2_action9(mybuf, v1 & 0x1F)
                    }
                }
            }
            else {
                if v1 < 0xF0 {
                    // 3 byte format
                    // Byte 1 is between 0xE0 and 0xEF
                    if (mybuf.len() < 3) && ! last_buffer {
                        // We wait for more bytes if not the last buffer.
                        // Our design cannot back-out procesed bytes.
                        // println!("TypeUnknown");
                        Utf8EndEnum::TypeUnknown
                    }
                    else if v1 < 0xED {
                        mybuf.pop_front();
                        if v1 == 0xE0 {
                            // Action 2
                            // v1 is 0xE0.
                            // println!("in action 2 with v1={:#02x}", v1);
                            byte2_action14(mybuf, v1 & 0xF)
                        }
                        else {
                            // Action 3
                            // v1 is between 0xE1 and 0xEC.
                            // println!("in action 3 with v1={:#02x}", v1);
                            byte2_action10(mybuf, v1 & 0xF)
                        }
                    }
                    else {
                        mybuf.pop_front();
                        if v1 == 0xED {
                            // Action 4
                            // println!("in action 4 with v1={:#02x}", v1);
                            byte2_action15(mybuf, v1 & 0xF)
                        }
                        else {
                            // Action 5
                            // v1 is 0xEE or 0xEF.
                            // println!("in action 5 with v1={:#02x}", v1);
                            byte2_action11(mybuf, v1 & 0xF)
                        }
                    }
                }
                else {
                    // 4 byte cases if byte 1 is between 0xF0 and 0xF4
                    if v1 > 0xF4 {
                        // codepoint too large
                        // println!("greater than F4 bad decode");
                        mybuf.pop_front();
                        Utf8EndEnum::BadDecode(1)
                    }
                    else if (mybuf.len() < 4) && ! last_buffer {
                        // We wait for more bytes if not the last buffer.
                        // Our design cannot back-out procesed bytes.
                        // println!("TypeUnknown");
                        Utf8EndEnum::TypeUnknown
                    }
                    else {
                        mybuf.pop_front();
                        if v1 == 0xF0 {
                            // Action 6
                            // println!("in action 6 with v1={:#02x}", v1);
                            byte2_action16(mybuf, v1 & 0x7)
                        }
                        else if v1 < 0xF4 {
                            // Action 7
                            // Byte 1 is between 0xF1 and 0xF3.
                            // println!("in action 7 with v1={:#02x}", v1);
                            byte2_action12(mybuf, v1 & 0x7)
                        }
                        else {
                            // Action 8
                            // Byte 1 is 0xF4.
                            // println!("in action 8 with v1={:#02x}", v1);
                            byte2_action13(mybuf, v1 & 0x7)
                        }
                    }
                }
            }
        }
        Option::None => {
            // println!("TypeUnknown");
            Utf8EndEnum::TypeUnknown
        }
    }
}


/// Most iterators on arrays allocated on the stack returns a reference
/// in order to save memory.  For our converter use-case this is a
/// problem because our conversion result is a temporary value that
/// is best delivered as a value, not as a reference.
/// This could cause two iterators failing to connect from one output to
/// the next input.
///
/// Proposed types of converters:
///
/// utf8 reference -> char (direct route)
///
/// char reference -> utf8 (another direct route)
///
/// char refernce -> char
///
/// utf32 reference -> utf32
///
/// utf8 reference -> utf8
///
/// char -> utf32
///
/// utf32 -> utf8
///
/// utf8 -> char
///
/// char reference to char iterator struct
pub struct CharRefToCharStruct<'b> {

    /// the source iterator
    my_borrow_mut_iter: &'b mut dyn Iterator<Item = &'b char>,
}

/// an adapter iterator to convert a char reference iterator to char iterator
impl<'b> Iterator for CharRefToCharStruct<'b> {
    type Item=char;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match self.my_borrow_mut_iter.next() {
            Option::None => { Option::None }
            Option::Some(v) => { Option::Some(* v) }
        }
    }

    /// sizing hint for iterator, with a lower bound and optional upperbound
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.my_borrow_mut_iter.size_hint()
    }
}

/// Function char_ref_iter_to_char_iter() takes a mutable reference to
/// a char reference iterator, and return a char iterator in its place.
///
/// # Arguments
///
/// * `input` - a mutable reference to a char reference iterator
#[inline]
pub fn char_ref_iter_to_char_iter<'a, I: 'a + Iterator>(input: &'a mut I)
-> CharRefToCharStruct<'a>
where I: Iterator<Item = &'a char>, {
    CharRefToCharStruct {
        my_borrow_mut_iter: input,
    }
}

/// UTF32 reference to UTF32 iterator struct
pub struct Utf32RefToUtf32Struct<'b> {

    /// the source iterator
    my_borrow_mut_iter: &'b mut dyn Iterator<Item = &'b u32>,
}

/// an adapter iterator to convert a UTF32 reference iterator to UTF32 iterator
impl<'b> Iterator for Utf32RefToUtf32Struct<'b> {
    type Item=u32;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match self.my_borrow_mut_iter.next() {
            Option::None => { Option::None }
            Option::Some(v) => { Option::Some(* v) }
        }
    }

    /// sizing hint for iterator, with a lower bound and optional upperbound
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.my_borrow_mut_iter.size_hint()
    }
}

/// Function utf32_ref_iter_to_utf32_iter() takes a mutable reference to
/// a UTF32 reference iterator, and return a UTF32 iterator in its place.
///
/// # Arguments
///
/// * `input` - a mutable reference to a UTF32 reference iterator
#[inline]
pub fn utf32_ref_iter_to_utf32_iter<'a, I: 'a + Iterator>(input: &'a mut I)
-> Utf32RefToUtf32Struct<'a>
where I: Iterator<Item = &'a u32>, {
    Utf32RefToUtf32Struct {
        my_borrow_mut_iter: input,
    }
}

/// UTF8 reference to UTF8 iterator struct
pub struct Utf8RefToUtf8Struct<'b> {

    /// the source iterator
    my_borrow_mut_iter: &'b mut dyn Iterator<Item = &'b u8>,
}

/// an adapter iterator to convert a UTF8 reference iterator to UTF8 iterator
impl<'b> Iterator for Utf8RefToUtf8Struct<'b> {
    type Item=u8;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match self.my_borrow_mut_iter.next() {
            Option::None => { Option::None }
            Option::Some(v) => { Option::Some(* v) }
        }
    }

    /// sizing hint for iterator, with a lower bound and optional upperbound
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.my_borrow_mut_iter.size_hint()
    }
}

/// Function utf8_ref_iter_to_utf8_iter() takes a mutable reference to
/// a UTF8 reference iterator, and return a UTF8 iterator in its place.
///
/// # Arguments
///
/// * `input` - a mutable reference to a UTF8 reference iterator
#[inline]
pub fn utf8_ref_iter_to_utf8_iter<'a, I: 'a + Iterator>(input: &'a mut I)
-> Utf8RefToUtf8Struct<'a>
where I: Iterator<Item = &'a u8>, {
    Utf8RefToUtf8Struct {
        my_borrow_mut_iter: input,
    }
}

/// char to UTF32 iterator struct
pub struct CharToUtf32Struct<'b> {

    /// the source iterator
    my_borrow_mut_iter: &'b mut dyn Iterator<Item = char>,
}

/// an adapter iterator to convert a char iterator to UTF32 iterator
impl<'b> Iterator for CharToUtf32Struct<'b> {
    type Item=u32;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match self.my_borrow_mut_iter.next() {
            Option::None => { Option::None }
            Option::Some(v) => { Option::Some(v as u32) }
        }
    }

    /// sizing hint for iterator, with a lower bound and optional upperbound
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.my_borrow_mut_iter.size_hint()
    }
}

/// Function char_iter_to_utf32_iter() takes a mutable reference to
/// a char iterator, and return a UTF32 iterator in its place.
///
/// # Arguments
///
/// * `input` - a mutable reference to a char iterator
#[inline]
pub fn char_iter_to_utf32_iter<'a, I: 'a + Iterator>(input: &'a mut I)
-> CharToUtf32Struct<'a>
where I: Iterator<Item = char>, {
    CharToUtf32Struct {
        my_borrow_mut_iter: input,
    }
}

/// BomAndCarriageReturnFilterStruct contains states tracking
/// iterator filtering states of Byte Order Mark, and Carriage Return
/// characters.
pub struct BomAndCarriageReturnFilterStruct<'b> {

    /// the source iterator
    my_borrow_mut_iter: &'b mut dyn Iterator<Item = char>,

    /// true at the start of iterator stream
    my_start_stream: bool,

    /// last character was a carriage return
    my_prev_cr: bool,
}

/// an adapter iterator to filter BOM and Carriage Return characters
impl<'b> Iterator for BomAndCarriageReturnFilterStruct<'b> {
    type Item=char;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            match self.my_borrow_mut_iter.next() {
                Option::None => {
                    break Option::None;
                }
                Option::Some(v) => {
                    if self.my_start_stream {
                        if v == BOM {
                            self.my_start_stream = false; // no longer at start
                            continue; // skip BOM
                        }
                        else {
                            self.my_start_stream = false;
                        }
                    }
                    if self.my_prev_cr {
                        // Previous character was a carriage return and
                        // already substituted with new-line.
                        if v == NL {
                            // CR - NL pair found
                            self.my_prev_cr = false;
                            continue;
                        }
                        else if v == CR {
                            // CR - CR found
                            // substitue the second CR with NL
                            break Option::Some(NL);
                        }
                        else {
                            // CR - non-line-end-char
                            self.my_prev_cr = false;
                        }
                    }
                    else if v == CR {
                        self.my_prev_cr = true;
                        // substitute CR with NL
                        break Option::Some(NL);
                    }
                    break Option::Some(v);
                }
            }
        }
    }

    /// sizing hint for iterator, with a lower bound and optional upperbound
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.my_borrow_mut_iter.size_hint()
    }
}

/// Function filter_bom_and_cr_iter() takes a mutable reference to
/// a char iterator, and return a filtered char iterator in its place.
///
/// The output iterator will remove a potential Byte Order Mark at
/// the beginning of a stream.
///
/// The output iterator will standardize on newline character line
/// ending convention, removing carriage returns and substituting them
/// with newlines.
///
/// # Arguments
///
/// * `input` - a mutable reference to a char iterator
#[inline]
pub fn filter_bom_and_cr_iter<'a, I: 'a + Iterator>(input: &'a mut I)
-> BomAndCarriageReturnFilterStruct<'a>
where I: Iterator<Item = char>, {
    BomAndCarriageReturnFilterStruct {
        my_borrow_mut_iter: input,
        my_start_stream: true,
        my_prev_cr: false,
    }
}

/// Common operations for UTF conversion parsers
pub trait UtfParserCommon {

    /// Reset all parser states to the initial value.
    /// Last buffer indication is set to true.
    /// Invalid decodes indication is cleared.
    fn reset_parser(&mut self);

    /// If argument `b` is true, then any input buffer to be presented will
    /// be the last buffer.
    fn set_is_last_buffer(&mut self, b: bool);

    /// Returns the last input buffer flag.
    fn is_last_buffer(&self) -> bool;

    /// This function signals the occurrence of an invalid conversion sequence.
    fn signal_invalid_sequence(& mut self);

    /// This function returns true if invalid conversion sequence occurred
    /// in this parsing stream.
    fn has_invalid_sequence(&self) -> bool;

    /// This function resets the invalid sequence state.
    fn reset_invalid_sequence(& mut self);
}

/// Provides conversion functions from UTF8 to char or UTF32
#[derive(Debug, Clone, Copy)]
pub struct FromUtf8 {
    my_buf: EightBytes,
    my_last_buffer: bool,
    my_invalid_sequence: bool,
}

/// Provides conversion functions from char or UTF32 to UTF8
#[derive(Debug, Clone, Copy)]
pub struct FromUnicode {
    my_buf: EightBytes,
    my_last_buffer: bool,
    my_invalid_sequence: bool,
}

/// adapter iterator converting from an UTF8 iterator to a char iterator
/// (This iterator contains a mutable borrow to the launching
/// FromUtf8 object while this iterator is alive.)
pub struct Utf8IterToCharIter<'p> {

    /// the source iterator
    my_borrow_mut_iter: &'p mut dyn Iterator<Item = u8>,

    /// mutable reference to FromUtf8 object
    my_info: &'p mut FromUtf8,
}

/// adapter iterator converting from an UTF32 iterator to an UTF8 iterator
/// (This iterator contains a mutable borrow to the launching
/// FromUnicode object while this iterator is alive.)
pub struct Utf32IterToUtf8Iter<'q> {

    /// the source iterator
    my_borrow_mut_iter: &'q mut dyn Iterator<Item = u32>,

    /// mutable reference to FromUnicode object
    my_info: &'q mut FromUnicode,
}

/// adapter iterator converting from an UTF8 reference iterator to char iterator
/// (This iterator contains a mutable borrow to the launching
/// FromUtf8 object while this iterator is alive.)
pub struct Utf8RefIterToCharIter<'r> {

    /// the source iterator
    my_borrow_mut_iter: &'r mut dyn Iterator<Item = &'r u8>,

    /// mutable reference to FromUtf8 object
    my_info: &'r mut FromUtf8,
}

/// adapter iterator converting from a char reference iterator to an UTF8 iterator
/// (This iterator contains a mutable borrow to the launching
/// FromUnicode object while this iterator is alive.)
pub struct CharRefIterToUtf8Iter<'s> {

    /// the source iterator
    my_borrow_mut_iter: &'s mut dyn Iterator<Item = &'s char>,

    /// mutable reference to FromUnicode object
    my_info: &'s mut FromUnicode,
}

/// Implementations of common operations for FromUtf8
impl<'b> UtfParserCommon for FromUtf8 {

    #[inline]
    /// If argument `b` is true, then any input buffer to be presented will
    /// be the last buffer.
    fn set_is_last_buffer(&mut self, b: bool) {
        self.my_last_buffer = b;
    }

    #[inline]
    /// Returns the last input buffer flag.
    fn is_last_buffer(&self) -> bool {
        self.my_last_buffer
    }

    #[inline]
    /// This function returns true if invalid UTF8 sequence occurred
    /// in this parsing stream.
    fn has_invalid_sequence(&self) -> bool {
        self.my_invalid_sequence
    }

    #[inline]
    /// This function signals the occurrence of an invalid UTF8 sequence.
    fn signal_invalid_sequence(&mut self) {
        self.my_invalid_sequence = true;
    }

    #[inline]
    /// This function resets the invalid decodes state.
    fn reset_invalid_sequence(& mut self) {
        self.my_invalid_sequence = false;
    }

    #[inline]
    /// Reset all parser states to the initial value.
    /// Last buffer indication is set to true.
    /// Invalid decodes indication is cleared.
    fn reset_parser(&mut self) {
        // Drain our buffer.
        self.my_buf.clear();
        self.set_is_last_buffer(true);
        self.reset_invalid_sequence();
    }

}

/// Implementations of common operations for FromUnicode
impl<'b> UtfParserCommon for FromUnicode {

    #[inline]
    /// If argument `b` is true, then any input buffer to be presented will
    /// be the last buffer.
    fn set_is_last_buffer(&mut self, b: bool) {
        self.my_last_buffer = b;
    }

    #[inline]
    /// Returns the last input buffer flag.
    fn is_last_buffer(&self) -> bool {
        self.my_last_buffer
    }

    #[inline]
    /// This function returns true if invalid UTF32 decodes occurred in this
    /// parsing stream.
    fn has_invalid_sequence(&self) -> bool {
        self.my_invalid_sequence
    }

    #[inline]
    /// This function signals the occurrence of an invalid UTF32 sequence.
    fn signal_invalid_sequence(&mut self) {
        self.my_invalid_sequence = true;
    }

    #[inline]
    /// This function resets the invalid sequence state.
    fn reset_invalid_sequence(&mut self) {
        self.my_invalid_sequence = false;
    }

    #[inline]
    /// Reset all parser states to the initial value.
    /// Last buffer indication is set to true.
    /// Invalid sequence indication is cleared.
    fn reset_parser(&mut self) {
        // Drain our buffer.
        self.my_buf.clear();
        self.set_is_last_buffer(true);
        self.reset_invalid_sequence();
    }

}

/// Map a char parsing result to a UTF32 parsing result.
pub fn parse_mapper_char_to_utf32(input: Result<(& [u8], char), MoreEnum>)
-> Result<(& [u8], u32), MoreEnum> {
    match input {
        Result::Err(e) => { Result::Err(e) }
        Result::Ok((new_spot, ch)) => { Ok((new_spot, ch as u32)) }
    }
}

/// Implementation of FromUtf8
impl FromUtf8 {

    /// Make a new FromUtf8
    pub fn new() -> FromUtf8 {
        FromUtf8 {
            my_buf : EightBytes::new(),
            my_last_buffer : true,
            my_invalid_sequence : false,
        }
    }

    /// A parser takes in byte slice, and returns a Result object with
    /// either the remaining input and the output char value, or an MoreEnum
    /// that requests additional data, or an end of data stream condition.
    ///
    /// Invalid UTF8 decodes are indicated by Unicode replacement characters.
    /// has_invalid_decodes() would return true after this event.
    /// Encountering a replacement character is considered the same as having
    /// an invalid decode.
    pub fn utf8_to_char<'b>(&mut self, input: &'b [u8])
    -> Result<(&'b [u8], char), MoreEnum> {
        let mut my_cursor: &[u8] = input;
        let last_buffer = self.my_last_buffer;
        // Fill buffer phase.
        loop {
            if self.my_buf.is_full() || (my_cursor.len() == 0) {
                break;
            }
            // Push a u8, and advance input position.
            self.my_buf.push_back(my_cursor[0]);
            my_cursor = &my_cursor[1..];
        }
        if self.my_buf.is_empty() {
            // Processing for buffer being empty case
            // Determine if we are at end of data.
            if last_buffer {
                // at end of data condition
                Result::Err(MoreEnum::More(0))
            }
            else {
                // Returning an indication to request a new buffer.
                Result::Err(MoreEnum::More(4096))
            }
        }
        else {
            match utf8_decode(& mut self.my_buf, last_buffer) {
                Utf8EndEnum::BadDecode(_) => {
                    self.signal_invalid_sequence();
                    Result::Ok((my_cursor, char::REPLACEMENT_CHARACTER))
                }
                Utf8EndEnum::Finish(code) => {
                    // Unsafe is justified because utf8_decode() finite state
                    // machine checks for all cases of invalid decodes.
                    let ch = unsafe { char::from_u32_unchecked(code) };
                    Result::Ok((my_cursor, ch))
                }
                Utf8EndEnum::TypeUnknown => {
                    // Insufficient data to decode.
                    if last_buffer {
                        self.signal_invalid_sequence();
                        // Buffer should be empty at this point.
                        Result::Ok((my_cursor, char::REPLACEMENT_CHARACTER))
                    }
                    else {
                        // Return an indication to request a new buffer.
                        Result::Err(MoreEnum::More(4096))
                    }
                }
            }
        }
    }

    /// A parser takes in byte slice, and returns a Result object with
    /// either the remaining input and the output u32 value, or an MoreEnum
    /// that requests additional data, or an end of data stream condition.
    ///
    /// Invalid UTF8 decodes are indicated by Unicode replacement characters.
    /// has_invalid_decodes() would return true after this event.
    /// Encountering a replacement character is considered the same as having
    /// an invalid decode.
    pub fn utf8_to_utf32<'c>(&mut self, input: &'c [u8])
    -> Result<(&'c [u8], u32), MoreEnum> {
        let char_parse_result = self.utf8_to_char(input);
        parse_mapper_char_to_utf32(char_parse_result)
    }

    /// Convert from UTF8 to char with a mutable reference
    /// to the source UTF8 iterator.
    pub fn utf8_to_char_with_iter<'d>(&'d mut self, iter: &'d mut dyn Iterator<Item = u8>)
    -> Utf8IterToCharIter {
        Utf8IterToCharIter {
            my_info : self,
            my_borrow_mut_iter: iter,
        }
    }

    /// Convert from UTF8 reference to char with a mutable reference
    /// to the source UTF8 iterator.
    pub fn utf8_ref_to_char_with_iter<'d>(&'d mut self, iter: &'d mut dyn Iterator<Item = &'d u8>)
    -> Utf8RefIterToCharIter {
        Utf8RefIterToCharIter {
            my_info : self,
            my_borrow_mut_iter: iter,
        }
    }

}


/// Implementation of FromUnicode
impl FromUnicode {

    /// Make a new FromUnicode
    pub fn new() -> FromUnicode {
        FromUnicode {
            my_buf : EightBytes::new(),
            my_last_buffer : true,
            my_invalid_sequence : false,
        }
    }

    /// A parser takes in char slice, and returns a Result object with
    /// either the remaining input and the output byte value, or an MoreEnum
    /// that requests additional data, or an end of data stream condition.
    ///
    /// Invalid UTF32 decodes are indicated by Unicode replacement characters.
    /// has_invalid_decodes() would return true after this event.
    /// Encountering a replacement character is considered the same as having
    /// an invalid decode.
    pub fn char_to_utf8<'b>(&mut self, input: &'b [char])
    -> Result<(&'b [char], u8), MoreEnum> {
        // Check if we can pull an u8 from our ring buffer
        match self.my_buf.pop_front() {
            Some(v1) => {
                return Result::Ok((input, v1));
            }
            None => {}
        }
        let mut my_cursor: &[char] = input;
        // Processing for input being empty case
        if my_cursor.len() == 0 {
            // Determine if we are at end of data.
            if self.is_last_buffer() {
                // at end of data condition
                return Result::Err(MoreEnum::More(0));
            }
            else {
                // Returning an indication to request a new buffer.
                return Result::Err(MoreEnum::More(1024));
            }
        }
        // Grab one UTF32 from input
        let cur_u32 = my_cursor[0] as u32;
        my_cursor = &my_cursor[1..];
        // Try to determine the type of UTF32 encoding.
        match classify_utf32(cur_u32) {
            Utf8TypeEnum::Type1(v1) => {
                Result::Ok((my_cursor, v1))
            }
            Utf8TypeEnum::Type2((v1,v2)) => {
                self.my_buf.push_back(v2);
                Result::Ok((my_cursor, v1))
            }
            Utf8TypeEnum::Type3((v1,v2,v3)) => {
                self.my_buf.push_back(v2);
                self.my_buf.push_back(v3);
                Result::Ok((my_cursor, v1))
            }
            Utf8TypeEnum::Type4((v1,v2,v3,v4)) => {
                self.my_buf.push_back(v2);
                self.my_buf.push_back(v3);
                self.my_buf.push_back(v4);
                Result::Ok((my_cursor, v1))
            }
            _ => {
                // Invalid UTF32 codepoint
                // Emit replacement byte sequence.
                self.signal_invalid_sequence();
                self.my_buf.push_back(REPLACE_PART2);
                self.my_buf.push_back(REPLACE_PART3);
                Result::Ok((my_cursor, REPLACE_PART1))
            }
        }
    }

    /// A parser takes in UTF32 slice, and returns a Result object with
    /// either the remaining input and the output byte value, or an MoreEnum
    /// that requests additional data, or an end of data stream condition.
    ///
    /// Invalid UTF32 decodes are indicated by Unicode replacement characters.
    /// has_invalid_decodes() would return true after this event.
    /// Encountering a replacement character is considered the same as having
    /// an invalid decode.
    pub fn utf32_to_utf8<'c>(&mut self, input: &'c [u32])
    -> Result<(&'c [u32], u8), MoreEnum> {
        // Check if we can pull an u8 from our ring buffer
        match self.my_buf.pop_front() {
            Some(v1) => {
                return Result::Ok((input, v1));
            }
            None => {}
        }
        let mut my_cursor: &[u32] = input;
        // Processing for input being empty case
        if my_cursor.len() == 0 {
            // Determine if we are at end of data.
            if self.is_last_buffer() {
                // at end of data condition
                return Result::Err(MoreEnum::More(0));
            }
            else {
                // Returning an indication to request a new buffer.
                return Result::Err(MoreEnum::More(1024));
            }
        }
        // Grab one UTF32 from input
        let cur_u32 = my_cursor[0];
        my_cursor = &my_cursor[1..];
        // Try to determine the type of UTF32 encoding.
        match classify_utf32(cur_u32) {
            Utf8TypeEnum::Type1(v1) => {
                Result::Ok((my_cursor, v1))
            }
            Utf8TypeEnum::Type2((v1,v2)) => {
                self.my_buf.push_back(v2);
                Result::Ok((my_cursor, v1))
            }
            Utf8TypeEnum::Type3((v1,v2,v3)) => {
                self.my_buf.push_back(v2);
                self.my_buf.push_back(v3);
                Result::Ok((my_cursor, v1))
            }
            Utf8TypeEnum::Type4((v1,v2,v3,v4)) => {
                self.my_buf.push_back(v2);
                self.my_buf.push_back(v3);
                self.my_buf.push_back(v4);
                Result::Ok((my_cursor, v1))
            }
            _ => {
                // Invalid UTF32 codepoint
                // Emit replacement byte sequence.
                self.signal_invalid_sequence();
                self.my_buf.push_back(REPLACE_PART2);
                self.my_buf.push_back(REPLACE_PART3);
                Result::Ok((my_cursor, REPLACE_PART1))
            }
        }
    }

    /// Convert from UTF32 iter to UTF8 iter with a mutable reference
    /// to the source UTF32 iterator.
    pub fn utf32_to_utf8_with_iter<'d>(&'d mut self, iter: &'d mut dyn Iterator<Item = u32>)
    -> Utf32IterToUtf8Iter {
        Utf32IterToUtf8Iter {
            my_borrow_mut_iter: iter,
            my_info: self,
        }
    }

    /// Convert from char reference iter to UTF8 iter with a mutable reference
    /// to the source char reference iterator.
    pub fn char_ref_to_utf8_with_iter<'d>(&'d mut self, iter: &'d mut dyn Iterator<Item = &'d char>)
    -> CharRefIterToUtf8Iter {
        CharRefIterToUtf8Iter {
            my_borrow_mut_iter: iter,
            my_info: self,
        }
    }

}

/// Implementations of common operations for Utf8IterToCharIter
impl<'g> UtfParserCommon for Utf8IterToCharIter<'g> {

    #[inline]
    /// If argument `b` is true, then any input buffer to be presented will
    /// be the last buffer.
    fn set_is_last_buffer(&mut self, b: bool) {
        self.my_info.set_is_last_buffer(b);
    }

    #[inline]
    /// Returns the last input buffer flag.
    fn is_last_buffer(&self) -> bool {
        self.my_info.is_last_buffer()
    }

    #[inline]
    /// This function returns true if invalid UTF8 sequence occurred
    /// in this parsing stream.
    fn has_invalid_sequence(&self) -> bool {
        self.my_info.has_invalid_sequence()
    }

    #[inline]
    /// This function signals the occurrence of an invalid UTF8 sequence.
    fn signal_invalid_sequence(&mut self) {
        self.my_info.signal_invalid_sequence();
    }

    #[inline]
    /// This function resets the invalid decodes state.
    fn reset_invalid_sequence(& mut self) {
        self.my_info.reset_invalid_sequence();
    }

    #[inline]
    /// Reset all parser states to the initial value.
    /// Last buffer indication is set to true.
    /// Invalid decodes indication is cleared.
    fn reset_parser(&mut self) {
        self.my_info.reset_parser();
    }
}

/// Iterator for Utf8IterToCharIter
impl<'g> Iterator for Utf8IterToCharIter<'g> {
    type Item = char;

    /// A parser takes in an iterator of UTF8 byte stream, and returns
    /// an iterator of char values.
    ///
    /// An invalid Unicode decode in the stream are substituted with
    /// an Unicode replacement character.
    ///
    /// has_invalid_sequence() would return true after observing
    /// invalid decodes, or observing a replacement character.
    fn next(&mut self) -> Option<Self::Item> {
        // Fill buffer phase.
        loop {
            if self.my_info.my_buf.is_full() {
                break;
            }
            match self.my_borrow_mut_iter.next() {
                Option::None => {
                    break;
                }
                Option::Some(utf8) => {
                    // Save it in our scratch pad.
                    self.my_info.my_buf.push_back(utf8);
                }
            }
        }
        if self.my_info.my_buf.is_empty() {
            // This is either the end of data, or the current buffer
            // has run to the end without left-over data in the
            // scratch pad.
            Option::None
        }
        else {
            let last_buffer = self.my_info.is_last_buffer();
            match utf8_decode(& mut self.my_info.my_buf, last_buffer) {
                Utf8EndEnum::BadDecode(_) => {
                    self.my_info.signal_invalid_sequence();
                    Option::Some(char::REPLACEMENT_CHARACTER)
                }
                Utf8EndEnum::Finish(code) => {
                    // Unsafe is justified because utf8_decode() finite state
                    // machine checks for all cases of invalid decodes.
                    let ch = unsafe { char::from_u32_unchecked(code) };
                    Option::Some(ch)
                }
                Utf8EndEnum::TypeUnknown => {
                    // Insufficient data to decode.
                    if last_buffer {
                        self.my_info.signal_invalid_sequence();
                        // Buffer should be empty at this point.
                        Option::Some(char::REPLACEMENT_CHARACTER)
                    }
                    else {
                        // Ready for next buffer
                        Option::None
                    }
                }
            }
        }
    }

    /// sizing hint for iterator, with a lower bound and optional upperbound
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.my_borrow_mut_iter.size_hint()
    }
}

/// Implementations of common operations for Utf8RefIterToCharIter
impl<'g> UtfParserCommon for Utf8RefIterToCharIter<'g> {

    #[inline]
    /// If argument `b` is true, then any input buffer to be presented will
    /// be the last buffer.
    fn set_is_last_buffer(&mut self, b: bool) {
        self.my_info.set_is_last_buffer(b);
    }

    #[inline]
    /// Returns the last input buffer flag.
    fn is_last_buffer(&self) -> bool {
        self.my_info.is_last_buffer()
    }

    #[inline]
    /// This function returns true if invalid UTF8 sequence occurred
    /// in this parsing stream.
    fn has_invalid_sequence(&self) -> bool {
        self.my_info.has_invalid_sequence()
    }

    #[inline]
    /// This function signals the occurrence of an invalid UTF8 sequence.
    fn signal_invalid_sequence(&mut self) {
        self.my_info.signal_invalid_sequence();
    }

    #[inline]
    /// This function resets the invalid decodes state.
    fn reset_invalid_sequence(& mut self) {
        self.my_info.reset_invalid_sequence();
    }

    #[inline]
    /// Reset all parser states to the initial value.
    /// Last buffer indication is set to true.
    /// Invalid decodes indication is cleared.
    fn reset_parser(&mut self) {
        self.my_info.reset_parser();
    }
}

/// Iterator for Utf8RefIterToCharIter
impl<'g> Iterator for Utf8RefIterToCharIter<'g> {
    type Item = char;

    /// A parser takes in an iterator of UTF8 byte stream, and returns
    /// an iterator of char values.
    ///
    /// An invalid Unicode decode in the stream are substituted with
    /// an Unicode replacement character.
    ///
    /// has_invalid_sequence() would return true after observing
    /// invalid decodes, or observing a replacement character.
    fn next(&mut self) -> Option<Self::Item> {
        // Fill buffer phase.
        loop {
            if self.my_info.my_buf.is_full() {
                break;
            }
            match self.my_borrow_mut_iter.next() {
                Option::None => {
                    break;
                }
                Option::Some(utf8) => {
                    // Save it in our scratch pad.
                    self.my_info.my_buf.push_back(* utf8);
                }
            }
        }
        if self.my_info.my_buf.is_empty() {
            // This is either the end of data, or the current buffer
            // has run to the end without left-over data in the
            // scratch pad.
            Option::None
        }
        else {
            let last_buffer = self.my_info.is_last_buffer();
            match utf8_decode(& mut self.my_info.my_buf, last_buffer) {
                Utf8EndEnum::BadDecode(_) => {
                    self.my_info.signal_invalid_sequence();
                    Option::Some(char::REPLACEMENT_CHARACTER)
                }
                Utf8EndEnum::Finish(code) => {
                    // Unsafe is justified because utf8_decode() finite state
                    // machine checks for all cases of invalid decodes.
                    let ch = unsafe { char::from_u32_unchecked(code) };
                    Option::Some(ch)
                }
                Utf8EndEnum::TypeUnknown => {
                    // Insufficient data to decode.
                    if last_buffer {
                        self.my_info.signal_invalid_sequence();
                        // Buffer should be empty at this point.
                        Option::Some(char::REPLACEMENT_CHARACTER)
                    }
                    else {
                        // Ready for next buffer
                        Option::None
                    }
                }
            }
        }
    }

    /// sizing hint for iterator, with a lower bound and optional upperbound
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.my_borrow_mut_iter.size_hint()
    }
}

/// Implementations of common operations for Utf32IterToUtf8Iter
impl<'h> UtfParserCommon for Utf32IterToUtf8Iter<'h> {

    #[inline]
    /// If argument `b` is true, then any input buffer to be presented will
    /// be the last buffer.
    fn set_is_last_buffer(&mut self, b: bool) {
        self.my_info.set_is_last_buffer(b);
    }

    #[inline]
    /// Returns the last input buffer flag.
    fn is_last_buffer(&self) -> bool {
        self.my_info.is_last_buffer()
    }

    #[inline]
    /// This function returns true if invalid UTF32 sequence occurred
    /// in this parsing stream.
    fn has_invalid_sequence(&self) -> bool {
        self.my_info.has_invalid_sequence()
    }

    #[inline]
    /// This function signals the occurrence of an invalid UTF32 sequence.
    fn signal_invalid_sequence(&mut self) {
        self.my_info.signal_invalid_sequence();
    }

    #[inline]
    /// This function resets the invalid decodes state.
    fn reset_invalid_sequence(& mut self) {
        self.my_info.reset_invalid_sequence();
    }

    #[inline]
    /// Reset all parser states to the initial value.
    /// Last buffer indication is set to true.
    /// Invalid decodes indication is cleared.
    fn reset_parser(&mut self) {
        self.my_info.reset_parser();
    }
}

/// Iterator for Utf32IterToUtf8Iter
impl<'h> Iterator for Utf32IterToUtf8Iter<'h> {
    type Item = u8;

    /// A parser takes in an iterator of Unicode codepoints, and returns
    /// the output UTF8 byte value.
    ///
    /// An invalid Unicode codepoint in the stream are substituted with
    /// an Unicode replacement character.
    ///
    /// has_invalid_sequence() would return true after observing
    /// invalid decodes, or observing a replacement character.
    fn next(&mut self) -> Option<Self::Item> {
        // Check if we can pull an u8 from our ring buffer.
        match self.my_info.my_buf.pop_front() {
            Option::Some(v1) => {
                return Option::Some(v1);
            }
            Option::None => {}
        }
        // Processing for input being empty case
        match self.my_borrow_mut_iter.next() {
            Option::None => {
                return Option::None;
            }
            Option::Some(utf32) => {
                // Try to determine the type of UTFf32 encoding.
                match classify_utf32(utf32) {
                    Utf8TypeEnum::Type1(v1) => {
                        Option::Some(v1)
                    }
                    Utf8TypeEnum::Type2((v1,v2)) => {
                        self.my_info.my_buf.push_back(v2);
                        Option::Some(v1)
                    }
                    Utf8TypeEnum::Type3((v1,v2,v3)) => {
                        self.my_info.my_buf.push_back(v2);
                        self.my_info.my_buf.push_back(v3);
                        Option::Some(v1)
                    }
                    Utf8TypeEnum::Type4((v1,v2,v3,v4)) => {
                        self.my_info.my_buf.push_back(v2);
                        self.my_info.my_buf.push_back(v3);
                        self.my_info.my_buf.push_back(v4);
                        Option::Some(v1)
                    }
                    _ => {
                        // Invalid UTF32 codepoint
                        // Emit replacement byte sequence.
                        self.my_info.signal_invalid_sequence();
                        self.my_info.my_buf.push_back(REPLACE_PART2);
                        self.my_info.my_buf.push_back(REPLACE_PART3);
                        Option::Some(REPLACE_PART1)
                    }
                }
            }
        }
    }

    /// sizing hint for iterator, with a lower bound and optional upperbound
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.my_borrow_mut_iter.size_hint()
    }

}

/// Implementations of common operations for CharRefIterToUtf8Iter
impl<'h> UtfParserCommon for CharRefIterToUtf8Iter<'h> {

    #[inline]
    /// If argument `b` is true, then any input buffer to be presented will
    /// be the last buffer.
    fn set_is_last_buffer(&mut self, b: bool) {
        self.my_info.set_is_last_buffer(b);
    }

    #[inline]
    /// Returns the last input buffer flag.
    fn is_last_buffer(&self) -> bool {
        self.my_info.is_last_buffer()
    }

    #[inline]
    /// This function returns true if invalid UTF32 sequence occurred
    /// in this parsing stream.
    fn has_invalid_sequence(&self) -> bool {
        self.my_info.has_invalid_sequence()
    }

    #[inline]
    /// This function signals the occurrence of an invalid UTF32 sequence.
    fn signal_invalid_sequence(&mut self) {
        self.my_info.signal_invalid_sequence();
    }

    #[inline]
    /// This function resets the invalid decodes state.
    fn reset_invalid_sequence(& mut self) {
        self.my_info.reset_invalid_sequence();
    }

    #[inline]
    /// Reset all parser states to the initial value.
    /// Last buffer indication is set to true.
    /// Invalid decodes indication is cleared.
    fn reset_parser(&mut self) {
        self.my_info.reset_parser();
    }
}

/// Iterator for CharRefIterToUtf8Iter
impl<'h> Iterator for CharRefIterToUtf8Iter<'h> {
    type Item = u8;

    /// A parser takes in an iterator of Unicode codepoints, and returns
    /// the output UTF8 byte value.
    ///
    /// An invalid Unicode codepoint in the stream are substituted with
    /// an Unicode replacement character.
    ///
    /// has_invalid_sequence() would return true after observing
    /// invalid decodes, or observing a replacement character.
    fn next(&mut self) -> Option<Self::Item> {
        // Check if we can pull an u8 from our ring buffer.
        match self.my_info.my_buf.pop_front() {
            Option::Some(v1) => {
                return Option::Some(v1);
            }
            Option::None => {}
        }
        // Processing for input being empty case
        match self.my_borrow_mut_iter.next() {
            Option::None => {
                return Option::None;
            }
            Option::Some(ch_ref) => {
                let utf32 = (* ch_ref) as u32;
                // Try to determine the type of UTFf32 encoding.
                match classify_utf32(utf32) {
                    Utf8TypeEnum::Type1(v1) => {
                        Option::Some(v1)
                    }
                    Utf8TypeEnum::Type2((v1,v2)) => {
                        self.my_info.my_buf.push_back(v2);
                        Option::Some(v1)
                    }
                    Utf8TypeEnum::Type3((v1,v2,v3)) => {
                        self.my_info.my_buf.push_back(v2);
                        self.my_info.my_buf.push_back(v3);
                        Option::Some(v1)
                    }
                    Utf8TypeEnum::Type4((v1,v2,v3,v4)) => {
                        self.my_info.my_buf.push_back(v2);
                        self.my_info.my_buf.push_back(v3);
                        self.my_info.my_buf.push_back(v4);
                        Option::Some(v1)
                    }
                    _ => {
                        // Invalid UTF32 codepoint
                        // Emit replacement byte sequence.
                        self.my_info.signal_invalid_sequence();
                        self.my_info.my_buf.push_back(REPLACE_PART2);
                        self.my_info.my_buf.push_back(REPLACE_PART3);
                        Option::Some(REPLACE_PART1)
                    }
                }
            }
        }
    }

    /// sizing hint for iterator, with a lower bound and optional upperbound
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.my_borrow_mut_iter.size_hint()
    }

}

#[cfg(test)]
mod tests {
    extern crate std;

    use crate::*;

    // Print bytes in hex codes.
    fn _print_bytes(u8_slice: & [u8]) {
        for indx in 0 .. u8_slice.len() {
            let b = u8_slice[indx] as u32;
            print!(" {:#02x}", b);
        }
        println!("");
    }

    #[test]
    // Test BOM and CR filtering
    fn test_filter_bom_and_cr() {
        let byte_slice = "\u{FEFF}\u{FEFF}\r\nA\r\rB\rCD\r\n\nEF\r\n\r\nG\n\r".as_bytes();
        let mut byte_ref_iter = byte_slice.iter();
        let mut from_utf8 = FromUtf8::new();
        let mut utf8_to_char_iter = from_utf8.utf8_ref_to_char_with_iter(& mut byte_ref_iter);
        let mut filter_iter = filter_bom_and_cr_iter(& mut utf8_to_char_iter);
        // Only one Byte Order Mark should be removed.
        assert_eq!(Some('\u{FEFF}'), filter_iter.next());
        assert_eq!(Some('\n'), filter_iter.next()); // CR - NL => NL
        assert_eq!(Some('A'), filter_iter.next());
        assert_eq!(Some('\n'), filter_iter.next()); // CR, CR => NL, NL
        assert_eq!(Some('\n'), filter_iter.next());
        assert_eq!(Some('B'), filter_iter.next());
        assert_eq!(Some('\n'), filter_iter.next()); // CR => NL
        assert_eq!(Some('C'), filter_iter.next());
        assert_eq!(Some('D'), filter_iter.next());
        assert_eq!(Some('\n'), filter_iter.next()); // CR NL => NL
        assert_eq!(Some('\n'), filter_iter.next()); // NL => NL
        assert_eq!(Some('E'), filter_iter.next());
        assert_eq!(Some('F'), filter_iter.next());
        assert_eq!(Some('\n'), filter_iter.next()); // CR NL => NL
        assert_eq!(Some('\n'), filter_iter.next()); // CR => NL
        assert_eq!(Some('G'), filter_iter.next());
        assert_eq!(Some('\n'), filter_iter.next()); // NL => NL
        assert_eq!(Some('\n'), filter_iter.next()); // CR => NL
        assert_eq!(Option::None, filter_iter.next());
    }

    // Have a char value go through a round trip of conversions.
    fn round_trip_parsing1(char_val: char) {
        let char_box: [char; 1] = [char_val; 1];
        let mut utf8_box: [u8; 4] = [0; 4];
        let mut utf8_len: usize = 0;

        let mut char_ref = & char_box[..];
        let mut utf32_parser = FromUnicode::new();
        loop {
            match utf32_parser.char_to_utf8(char_ref) {
                Result::Ok((char_pos, b)) => {
                    if char_val == char::REPLACEMENT_CHARACTER {
                        assert_eq!(true, utf32_parser.has_invalid_sequence());
                    }
                    utf8_box[utf8_len] = b;
                    utf8_len += 1;
                    char_ref = char_pos;
                }
                Result::Err(MoreEnum::More(_)) => {
                    break;
                }
            }
        }
        let mut utf8_ref = & utf8_box[0 .. utf8_len];
        let mut char_box2: [char; 1] = [char::MAX; 1];
        let mut char_len: usize = 0;
        let mut utf8_parser = FromUtf8::new();
        loop {
            match utf8_parser.utf8_to_char(utf8_ref) {
                Result::Ok((utf8_pos, ch)) => {
                    if char_val == char::REPLACEMENT_CHARACTER {
                        assert_eq!(true, utf8_parser.has_invalid_sequence());
                    }
                    char_box2[char_len] = ch;
                    char_len += 1;
                    utf8_ref = utf8_pos;
                }
                Result::Err(MoreEnum::More(_)) => {
                    break;
                }
            }
        }
        assert_eq!(1, char_len);
        assert_eq!(char_val, char_box2[0]);
    }

    // Have a char value go through a round trip of conversions.
    fn round_trip_parsing2(code_val: u32) {
        let utf32_box: [u32; 1] = [code_val; 1];
        let mut utf8_box: [u8; 4] = [0; 4];
        let mut utf8_len: usize = 0;

        let mut utf32_ref = & utf32_box[..];
        let mut utf32_parser = FromUnicode::new();
        loop {
            match utf32_parser.utf32_to_utf8(utf32_ref) {
                Result::Ok((utf32_pos, b)) => {
                    if code_val == REPLACE_UTF32 {
                        assert_eq!(true, utf32_parser.has_invalid_sequence());
                    }
                    utf8_box[utf8_len] = b;
                    utf8_len += 1;
                    utf32_ref = utf32_pos;
                }
                Result::Err(MoreEnum::More(_)) => {
                    break;
                }
            }
        }
        let mut utf8_ref = & utf8_box[0 .. utf8_len];
        let mut utf32_box2: [u32; 1] = [0; 1];
        let mut utf32_len: usize = 0;
        let mut utf8_parser = FromUtf8::new();
        loop {
            match utf8_parser.utf8_to_utf32(utf8_ref) {
                Result::Ok((utf8_pos, co)) => {
                    if code_val == REPLACE_UTF32 {
                        assert_eq!(true, utf8_parser.has_invalid_sequence());
                    }
                    utf32_box2[utf32_len] = co;
                    utf32_len += 1;
                    utf8_ref = utf8_pos;
                }
                Result::Err(MoreEnum::More(_)) => {
                    break;
                }
            }
        }
        assert_eq!(1, utf32_len);
        assert_eq!(code_val, utf32_box2[0]);
    }

    #[test]
    // Test using both parsing converters to convert back and forth.
    pub fn test_round_trip_parsing() {
        let mut code:u32 = 0;
        loop {
            let ch = char::from_u32(code).unwrap();
            round_trip_parsing1(ch);
            round_trip_parsing2(code);
            code += 1;
            if code == 0xD800 {
                code = 0xE000; // skip UTF16 surrogate range
            }
            if code == 0x110000 {
                break;
            }
        }
    }


}

pub mod buf;