summaryrefslogtreecommitdiff
path: root/src/mscorlib/src/System/Text/Encoding.cs
blob: 88eeb19d24a74a3c4486515dfbb625f3a299c877 (plain)
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace System.Text
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Runtime;
    using System.Runtime.Serialization;
    using System.Globalization;
    using System.Security;
    using System.Threading;
    using System.Text;
    using System.Diagnostics;
    using System.Diagnostics.CodeAnalysis;
    using System.Diagnostics.Contracts;
    using Win32Native = Microsoft.Win32.Win32Native;

    // This abstract base class represents a character encoding. The class provides
    // methods to convert arrays and strings of Unicode characters to and from
    // arrays of bytes. A number of Encoding implementations are provided in
    // the System.Text package, including:
    //
    // ASCIIEncoding, which encodes Unicode characters as single 7-bit
    // ASCII characters. This encoding only supports character values between 0x00
    //     and 0x7F.
    // BaseCodePageEncoding, which encapsulates a Windows code page. Any
    //     installed code page can be accessed through this encoding, and conversions
    //     are performed using the WideCharToMultiByte and
    //     MultiByteToWideChar Windows API functions.
    // UnicodeEncoding, which encodes each Unicode character as two
    //    consecutive bytes. Both little-endian (code page 1200) and big-endian (code
    //    page 1201) encodings are recognized.
    // UTF7Encoding, which encodes Unicode characters using the UTF-7
    //     encoding (UTF-7 stands for UCS Transformation Format, 7-bit form). This
    //     encoding supports all Unicode character values, and can also be accessed
    //     as code page 65000.
    // UTF8Encoding, which encodes Unicode characters using the UTF-8
    //     encoding (UTF-8 stands for UCS Transformation Format, 8-bit form). This
    //     encoding supports all Unicode character values, and can also be accessed
    //     as code page 65001.
    // UTF32Encoding, both 12000 (little endian) & 12001 (big endian)
    //
    // In addition to directly instantiating Encoding objects, an
    // application can use the ForCodePage, GetASCII,
    // GetDefault, GetUnicode, GetUTF7, and GetUTF8
    // methods in this class to obtain encodings.
    //
    // Through an encoding, the GetBytes method is used to convert arrays
    // of characters to arrays of bytes, and the GetChars method is used to
    // convert arrays of bytes to arrays of characters. The GetBytes and
    // GetChars methods maintain no state between conversions, and are
    // generally intended for conversions of complete blocks of bytes and
    // characters in one operation. When the data to be converted is only available
    // in sequential blocks (such as data read from a stream) or when the amount of
    // data is so large that it needs to be divided into smaller blocks, an
    // application may choose to use a Decoder or an Encoder to
    // perform the conversion. Decoders and encoders allow sequential blocks of
    // data to be converted and they maintain the state required to support
    // conversions of data that spans adjacent blocks. Decoders and encoders are
    // obtained using the GetDecoder and GetEncoder methods.
    //
    // The core GetBytes and GetChars methods require the caller
    // to provide the destination buffer and ensure that the buffer is large enough
    // to hold the entire result of the conversion. When using these methods,
    // either directly on an Encoding object or on an associated
    // Decoder or Encoder, an application can use one of two methods
    // to allocate destination buffers.
    //
    // The GetByteCount and GetCharCount methods can be used to
    // compute the exact size of the result of a particular conversion, and an
    // appropriately sized buffer for that conversion can then be allocated.
    // The GetMaxByteCount and GetMaxCharCount methods can be
    // be used to compute the maximum possible size of a conversion of a given
    // number of bytes or characters, and a buffer of that size can then be reused
    // for multiple conversions.
    //
    // The first method generally uses less memory, whereas the second method
    // generally executes faster.
    //

    public abstract class Encoding : ICloneable
    {
        // For netcore we use UTF8 as default encoding since ANSI isn't available
        private static readonly UTF8Encoding.UTF8EncodingSealed s_defaultEncoding  = new UTF8Encoding.UTF8EncodingSealed(encoderShouldEmitUTF8Identifier: false);

        // Returns an encoding for the system's current ANSI code page.
        public static Encoding Default => s_defaultEncoding;

        //
        // The following values are from mlang.idl.  These values
        // should be in sync with those in mlang.idl.
        //
        internal const int MIMECONTF_MAILNEWS = 0x00000001;
        internal const int MIMECONTF_BROWSER = 0x00000002;
        internal const int MIMECONTF_SAVABLE_MAILNEWS = 0x00000100;
        internal const int MIMECONTF_SAVABLE_BROWSER = 0x00000200;

        // Special Case Code Pages
        private const int CodePageDefault = 0;
        private const int CodePageNoOEM = 1;        // OEM Code page not supported
        private const int CodePageNoMac = 2;        // MAC code page not supported
        private const int CodePageNoThread = 3;        // Thread code page not supported
        private const int CodePageNoSymbol = 42;       // Symbol code page not supported
        private const int CodePageUnicode = 1200;     // Unicode
        private const int CodePageBigEndian = 1201;     // Big Endian Unicode
        private const int CodePageWindows1252 = 1252;     // Windows 1252 code page

        // 20936 has same code page as 10008, so we'll special case it
        private const int CodePageMacGB2312 = 10008;
        private const int CodePageGB2312 = 20936;
        private const int CodePageMacKorean = 10003;
        private const int CodePageDLLKorean = 20949;

        // ISO 2022 Code Pages
        private const int ISO2022JP = 50220;
        private const int ISO2022JPESC = 50221;
        private const int ISO2022JPSISO = 50222;
        private const int ISOKorean = 50225;
        private const int ISOSimplifiedCN = 50227;
        private const int EUCJP = 51932;
        private const int ChineseHZ = 52936;    // HZ has ~}~{~~ sequences

        // 51936 is the same as 936
        private const int DuplicateEUCCN = 51936;
        private const int EUCCN = 936;

        private const int EUCKR = 51949;

        // Latin 1 & ASCII Code Pages
        internal const int CodePageASCII = 20127;    // ASCII
        internal const int ISO_8859_1 = 28591;    // Latin1

        // ISCII
        private const int ISCIIAssemese = 57006;
        private const int ISCIIBengali = 57003;
        private const int ISCIIDevanagari = 57002;
        private const int ISCIIGujarathi = 57010;
        private const int ISCIIKannada = 57008;
        private const int ISCIIMalayalam = 57009;
        private const int ISCIIOriya = 57007;
        private const int ISCIIPanjabi = 57011;
        private const int ISCIITamil = 57004;
        private const int ISCIITelugu = 57005;

        // GB18030
        private const int GB18030 = 54936;

        // Other
        private const int ISO_8859_8I = 38598;
        private const int ISO_8859_8_Visual = 28598;

        // 50229 is currently unsupported // "Chinese Traditional (ISO-2022)"
        private const int ENC50229 = 50229;

        // Special code pages
        private const int CodePageUTF7 = 65000;
        private const int CodePageUTF8 = 65001;
        private const int CodePageUTF32 = 12000;
        private const int CodePageUTF32BE = 12001;

        internal int m_codePage = 0;

        // dataItem should be internal (not private). otherwise it will break during the deserialization
        // of the data came from Everett
        internal CodePageDataItem dataItem = null;

        [NonSerialized]
        internal bool m_deserializedFromEverett = false;

        // Because of encoders we may be read only
        [OptionalField(VersionAdded = 2)]
        private bool m_isReadOnly = true;

        // Encoding (encoder) fallback
        [OptionalField(VersionAdded = 2)]
        internal EncoderFallback encoderFallback = null;
        [OptionalField(VersionAdded = 2)]
        internal DecoderFallback decoderFallback = null;

        protected Encoding() : this(0)
        {
        }


        protected Encoding(int codePage)
        {
            // Validate code page
            if (codePage < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(codePage));
            }
            Contract.EndContractBlock();

            // Remember code page
            m_codePage = codePage;

            // Use default encoder/decoder fallbacks
            this.SetDefaultFallbacks();
        }

        // This constructor is needed to allow any sub-classing implementation to provide encoder/decoder fallback objects 
        // because the encoding object is always created as read-only object and don't allow setting encoder/decoder fallback 
        // after the creation is done. 
        protected Encoding(int codePage, EncoderFallback encoderFallback, DecoderFallback decoderFallback)
        {
            // Validate code page
            if (codePage < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(codePage));
            }
            Contract.EndContractBlock();

            // Remember code page
            m_codePage = codePage;

            this.encoderFallback = encoderFallback ?? new InternalEncoderBestFitFallback(this);
            this.decoderFallback = decoderFallback ?? new InternalDecoderBestFitFallback(this);
        }

        // Default fallback that we'll use.
        internal virtual void SetDefaultFallbacks()
        {
            // For UTF-X encodings, we use a replacement fallback with an "\xFFFD" string,
            // For ASCII we use "?" replacement fallback, etc.
            this.encoderFallback = new InternalEncoderBestFitFallback(this);
            this.decoderFallback = new InternalDecoderBestFitFallback(this);
        }


        #region Serialization
        internal void OnDeserializing()
        {
            // intialize the optional Whidbey fields
            encoderFallback = null;
            decoderFallback = null;
            m_isReadOnly = true;
        }

        internal void OnDeserialized()
        {
            if (encoderFallback == null || decoderFallback == null)
            {
                m_deserializedFromEverett = true;
                SetDefaultFallbacks();
            }

            // dataItem is always recalculated from the code page #
            dataItem = null;
        }

        [OnDeserializing]
        private void OnDeserializing(StreamingContext ctx)
        {
            OnDeserializing();
        }


        [OnDeserialized]
        private void OnDeserialized(StreamingContext ctx)
        {
            OnDeserialized();
        }

        [OnSerializing]
        private void OnSerializing(StreamingContext ctx)
        {
            // to be consistent with SerializeEncoding
            dataItem = null;
        }

        // the following two methods are used for the inherited classes which implemented ISerializable
        // Deserialization Helper
        internal void DeserializeEncoding(SerializationInfo info, StreamingContext context)
        {
            // Any info?
            if (info == null) throw new ArgumentNullException(nameof(info));
            Contract.EndContractBlock();

            // All versions have a code page
            this.m_codePage = (int)info.GetValue("m_codePage", typeof(int));

            // We can get dataItem on the fly if needed, and the index is different between versions
            // so ignore whatever dataItem data we get from Everett.
            this.dataItem = null;

            // See if we have a code page
            try
            {
                //
                // Try Whidbey V2.0 Fields
                //

                m_isReadOnly = (bool)info.GetValue("m_isReadOnly", typeof(bool));

                this.encoderFallback = (EncoderFallback)info.GetValue("encoderFallback", typeof(EncoderFallback));
                this.decoderFallback = (DecoderFallback)info.GetValue("decoderFallback", typeof(DecoderFallback));
            }
            catch (SerializationException)
            {
                //
                // Didn't have Whidbey things, must be Everett
                //
                this.m_deserializedFromEverett = true;

                // May as well be read only
                m_isReadOnly = true;
                SetDefaultFallbacks();
            }
        }

        // Serialization Helper
        internal void SerializeEncoding(SerializationInfo info, StreamingContext context)
        {
            // Any Info?
            if (info == null) throw new ArgumentNullException(nameof(info));
            Contract.EndContractBlock();

            // These are new V2.0 Whidbey stuff
            info.AddValue("m_isReadOnly", m_isReadOnly);
            info.AddValue("encoderFallback", this.EncoderFallback);
            info.AddValue("decoderFallback", this.DecoderFallback);

            // These were in Everett V1.1 as well
            info.AddValue("m_codePage", this.m_codePage);

            // This was unique to Everett V1.1
            info.AddValue("dataItem", null);

            // Everett duplicated these fields, so these are needed for portability
            info.AddValue("Encoding+m_codePage", this.m_codePage);
            info.AddValue("Encoding+dataItem", null);
        }

        #endregion Serialization

        // Converts a byte array from one encoding to another. The bytes in the
        // bytes array are converted from srcEncoding to
        // dstEncoding, and the returned value is a new byte array
        // containing the result of the conversion.
        //
        [Pure]
        public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding,
            byte[] bytes)
        {
            if (bytes == null)
                throw new ArgumentNullException(nameof(bytes));
            Contract.Ensures(Contract.Result<byte[]>() != null);

            return Convert(srcEncoding, dstEncoding, bytes, 0, bytes.Length);
        }

        // Converts a range of bytes in a byte array from one encoding to another.
        // This method converts count bytes from bytes starting at
        // index index from srcEncoding to dstEncoding, and
        // returns a new byte array containing the result of the conversion.
        //
        [Pure]
        public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding,
            byte[] bytes, int index, int count)
        {
            if (srcEncoding == null || dstEncoding == null)
            {
                throw new ArgumentNullException((srcEncoding == null ? nameof(srcEncoding) : nameof(dstEncoding)),
                    SR.ArgumentNull_Array);
            }
            if (bytes == null)
            {
                throw new ArgumentNullException(nameof(bytes),
                    SR.ArgumentNull_Array);
            }
            Contract.Ensures(Contract.Result<byte[]>() != null);

            return dstEncoding.GetBytes(srcEncoding.GetChars(bytes, index, count));
        }


        public static void RegisterProvider(EncodingProvider provider)
        {
            // Parameters validated inside EncodingProvider
            EncodingProvider.AddProvider(provider);
        }

        [Pure]
        public static Encoding GetEncoding(int codepage)
        {
            Encoding result = EncodingProvider.GetEncodingFromProvider(codepage);
            if (result != null)
                return result;

            //
            // NOTE: If you add a new encoding that can be get by codepage, be sure to
            // add the corresponding item in EncodingTable.
            // Otherwise, the code below will throw exception when trying to call
            // EncodingTable.GetDataItem().
            //
            if (codepage < 0 || codepage > 65535)
            {
                throw new ArgumentOutOfRangeException(
                    nameof(codepage), SR.Format(SR.ArgumentOutOfRange_Range, 0, 65535));
            }

            Contract.EndContractBlock();

            // Our Encoding

            // See if the encoding is cached in a static field.
            switch (codepage)
            {
                case CodePageDefault: return Default;            // 0
                case CodePageUnicode: return Unicode;            // 1200
                case CodePageBigEndian: return BigEndianUnicode; // 1201
                case CodePageUTF32: return UTF32;                // 12000
                case CodePageUTF32BE: return BigEndianUTF32;     // 12001
                case CodePageUTF7: return UTF7;                  // 65000
                case CodePageUTF8: return UTF8;                  // 65001
                case CodePageASCII: return ASCII;                // 20127
                case ISO_8859_1: return Latin1;                  // 28591

                // We don't allow the following special code page values that Win32 allows.
                case CodePageNoOEM:                              // 1 CP_OEMCP
                case CodePageNoMac:                              // 2 CP_MACCP
                case CodePageNoThread:                           // 3 CP_THREAD_ACP
                case CodePageNoSymbol:                           // 42 CP_SYMBOL
                    throw new ArgumentException(SR.Format(SR.Argument_CodepageNotSupported, codepage), nameof(codepage));
            }

            // Is it a valid code page?
            if (EncodingTable.GetCodePageDataItem(codepage) == null)
            {
                throw new NotSupportedException(
                    SR.Format(SR.NotSupported_NoCodepageData, codepage));
            }

            return UTF8;
        }

        [Pure]
        public static Encoding GetEncoding(int codepage,
            EncoderFallback encoderFallback, DecoderFallback decoderFallback)
        {
            Encoding baseEncoding = EncodingProvider.GetEncodingFromProvider(codepage, encoderFallback, decoderFallback);

            if (baseEncoding != null)
                return baseEncoding;

            // Get the default encoding (which is cached and read only)
            baseEncoding = GetEncoding(codepage);

            // Clone it and set the fallback
            Encoding fallbackEncoding = (Encoding)baseEncoding.Clone();
            fallbackEncoding.EncoderFallback = encoderFallback;
            fallbackEncoding.DecoderFallback = decoderFallback;

            return fallbackEncoding;
        }
        // Returns an Encoding object for a given name or a given code page value.
        //
        [Pure]
        public static Encoding GetEncoding(String name)
        {
            Encoding baseEncoding = EncodingProvider.GetEncodingFromProvider(name);
            if (baseEncoding != null)
                return baseEncoding;

            //
            // NOTE: If you add a new encoding that can be requested by name, be sure to
            // add the corresponding item in EncodingTable.
            // Otherwise, the code below will throw exception when trying to call
            // EncodingTable.GetCodePageFromName().
            //
            return (GetEncoding(EncodingTable.GetCodePageFromName(name)));
        }

        // Returns an Encoding object for a given name or a given code page value.
        //
        [Pure]
        public static Encoding GetEncoding(String name,
            EncoderFallback encoderFallback, DecoderFallback decoderFallback)
        {
            Encoding baseEncoding = EncodingProvider.GetEncodingFromProvider(name, encoderFallback, decoderFallback);
            if (baseEncoding != null)
                return baseEncoding;

            //
            // NOTE: If you add a new encoding that can be requested by name, be sure to
            // add the corresponding item in EncodingTable.
            // Otherwise, the code below will throw exception when trying to call
            // EncodingTable.GetCodePageFromName().
            //
            return (GetEncoding(EncodingTable.GetCodePageFromName(name), encoderFallback, decoderFallback));
        }

        // Return a list of all EncodingInfo objects describing all of our encodings
        [Pure]
        public static EncodingInfo[] GetEncodings()
        {
            return EncodingTable.GetEncodings();
        }

        [Pure]
        public virtual byte[] GetPreamble()
        {
            return Array.Empty<Byte>();
        }

        private void GetDataItem()
        {
            if (dataItem == null)
            {
                dataItem = EncodingTable.GetCodePageDataItem(m_codePage);
                if (dataItem == null)
                {
                    throw new NotSupportedException(
                        SR.Format(SR.NotSupported_NoCodepageData, m_codePage));
                }
            }
        }

        // Returns the name for this encoding that can be used with mail agent body tags.
        // If the encoding may not be used, the string is empty.

        public virtual String BodyName
        {
            get
            {
                if (dataItem == null)
                {
                    GetDataItem();
                }
                return (dataItem.BodyName);
            }
        }

        // Returns the human-readable description of the encoding ( e.g. Hebrew (DOS)).

        public virtual String EncodingName
        {
            get
            {
                return SR.GetResourceString("Globalization_cp_" + m_codePage.ToString());
            }
        }

        // Returns the name for this encoding that can be used with mail agent header
        // tags.  If the encoding may not be used, the string is empty.

        public virtual String HeaderName
        {
            get
            {
                if (dataItem == null)
                {
                    GetDataItem();
                }
                return (dataItem.HeaderName);
            }
        }

        // Returns the array of IANA-registered names for this encoding.  If there is an
        // IANA preferred name, it is the first name in the array.

        public virtual String WebName
        {
            get
            {
                if (dataItem == null)
                {
                    GetDataItem();
                }
                return (dataItem.WebName);
            }
        }

        // Returns the windows code page that most closely corresponds to this encoding.

        public virtual int WindowsCodePage
        {
            get
            {
                if (dataItem == null)
                {
                    GetDataItem();
                }
                return (dataItem.UIFamilyCodePage);
            }
        }


        // True if and only if the encoding is used for display by browsers clients.

        public virtual bool IsBrowserDisplay
        {
            get
            {
                if (dataItem == null)
                {
                    GetDataItem();
                }
                return ((dataItem.Flags & MIMECONTF_BROWSER) != 0);
            }
        }

        // True if and only if the encoding is used for saving by browsers clients.

        public virtual bool IsBrowserSave
        {
            get
            {
                if (dataItem == null)
                {
                    GetDataItem();
                }
                return ((dataItem.Flags & MIMECONTF_SAVABLE_BROWSER) != 0);
            }
        }

        // True if and only if the encoding is used for display by mail and news clients.

        public virtual bool IsMailNewsDisplay
        {
            get
            {
                if (dataItem == null)
                {
                    GetDataItem();
                }
                return ((dataItem.Flags & MIMECONTF_MAILNEWS) != 0);
            }
        }


        // True if and only if the encoding is used for saving documents by mail and
        // news clients

        public virtual bool IsMailNewsSave
        {
            get
            {
                if (dataItem == null)
                {
                    GetDataItem();
                }
                return ((dataItem.Flags & MIMECONTF_SAVABLE_MAILNEWS) != 0);
            }
        }

        // True if and only if the encoding only uses single byte code points.  (Ie, ASCII, 1252, etc)

        public virtual bool IsSingleByte
        {
            get
            {
                return false;
            }
        }


        public EncoderFallback EncoderFallback
        {
            get
            {
                return encoderFallback;
            }

            set
            {
                if (this.IsReadOnly)
                    throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);

                if (value == null)
                    throw new ArgumentNullException(nameof(value));
                Contract.EndContractBlock();

                encoderFallback = value;
            }
        }


        public DecoderFallback DecoderFallback
        {
            get
            {
                return decoderFallback;
            }

            set
            {
                if (this.IsReadOnly)
                    throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);

                if (value == null)
                    throw new ArgumentNullException(nameof(value));
                Contract.EndContractBlock();

                decoderFallback = value;
            }
        }


        public virtual Object Clone()
        {
            Encoding newEncoding = (Encoding)this.MemberwiseClone();

            // New one should be readable
            newEncoding.m_isReadOnly = false;
            return newEncoding;
        }


        public bool IsReadOnly
        {
            get
            {
                return (m_isReadOnly);
            }
        }


        // Returns an encoding for the ASCII character set. The returned encoding
        // will be an instance of the ASCIIEncoding class.

        public static Encoding ASCII => ASCIIEncoding.s_default;

        // Returns an encoding for the Latin1 character set. The returned encoding
        // will be an instance of the Latin1Encoding class.
        //
        // This is for our optimizations
        private static Encoding Latin1 => Latin1Encoding.s_default;

        // Returns the number of bytes required to encode the given character
        // array.
        //
        [Pure]
        public virtual int GetByteCount(char[] chars)
        {
            if (chars == null)
            {
                throw new ArgumentNullException(nameof(chars),
                    SR.ArgumentNull_Array);
            }
            Contract.EndContractBlock();

            return GetByteCount(chars, 0, chars.Length);
        }

        [Pure]
        public virtual int GetByteCount(String s)
        {
            if (s == null)
                throw new ArgumentNullException(nameof(s));
            Contract.EndContractBlock();

            char[] chars = s.ToCharArray();
            return GetByteCount(chars, 0, chars.Length);
        }

        // Returns the number of bytes required to encode a range of characters in
        // a character array.
        //
        [Pure]
        public abstract int GetByteCount(char[] chars, int index, int count);

        // Returns the number of bytes required to encode a string range.
        //
        [Pure]
        public int GetByteCount(string s, int index, int count)
        {
            if (s == null)
                throw new ArgumentNullException(nameof(s),
                    SR.ArgumentNull_String);
            if (index < 0)
                throw new ArgumentOutOfRangeException(nameof(index),
                      SR.ArgumentOutOfRange_NeedNonNegNum);
            if (count < 0)
                throw new ArgumentOutOfRangeException(nameof(count),
                      SR.ArgumentOutOfRange_NeedNonNegNum);
            if (index > s.Length - count)
                throw new ArgumentOutOfRangeException(nameof(index),
                      SR.ArgumentOutOfRange_IndexCount);
            Contract.EndContractBlock();

            unsafe
            {
                fixed (char* pChar = s)
                {
                    return GetByteCount(pChar + index, count);
                }
            }
        }

        // We expect this to be the workhorse for NLS encodings
        // unfortunately for existing overrides, it has to call the [] version,
        // which is really slow, so this method should be avoided if you're calling
        // a 3rd party encoding.
        [Pure]
        [CLSCompliant(false)]
        public virtual unsafe int GetByteCount(char* chars, int count)
        {
            // Validate input parameters
            if (chars == null)
                throw new ArgumentNullException(nameof(chars),
                      SR.ArgumentNull_Array);

            if (count < 0)
                throw new ArgumentOutOfRangeException(nameof(count),
                      SR.ArgumentOutOfRange_NeedNonNegNum);
            Contract.EndContractBlock();

            char[] arrChar = new char[count];
            int index;

            for (index = 0; index < count; index++)
                arrChar[index] = chars[index];

            return GetByteCount(arrChar, 0, count);
        }

        // For NLS Encodings, workhorse takes an encoder (may be null)
        // Always validate parameters before calling internal version, which will only assert.
        internal virtual unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
        {
            Contract.Requires(chars != null);
            Contract.Requires(count >= 0);

            return GetByteCount(chars, count);
        }

        // Returns a byte array containing the encoded representation of the given
        // character array.
        //
        [Pure]
        public virtual byte[] GetBytes(char[] chars)
        {
            if (chars == null)
            {
                throw new ArgumentNullException(nameof(chars),
                    SR.ArgumentNull_Array);
            }
            Contract.EndContractBlock();
            return GetBytes(chars, 0, chars.Length);
        }

        // Returns a byte array containing the encoded representation of a range
        // of characters in a character array.
        //
        [Pure]
        public virtual byte[] GetBytes(char[] chars, int index, int count)
        {
            byte[] result = new byte[GetByteCount(chars, index, count)];
            GetBytes(chars, index, count, result, 0);
            return result;
        }

        // Encodes a range of characters in a character array into a range of bytes
        // in a byte array. An exception occurs if the byte array is not large
        // enough to hold the complete encoding of the characters. The
        // GetByteCount method can be used to determine the exact number of
        // bytes that will be produced for a given range of characters.
        // Alternatively, the GetMaxByteCount method can be used to
        // determine the maximum number of bytes that will be produced for a given
        // number of characters, regardless of the actual character values.
        //
        public abstract int GetBytes(char[] chars, int charIndex, int charCount,
            byte[] bytes, int byteIndex);

        // Returns a byte array containing the encoded representation of the given
        // string.
        //
        [Pure]
        public virtual byte[] GetBytes(String s)
        {
            if (s == null)
                throw new ArgumentNullException(nameof(s),
                    SR.ArgumentNull_String);
            Contract.EndContractBlock();

            int byteCount = GetByteCount(s);
            byte[] bytes = new byte[byteCount];
            int bytesReceived = GetBytes(s, 0, s.Length, bytes, 0);
            Debug.Assert(byteCount == bytesReceived);
            return bytes;
        }

        // Returns a byte array containing the encoded representation of the given
        // string range.
        //
        [Pure]
        public byte[] GetBytes(string s, int index, int count)
        {
            if (s == null)
                throw new ArgumentNullException(nameof(s),
                    SR.ArgumentNull_String);
            if (index < 0)
                throw new ArgumentOutOfRangeException(nameof(index),
                      SR.ArgumentOutOfRange_NeedNonNegNum);
            if (count < 0)
                throw new ArgumentOutOfRangeException(nameof(count),
                      SR.ArgumentOutOfRange_NeedNonNegNum);
            if (index > s.Length - count)
                throw new ArgumentOutOfRangeException(nameof(index),
                      SR.ArgumentOutOfRange_IndexCount);
            Contract.EndContractBlock();

            unsafe
            {
                fixed (char* pChar = s)
                {
                    int byteCount = GetByteCount(pChar + index, count);
                    if (byteCount == 0)
                        return Array.Empty<byte>();

                    byte[] bytes = new byte[byteCount];
                    fixed (byte* pBytes = &bytes[0])
                    {
                        int bytesReceived = GetBytes(pChar + index, count, pBytes, byteCount);
                        Debug.Assert(byteCount == bytesReceived);
                    }
                    return bytes;
                }
            }
        }

        public virtual int GetBytes(String s, int charIndex, int charCount,
                                       byte[] bytes, int byteIndex)
        {
            if (s == null)
                throw new ArgumentNullException(nameof(s));
            Contract.EndContractBlock();
            return GetBytes(s.ToCharArray(), charIndex, charCount, bytes, byteIndex);
        }

        // This is our internal workhorse
        // Always validate parameters before calling internal version, which will only assert.
        internal virtual unsafe int GetBytes(char* chars, int charCount,
                                                byte* bytes, int byteCount, EncoderNLS encoder)
        {
            return GetBytes(chars, charCount, bytes, byteCount);
        }

        // We expect this to be the workhorse for NLS Encodings, but for existing
        // ones we need a working (if slow) default implimentation)
        //
        // WARNING WARNING WARNING
        //
        // WARNING: If this breaks it could be a security threat.  Obviously we
        // call this internally, so you need to make sure that your pointers, counts
        // and indexes are correct when you call this method.
        //
        // In addition, we have internal code, which will be marked as "safe" calling
        // this code.  However this code is dependent upon the implimentation of an
        // external GetBytes() method, which could be overridden by a third party and
        // the results of which cannot be guaranteed.  We use that result to copy
        // the byte[] to our byte* output buffer.  If the result count was wrong, we
        // could easily overflow our output buffer.  Therefore we do an extra test
        // when we copy the buffer so that we don't overflow byteCount either.

        [CLSCompliant(false)]
        public virtual unsafe int GetBytes(char* chars, int charCount,
                                              byte* bytes, int byteCount)
        {
            // Validate input parameters
            if (bytes == null || chars == null)
                throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
                    SR.ArgumentNull_Array);

            if (charCount < 0 || byteCount < 0)
                throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)),
                    SR.ArgumentOutOfRange_NeedNonNegNum);
            Contract.EndContractBlock();

            // Get the char array to convert
            char[] arrChar = new char[charCount];

            int index;
            for (index = 0; index < charCount; index++)
                arrChar[index] = chars[index];

            // Get the byte array to fill
            byte[] arrByte = new byte[byteCount];

            // Do the work
            int result = GetBytes(arrChar, 0, charCount, arrByte, 0);

            Debug.Assert(result <= byteCount, "[Encoding.GetBytes]Returned more bytes than we have space for");

            // Copy the byte array
            // WARNING: We MUST make sure that we don't copy too many bytes.  We can't
            // rely on result because it could be a 3rd party implimentation.  We need
            // to make sure we never copy more than byteCount bytes no matter the value
            // of result
            if (result < byteCount)
                byteCount = result;

            // Copy the data, don't overrun our array!
            for (index = 0; index < byteCount; index++)
                bytes[index] = arrByte[index];

            return byteCount;
        }

        // Returns the number of characters produced by decoding the given byte
        // array.
        //
        [Pure]
        public virtual int GetCharCount(byte[] bytes)
        {
            if (bytes == null)
            {
                throw new ArgumentNullException(nameof(bytes),
                    SR.ArgumentNull_Array);
            }
            Contract.EndContractBlock();
            return GetCharCount(bytes, 0, bytes.Length);
        }

        // Returns the number of characters produced by decoding a range of bytes
        // in a byte array.
        //
        [Pure]
        public abstract int GetCharCount(byte[] bytes, int index, int count);

        // We expect this to be the workhorse for NLS Encodings, but for existing
        // ones we need a working (if slow) default implimentation)
        [Pure]
        [CLSCompliant(false)]
        public virtual unsafe int GetCharCount(byte* bytes, int count)
        {
            // Validate input parameters
            if (bytes == null)
                throw new ArgumentNullException(nameof(bytes),
                      SR.ArgumentNull_Array);

            if (count < 0)
                throw new ArgumentOutOfRangeException(nameof(count),
                      SR.ArgumentOutOfRange_NeedNonNegNum);
            Contract.EndContractBlock();

            byte[] arrbyte = new byte[count];
            int index;

            for (index = 0; index < count; index++)
                arrbyte[index] = bytes[index];

            return GetCharCount(arrbyte, 0, count);
        }

        // This is our internal workhorse
        // Always validate parameters before calling internal version, which will only assert.
        internal virtual unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder)
        {
            return GetCharCount(bytes, count);
        }

        // Returns a character array containing the decoded representation of a
        // given byte array.
        //
        [Pure]
        public virtual char[] GetChars(byte[] bytes)
        {
            if (bytes == null)
            {
                throw new ArgumentNullException(nameof(bytes),
                    SR.ArgumentNull_Array);
            }
            Contract.EndContractBlock();
            return GetChars(bytes, 0, bytes.Length);
        }

        // Returns a character array containing the decoded representation of a
        // range of bytes in a byte array.
        //
        [Pure]
        public virtual char[] GetChars(byte[] bytes, int index, int count)
        {
            char[] result = new char[GetCharCount(bytes, index, count)];
            GetChars(bytes, index, count, result, 0);
            return result;
        }

        // Decodes a range of bytes in a byte array into a range of characters in a
        // character array. An exception occurs if the character array is not large
        // enough to hold the complete decoding of the bytes. The
        // GetCharCount method can be used to determine the exact number of
        // characters that will be produced for a given range of bytes.
        // Alternatively, the GetMaxCharCount method can be used to
        // determine the maximum number of characterss that will be produced for a
        // given number of bytes, regardless of the actual byte values.
        //

        public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount,
                                       char[] chars, int charIndex);


        // We expect this to be the workhorse for NLS Encodings, but for existing
        // ones we need a working (if slow) default implimentation)
        //
        // WARNING WARNING WARNING
        //
        // WARNING: If this breaks it could be a security threat.  Obviously we
        // call this internally, so you need to make sure that your pointers, counts
        // and indexes are correct when you call this method.
        //
        // In addition, we have internal code, which will be marked as "safe" calling
        // this code.  However this code is dependent upon the implimentation of an
        // external GetChars() method, which could be overridden by a third party and
        // the results of which cannot be guaranteed.  We use that result to copy
        // the char[] to our char* output buffer.  If the result count was wrong, we
        // could easily overflow our output buffer.  Therefore we do an extra test
        // when we copy the buffer so that we don't overflow charCount either.

        [CLSCompliant(false)]
        public virtual unsafe int GetChars(byte* bytes, int byteCount,
                                              char* chars, int charCount)
        {
            // Validate input parameters
            if (chars == null || bytes == null)
                throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes),
                    SR.ArgumentNull_Array);

            if (byteCount < 0 || charCount < 0)
                throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)),
                    SR.ArgumentOutOfRange_NeedNonNegNum);
            Contract.EndContractBlock();

            // Get the byte array to convert
            byte[] arrByte = new byte[byteCount];

            int index;
            for (index = 0; index < byteCount; index++)
                arrByte[index] = bytes[index];

            // Get the char array to fill
            char[] arrChar = new char[charCount];

            // Do the work
            int result = GetChars(arrByte, 0, byteCount, arrChar, 0);

            Debug.Assert(result <= charCount, "[Encoding.GetChars]Returned more chars than we have space for");

            // Copy the char array
            // WARNING: We MUST make sure that we don't copy too many chars.  We can't
            // rely on result because it could be a 3rd party implimentation.  We need
            // to make sure we never copy more than charCount chars no matter the value
            // of result
            if (result < charCount)
                charCount = result;

            // Copy the data, don't overrun our array!
            for (index = 0; index < charCount; index++)
                chars[index] = arrChar[index];

            return charCount;
        }


        // This is our internal workhorse
        // Always validate parameters before calling internal version, which will only assert.
        internal virtual unsafe int GetChars(byte* bytes, int byteCount,
                                                char* chars, int charCount, DecoderNLS decoder)
        {
            return GetChars(bytes, byteCount, chars, charCount);
        }


        [CLSCompliant(false)]
        public unsafe string GetString(byte* bytes, int byteCount)
        {
            if (bytes == null)
                throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array);

            if (byteCount < 0)
                throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum);
            Contract.EndContractBlock();

            return String.CreateStringFromEncoding(bytes, byteCount, this);
        }

        // Returns the code page identifier of this encoding. The returned value is
        // an integer between 0 and 65535 if the encoding has a code page
        // identifier, or -1 if the encoding does not represent a code page.
        //

        public virtual int CodePage
        {
            get
            {
                return m_codePage;
            }
        }

        // IsAlwaysNormalized
        // Returns true if the encoding is always normalized for the specified encoding form
        [Pure]
        public bool IsAlwaysNormalized()
        {
            return this.IsAlwaysNormalized(NormalizationForm.FormC);
        }

        [Pure]
        public virtual bool IsAlwaysNormalized(NormalizationForm form)
        {
            // Assume false unless the encoding knows otherwise
            return false;
        }

        // Returns a Decoder object for this encoding. The returned object
        // can be used to decode a sequence of bytes into a sequence of characters.
        // Contrary to the GetChars family of methods, a Decoder can
        // convert partial sequences of bytes into partial sequences of characters
        // by maintaining the appropriate state between the conversions.
        //
        // This default implementation returns a Decoder that simply
        // forwards calls to the GetCharCount and GetChars methods to
        // the corresponding methods of this encoding. Encodings that require state
        // to be maintained between successive conversions should override this
        // method and return an instance of an appropriate Decoder
        // implementation.
        //

        public virtual Decoder GetDecoder()
        {
            return new DefaultDecoder(this);
        }

        // Returns an Encoder object for this encoding. The returned object
        // can be used to encode a sequence of characters into a sequence of bytes.
        // Contrary to the GetBytes family of methods, an Encoder can
        // convert partial sequences of characters into partial sequences of bytes
        // by maintaining the appropriate state between the conversions.
        //
        // This default implementation returns an Encoder that simply
        // forwards calls to the GetByteCount and GetBytes methods to
        // the corresponding methods of this encoding. Encodings that require state
        // to be maintained between successive conversions should override this
        // method and return an instance of an appropriate Encoder
        // implementation.
        //

        public virtual Encoder GetEncoder()
        {
            return new DefaultEncoder(this);
        }

        // Returns the maximum number of bytes required to encode a given number of
        // characters. This method can be used to determine an appropriate buffer
        // size for byte arrays passed to the GetBytes method of this
        // encoding or the GetBytes method of an Encoder for this
        // encoding. All encodings must guarantee that no buffer overflow
        // exceptions will occur if buffers are sized according to the results of
        // this method.
        //
        // WARNING: If you're using something besides the default replacement encoder fallback,
        // then you could have more bytes than this returned from an actual call to GetBytes().
        //
        [Pure]
        public abstract int GetMaxByteCount(int charCount);

        // Returns the maximum number of characters produced by decoding a given
        // number of bytes. This method can be used to determine an appropriate
        // buffer size for character arrays passed to the GetChars method of
        // this encoding or the GetChars method of a Decoder for this
        // encoding. All encodings must guarantee that no buffer overflow
        // exceptions will occur if buffers are sized according to the results of
        // this method.
        //
        [Pure]
        public abstract int GetMaxCharCount(int byteCount);

        // Returns a string containing the decoded representation of a given byte
        // array.
        //
        [Pure]
        public virtual String GetString(byte[] bytes)
        {
            if (bytes == null)
                throw new ArgumentNullException(nameof(bytes),
                    SR.ArgumentNull_Array);
            Contract.EndContractBlock();

            return GetString(bytes, 0, bytes.Length);
        }

        // Returns a string containing the decoded representation of a range of
        // bytes in a byte array.
        //
        // Internally we override this for performance
        //
        [Pure]
        public virtual String GetString(byte[] bytes, int index, int count)
        {
            return new String(GetChars(bytes, index, count));
        }

        // Returns an encoding for Unicode format. The returned encoding will be
        // an instance of the UnicodeEncoding class.
        //
        // It will use little endian byte order, but will detect
        // input in big endian if it finds a byte order mark per Unicode 2.0.

        public static Encoding Unicode => UnicodeEncoding.s_littleEndianDefault;

        // Returns an encoding for Unicode format. The returned encoding will be
        // an instance of the UnicodeEncoding class.
        //
        // It will use big endian byte order, but will detect
        // input in little endian if it finds a byte order mark per Unicode 2.0.

        public static Encoding BigEndianUnicode => UnicodeEncoding.s_bigEndianDefault;

        // Returns an encoding for the UTF-7 format. The returned encoding will be
        // an instance of the UTF7Encoding class.

        public static Encoding UTF7 => UTF7Encoding.s_default;

        // Returns an encoding for the UTF-8 format. The returned encoding will be
        // an instance of the UTF8Encoding class.

        public static Encoding UTF8 => UTF8Encoding.s_default;

        // Returns an encoding for the UTF-32 format. The returned encoding will be
        // an instance of the UTF32Encoding class.

        public static Encoding UTF32 => UTF32Encoding.s_default;

        // Returns an encoding for the UTF-32 format. The returned encoding will be
        // an instance of the UTF32Encoding class.
        //
        // It will use big endian byte order.

        private static Encoding BigEndianUTF32 => UTF32Encoding.s_bigEndianDefault;

        public override bool Equals(Object value)
        {
            Encoding that = value as Encoding;
            if (that != null)
                return (m_codePage == that.m_codePage) &&
                       (EncoderFallback.Equals(that.EncoderFallback)) &&
                       (DecoderFallback.Equals(that.DecoderFallback));
            return (false);
        }


        public override int GetHashCode()
        {
            return m_codePage + this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode();
        }

        internal virtual char[] GetBestFitUnicodeToBytesData()
        {
            // Normally we don't have any best fit data.
            return Array.Empty<Char>();
        }

        internal virtual char[] GetBestFitBytesToUnicodeData()
        {
            // Normally we don't have any best fit data.
            return Array.Empty<Char>();
        }

        internal void ThrowBytesOverflow()
        {
            // Special message to include fallback type in case fallback's GetMaxCharCount is broken
            // This happens if user has implimented an encoder fallback with a broken GetMaxCharCount
            throw new ArgumentException(
                SR.Format(SR.Argument_EncodingConversionOverflowBytes, EncodingName, EncoderFallback.GetType()), "bytes");
        }

        internal void ThrowBytesOverflow(EncoderNLS encoder, bool nothingEncoded)
        {
            if (encoder == null || encoder.m_throwOnOverflow || nothingEncoded)
            {
                if (encoder != null && encoder.InternalHasFallbackBuffer)
                    encoder.FallbackBuffer.InternalReset();
                // Special message to include fallback type in case fallback's GetMaxCharCount is broken
                // This happens if user has implimented an encoder fallback with a broken GetMaxCharCount
                ThrowBytesOverflow();
            }

            // If we didn't throw, we are in convert and have to remember our flushing
            encoder.ClearMustFlush();
        }

        internal void ThrowCharsOverflow()
        {
            // Special message to include fallback type in case fallback's GetMaxCharCount is broken
            // This happens if user has implimented a decoder fallback with a broken GetMaxCharCount
            throw new ArgumentException(
                SR.Format(SR.Argument_EncodingConversionOverflowChars, EncodingName, DecoderFallback.GetType()), "chars");
        }

        internal void ThrowCharsOverflow(DecoderNLS decoder, bool nothingDecoded)
        {
            if (decoder == null || decoder.m_throwOnOverflow || nothingDecoded)
            {
                if (decoder != null && decoder.InternalHasFallbackBuffer)
                    decoder.FallbackBuffer.InternalReset();

                // Special message to include fallback type in case fallback's GetMaxCharCount is broken
                // This happens if user has implimented a decoder fallback with a broken GetMaxCharCount
                ThrowCharsOverflow();
            }

            // If we didn't throw, we are in convert and have to remember our flushing
            decoder.ClearMustFlush();
        }

        internal sealed class DefaultEncoder : Encoder, IObjectReference, ISerializable
        {
            private Encoding m_encoding;
            [NonSerialized] private bool m_hasInitializedEncoding;

            [NonSerialized] internal char charLeftOver;

            public DefaultEncoder(Encoding encoding)
            {
                m_encoding = encoding;
                m_hasInitializedEncoding = true;
            }
            
            public Object GetRealObject(StreamingContext context)
            {
                throw new PlatformNotSupportedException();
            }

            // ISerializable implementation, get data for this object
            void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
            {
                throw new PlatformNotSupportedException();
            }

            // Returns the number of bytes the next call to GetBytes will
            // produce if presented with the given range of characters and the given
            // value of the flush parameter. The returned value takes into
            // account the state in which the encoder was left following the last call
            // to GetBytes. The state of the encoder is not affected by a call
            // to this method.
            //

            public override int GetByteCount(char[] chars, int index, int count, bool flush)
            {
                return m_encoding.GetByteCount(chars, index, count);
            }

            [SuppressMessage("Microsoft.Contracts", "CC1055")]  // Skip extra error checking to avoid *potential* AppCompat problems.
            public unsafe override int GetByteCount(char* chars, int count, bool flush)
            {
                return m_encoding.GetByteCount(chars, count);
            }

            // Encodes a range of characters in a character array into a range of bytes
            // in a byte array. The method encodes charCount characters from
            // chars starting at index charIndex, storing the resulting
            // bytes in bytes starting at index byteIndex. The encoding
            // takes into account the state in which the encoder was left following the
            // last call to this method. The flush parameter indicates whether
            // the encoder should flush any shift-states and partial characters at the
            // end of the conversion. To ensure correct termination of a sequence of
            // blocks of encoded bytes, the last call to GetBytes should specify
            // a value of true for the flush parameter.
            //
            // An exception occurs if the byte array is not large enough to hold the
            // complete encoding of the characters. The GetByteCount method can
            // be used to determine the exact number of bytes that will be produced for
            // a given range of characters. Alternatively, the GetMaxByteCount
            // method of the Encoding that produced this encoder can be used to
            // determine the maximum number of bytes that will be produced for a given
            // number of characters, regardless of the actual character values.
            //

            public override int GetBytes(char[] chars, int charIndex, int charCount,
                                          byte[] bytes, int byteIndex, bool flush)
            {
                return m_encoding.GetBytes(chars, charIndex, charCount, bytes, byteIndex);
            }

            [SuppressMessage("Microsoft.Contracts", "CC1055")]  // Skip extra error checking to avoid *potential* AppCompat problems.
            public unsafe override int GetBytes(char* chars, int charCount,
                                                 byte* bytes, int byteCount, bool flush)
            {
                return m_encoding.GetBytes(chars, charCount, bytes, byteCount);
            }
        }

        internal sealed class DefaultDecoder : Decoder, IObjectReference, ISerializable
        {
            private Encoding m_encoding;
            [NonSerialized]
            private bool m_hasInitializedEncoding;

            public DefaultDecoder(Encoding encoding)
            {
                m_encoding = encoding;
                m_hasInitializedEncoding = true;
            }

            public Object GetRealObject(StreamingContext context)
            {
                throw new PlatformNotSupportedException();
            }

            // ISerializable implementation
            void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
            {
                throw new PlatformNotSupportedException();
            }

            // Returns the number of characters the next call to GetChars will
            // produce if presented with the given range of bytes. The returned value
            // takes into account the state in which the decoder was left following the
            // last call to GetChars. The state of the decoder is not affected
            // by a call to this method.
            //

            public override int GetCharCount(byte[] bytes, int index, int count)
            {
                return GetCharCount(bytes, index, count, false);
            }

            public override int GetCharCount(byte[] bytes, int index, int count, bool flush)
            {
                return m_encoding.GetCharCount(bytes, index, count);
            }

            [SuppressMessage("Microsoft.Contracts", "CC1055")]  // Skip extra error checking to avoid *potential* AppCompat problems.
            public unsafe override int GetCharCount(byte* bytes, int count, bool flush)
            {
                // By default just call the encoding version, no flush by default
                return m_encoding.GetCharCount(bytes, count);
            }

            // Decodes a range of bytes in a byte array into a range of characters
            // in a character array. The method decodes byteCount bytes from
            // bytes starting at index byteIndex, storing the resulting
            // characters in chars starting at index charIndex. The
            // decoding takes into account the state in which the decoder was left
            // following the last call to this method.
            //
            // An exception occurs if the character array is not large enough to
            // hold the complete decoding of the bytes. The GetCharCount method
            // can be used to determine the exact number of characters that will be
            // produced for a given range of bytes. Alternatively, the
            // GetMaxCharCount method of the Encoding that produced this
            // decoder can be used to determine the maximum number of characters that
            // will be produced for a given number of bytes, regardless of the actual
            // byte values.
            //

            public override int GetChars(byte[] bytes, int byteIndex, int byteCount,
                                           char[] chars, int charIndex)
            {
                return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false);
            }

            public override int GetChars(byte[] bytes, int byteIndex, int byteCount,
                                           char[] chars, int charIndex, bool flush)
            {
                return m_encoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
            }

            [SuppressMessage("Microsoft.Contracts", "CC1055")]  // Skip extra error checking to avoid *potential* AppCompat problems.
            public unsafe override int GetChars(byte* bytes, int byteCount,
                                                  char* chars, int charCount, bool flush)
            {
                // By default just call the encoding's version
                return m_encoding.GetChars(bytes, byteCount, chars, charCount);
            }
        }

        internal class EncodingCharBuffer
        {
            private unsafe char* chars;
            private unsafe char* charStart;
            private unsafe char* charEnd;
            private int charCountResult = 0;
            private Encoding enc;
            private DecoderNLS decoder;
            private unsafe byte* byteStart;
            private unsafe byte* byteEnd;
            private unsafe byte* bytes;
            private DecoderFallbackBuffer fallbackBuffer;

            internal unsafe EncodingCharBuffer(Encoding enc, DecoderNLS decoder, char* charStart, int charCount,
                                                    byte* byteStart, int byteCount)
            {
                this.enc = enc;
                this.decoder = decoder;

                chars = charStart;
                this.charStart = charStart;
                charEnd = charStart + charCount;

                this.byteStart = byteStart;
                bytes = byteStart;
                byteEnd = byteStart + byteCount;

                if (this.decoder == null)
                    fallbackBuffer = enc.DecoderFallback.CreateFallbackBuffer();
                else
                    fallbackBuffer = this.decoder.FallbackBuffer;

                // If we're getting chars or getting char count we don't expect to have
                // to remember fallbacks between calls (so it should be empty)
                Debug.Assert(fallbackBuffer.Remaining == 0,
                    "[Encoding.EncodingCharBuffer.EncodingCharBuffer]Expected empty fallback buffer for getchars/charcount");
                fallbackBuffer.InternalInitialize(bytes, charEnd);
            }

            internal unsafe bool AddChar(char ch, int numBytes)
            {
                if (chars != null)
                {
                    if (chars >= charEnd)
                    {
                        // Throw maybe
                        bytes -= numBytes;                                        // Didn't encode these bytes
                        enc.ThrowCharsOverflow(decoder, bytes <= byteStart);    // Throw?
                        return false;                                           // No throw, but no store either
                    }

                    *(chars++) = ch;
                }
                charCountResult++;
                return true;
            }

            internal unsafe bool AddChar(char ch)
            {
                return AddChar(ch, 1);
            }

            internal unsafe void AdjustBytes(int count)
            {
                bytes += count;
            }

            internal unsafe bool MoreData
            {
                get
                {
                    return bytes < byteEnd;
                }
            }

            // GetNextByte shouldn't be called unless the caller's already checked more data or even more data,
            // but we'll double check just to make sure.
            internal unsafe byte GetNextByte()
            {
                Debug.Assert(bytes < byteEnd, "[EncodingCharBuffer.GetNextByte]Expected more date");
                if (bytes >= byteEnd)
                    return 0;
                return *(bytes++);
            }

            internal unsafe int BytesUsed
            {
                get
                {
                    return (int)(bytes - byteStart);
                }
            }

            internal unsafe bool Fallback(byte fallbackByte)
            {
                // Build our buffer
                byte[] byteBuffer = new byte[] { fallbackByte };

                // Do the fallback and add the data.
                return Fallback(byteBuffer);
            }

            internal unsafe bool Fallback(byte[] byteBuffer)
            {
                // Do the fallback and add the data.
                if (chars != null)
                {
                    char* pTemp = chars;
                    if (fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars) == false)
                    {
                        // Throw maybe
                        bytes -= byteBuffer.Length;                             // Didn't use how many ever bytes we're falling back
                        fallbackBuffer.InternalReset();                         // We didn't use this fallback.
                        enc.ThrowCharsOverflow(decoder, chars == charStart);    // Throw?
                        return false;                                           // No throw, but no store either
                    }
                    charCountResult += unchecked((int)(chars - pTemp));
                }
                else
                {
                    charCountResult += fallbackBuffer.InternalFallback(byteBuffer, bytes);
                }

                return true;
            }

            internal unsafe int Count
            {
                get
                {
                    return charCountResult;
                }
            }
        }

        internal class EncodingByteBuffer
        {
            private unsafe byte* bytes;
            private unsafe byte* byteStart;
            private unsafe byte* byteEnd;
            private unsafe char* chars;
            private unsafe char* charStart;
            private unsafe char* charEnd;
            private int byteCountResult = 0;
            private Encoding enc;
            private EncoderNLS encoder;
            internal EncoderFallbackBuffer fallbackBuffer;

            internal unsafe EncodingByteBuffer(Encoding inEncoding, EncoderNLS inEncoder,
                        byte* inByteStart, int inByteCount, char* inCharStart, int inCharCount)
            {
                enc = inEncoding;
                encoder = inEncoder;

                charStart = inCharStart;
                chars = inCharStart;
                charEnd = inCharStart + inCharCount;

                bytes = inByteStart;
                byteStart = inByteStart;
                byteEnd = inByteStart + inByteCount;

                if (encoder == null)
                    this.fallbackBuffer = enc.EncoderFallback.CreateFallbackBuffer();
                else
                {
                    this.fallbackBuffer = encoder.FallbackBuffer;
                    // If we're not converting we must not have data in our fallback buffer
                    if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer &&
                        this.fallbackBuffer.Remaining > 0)
                        throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, encoder.Encoding.EncodingName, encoder.Fallback.GetType()));
                }
                fallbackBuffer.InternalInitialize(chars, charEnd, encoder, bytes != null);
            }

            internal unsafe bool AddByte(byte b, int moreBytesExpected)
            {
                Debug.Assert(moreBytesExpected >= 0, "[EncodingByteBuffer.AddByte]expected non-negative moreBytesExpected");
                if (bytes != null)
                {
                    if (bytes >= byteEnd - moreBytesExpected)
                    {
                        // Throw maybe.  Check which buffer to back up (only matters if Converting)
                        this.MovePrevious(true);            // Throw if necessary
                        return false;                       // No throw, but no store either
                    }

                    *(bytes++) = b;
                }
                byteCountResult++;
                return true;
            }

            internal unsafe bool AddByte(byte b1)
            {
                return (AddByte(b1, 0));
            }

            internal unsafe bool AddByte(byte b1, byte b2)
            {
                return (AddByte(b1, b2, 0));
            }

            internal unsafe bool AddByte(byte b1, byte b2, int moreBytesExpected)
            {
                return (AddByte(b1, 1 + moreBytesExpected) && AddByte(b2, moreBytesExpected));
            }

            internal unsafe void MovePrevious(bool bThrow)
            {
                if (fallbackBuffer.bFallingBack)
                    fallbackBuffer.MovePrevious();                      // don't use last fallback
                else
                {
                    Debug.Assert(chars > charStart ||
                        ((bThrow == true) && (bytes == byteStart)),
                        "[EncodingByteBuffer.MovePrevious]expected previous data or throw");
                    if (chars > charStart)
                        chars--;                                        // don't use last char
                }

                if (bThrow)
                    enc.ThrowBytesOverflow(encoder, bytes == byteStart);    // Throw? (and reset fallback if not converting)
            }

            internal unsafe bool MoreData
            {
                get
                {
                    // See if fallbackBuffer is not empty or if there's data left in chars buffer.
                    return ((fallbackBuffer.Remaining > 0) || (chars < charEnd));
                }
            }

            internal unsafe char GetNextChar()
            {
                // See if there's something in our fallback buffer
                char cReturn = fallbackBuffer.InternalGetNextChar();

                // Nothing in the fallback buffer, return our normal data.
                if (cReturn == 0)
                {
                    if (chars < charEnd)
                        cReturn = *(chars++);
                }

                return cReturn;
            }

            internal unsafe int CharsUsed
            {
                get
                {
                    return (int)(chars - charStart);
                }
            }

            internal unsafe int Count
            {
                get
                {
                    return byteCountResult;
                }
            }
        }
    }
}