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 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143
|
//
// System.NumberFormatter.cs
//
// Author:
// Kazuki Oikawa (kazuki@panicode.com)
// Eyal Alaluf (eyala@mainsoft.com)
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
// Copyright (C) 2008 Mainsoft Co. (http://www.mainsoft.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Globalization;
using System.Text;
using System.Threading;
using System.Runtime.CompilerServices;
namespace System
{
internal sealed partial class NumberFormatter
{
#region Static Fields
const int DefaultExpPrecision = 6;
const int HundredMillion = 100000000;
const long SeventeenDigitsThreshold = 10000000000000000;
const ulong ULongDivHundredMillion = UInt64.MaxValue / HundredMillion;
const ulong ULongModHundredMillion = 1 + UInt64.MaxValue % HundredMillion;
const int DoubleBitsExponentShift = 52;
const int DoubleBitsExponentMask = 0x7ff;
const long DoubleBitsMantissaMask = 0xfffffffffffff;
const int DecimalBitsScaleMask = 0x1f0000;
const int SingleDefPrecision = 7;
const int DoubleDefPrecision = 15;
const int Int32DefPrecision = 10;
const int UInt32DefPrecision = 10;
const int Int64DefPrecision = 19;
const int UInt64DefPrecision = 20;
const int DecimalDefPrecision = 100;
const int TenPowersListLength = 19;
const double MinRoundtripVal = -1.79769313486231E+308;
const double MaxRoundtripVal = 1.79769313486231E+308;
// The below arrays are taken from mono/metatdata/number-formatter.h
private static readonly unsafe ulong* MantissaBitsTable;
private static readonly unsafe int* TensExponentTable;
private static readonly unsafe char* DigitLowerTable;
private static readonly unsafe char* DigitUpperTable;
private static readonly unsafe long* TenPowersList;
// DecHexDigits s a translation table from a decimal number to its
// digits hexadecimal representation (e.g. DecHexDigits [34] = 0x34).
private static readonly unsafe int* DecHexDigits;
[MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]
private unsafe static extern void GetFormatterTables (out ulong* MantissaBitsTable, out int* TensExponentTable,
out char* DigitLowerTable, out char* DigitUpperTable,
out long* TenPowersList, out int* DecHexDigits);
unsafe static NumberFormatter()
{
GetFormatterTables (out MantissaBitsTable, out TensExponentTable,
out DigitLowerTable, out DigitUpperTable, out TenPowersList, out DecHexDigits);
}
unsafe static long GetTenPowerOf(int i)
{
return TenPowersList [i];
}
#endregion Static Fields
#region Fields
private NumberFormatInfo _nfi;
//part of the private stringbuffer
private char[] _cbuf;
private bool _NaN;
private bool _infinity;
private bool _isCustomFormat;
private bool _specifierIsUpper;
private bool _positive;
private char _specifier;
private int _precision;
private int _defPrecision;
private int _digitsLen;
private int _offset; // Represent the first digit offset.
private int _decPointPos;
// The following fields are a hexadeimal representation of the digits.
// For instance _val = 0x234 represents the digits '2', '3', '4'.
private uint _val1; // Digits 0 - 7.
private uint _val2; // Digits 8 - 15.
private uint _val3; // Digits 16 - 23.
private uint _val4; // Digits 23 - 31. Only needed for decimals.
#endregion Fields
#region Constructor Helpers
// Translate an unsigned int to hexadecimal digits.
// i.e. 123456789 is represented by _val1 = 0x23456789 and _val2 = 0x1
private void InitDecHexDigits (uint value)
{
if (value >= HundredMillion) {
int div1 = (int)(value / HundredMillion);
value -= HundredMillion * (uint)div1;
_val2 = FastToDecHex (div1);
}
_val1 = ToDecHex ((int)value);
}
// Translate an unsigned long to hexadecimal digits.
private void InitDecHexDigits (ulong value)
{
if (value >= HundredMillion) {
long div1 = (long)(value / HundredMillion);
value -= HundredMillion * (ulong)div1;
if (div1 >= HundredMillion) {
int div2 = (int)(div1 / HundredMillion);
div1 = div1 - div2 * (long)HundredMillion;
_val3 = ToDecHex (div2);
}
if (div1 != 0)
_val2 = ToDecHex ((int)(div1));
}
if (value != 0)
_val1 = ToDecHex ((int)value);
}
// Translate a decimal integer to hexadecimal digits.
// The decimal integer is 96 digits and its value is hi * 2^64 + lo.
// is the lower 64 bits.
private void InitDecHexDigits (uint hi, ulong lo)
{
if (hi == 0) {
InitDecHexDigits (lo); // Only the lower 64 bits matter.
return;
}
// Compute (hi, lo) = (hi , lo) / HundredMillion.
uint divhi = hi / HundredMillion;
ulong remhi = hi - divhi * HundredMillion;
ulong divlo = lo / HundredMillion;
ulong remlo = lo - divlo * HundredMillion + remhi * ULongModHundredMillion;
hi = divhi;
lo = divlo + remhi * ULongDivHundredMillion;
divlo = remlo / HundredMillion;
remlo -= divlo * HundredMillion;
lo += divlo;
_val1 = ToDecHex ((int)remlo);
// Divide hi * 2 ^ 64 + lo by HundredMillion using the fact that
// hi < HundredMillion.
divlo = lo / HundredMillion;
remlo = lo - divlo * HundredMillion;
lo = divlo;
if (hi != 0) {
lo += hi * ULongDivHundredMillion;
remlo += hi * ULongModHundredMillion;
divlo = remlo / HundredMillion;
lo += divlo;
remlo -= divlo * HundredMillion;
}
_val2 = ToDecHex ((int)remlo);
// Now we are left with 64 bits store in lo.
if (lo >= HundredMillion) {
divlo = lo / HundredMillion;
lo -= divlo * HundredMillion;
_val4 = ToDecHex ((int)divlo);
}
_val3 = ToDecHex ((int)lo);
}
// Helper to translate an int in the range 0 .. 9999 to its
// Hexadecimal digits representation.
unsafe private static uint FastToDecHex (int val)
{
if (val < 100)
return (uint)DecHexDigits [val];
// Uses 2^19 (524288) to compute val / 100 for val < 10000.
int v = (val * 5243) >> 19;
return (uint)((DecHexDigits [v] << 8) | DecHexDigits [val - v * 100]);
}
// Helper to translate an int in the range 0 .. 99999999 to its
// Hexadecimal digits representation.
private static uint ToDecHex (int val)
{
uint res = 0;
if (val >= 10000) {
int v = val / 10000;
val -= v * 10000;
res = FastToDecHex (v) << 16;
}
return res | FastToDecHex (val);
}
// Helper to count number of hexadecimal digits in a number.
private static int FastDecHexLen (int val)
{
if (val < 0x100)
if (val < 0x10)
return 1;
else
return 2;
else if (val < 0x1000)
return 3;
else
return 4;
}
private static int DecHexLen (uint val)
{
if (val < 0x10000)
return FastDecHexLen ((int)val);
return 4 + FastDecHexLen ((int)(val >> 16));
}
// Count number of hexadecimal digits stored in _val1 .. _val4.
private int DecHexLen ()
{
if (_val4 != 0)
return DecHexLen (_val4) + 24;
else if (_val3 != 0)
return DecHexLen (_val3) + 16;
else if (_val2 != 0)
return DecHexLen (_val2) + 8;
else if (_val1 != 0)
return DecHexLen (_val1);
else
return 0;
}
// Helper to count the 10th scale (number of digits) in a number
private static int ScaleOrder (long hi)
{
for (int i = TenPowersListLength - 1; i >= 0; i--)
if (hi >= GetTenPowerOf (i))
return i + 1;
return 1;
}
// Compute the initial precision for rounding a floating number
// according to the used format.
int InitialFloatingPrecision ()
{
if (_specifier == 'R')
return _defPrecision + 2;
if (_precision < _defPrecision)
return _defPrecision;
if (_specifier == 'G')
return Math.Min (_defPrecision + 2, _precision);
if (_specifier == 'E')
return Math.Min (_defPrecision + 2, _precision + 1);
return _defPrecision;
}
// Parse the given format and extract the precision in it.
// Returns -1 for empty formats and -2 to indicate that the format
// is a custom format.
private static int ParsePrecision (string format)
{
int precision = 0;
for (int i = 1; i < format.Length; i++) {
int val = format [i] - '0';
precision = precision * 10 + val;
if (val < 0 || val > 9 || precision > 99)
return -2;
}
return precision;
}
#endregion Constructor Helpers
#region Constructors
// Parse the given format and initialize the following fields:
// _isCustomFormat, _specifierIsUpper, _specifier & _precision.
NumberFormatter (Thread current)
{
_cbuf = EmptyArray<char>.Value;
if (current == null)
return;
CurrentCulture = current.CurrentCulture;
}
private void Init (string format)
{
_val1 = _val2 = _val3 = _val4 = 0;
_offset = 0;
_NaN = _infinity = false;
_isCustomFormat = false;
_specifierIsUpper = true;
_precision = -1;
if (format == null || format.Length == 0) {
_specifier = 'G';
return;
}
char specifier = format [0];
if (specifier >= 'a' && specifier <= 'z') {
specifier = (char)(specifier - 'a' + 'A');
_specifierIsUpper = false;
}
else if (specifier < 'A' || specifier > 'Z') {
_isCustomFormat = true;
_specifier = '0';
return;
}
_specifier = specifier;
if (format.Length > 1) {
_precision = ParsePrecision (format);
if (_precision == -2) { // Is it a custom format?
_isCustomFormat = true;
_specifier = '0';
_precision = -1;
}
}
}
private void InitHex (ulong value)
{
switch (_defPrecision) {
case Int32DefPrecision: value = (uint) value; break;
}
_val1 = (uint)value;
_val2 = (uint)(value >> 32);
_decPointPos = _digitsLen = DecHexLen ();
if (value == 0)
_decPointPos = 1;
}
private void Init (string format, int value, int defPrecision)
{
Init (format);
_defPrecision = defPrecision;
_positive = value >= 0;
if (value == 0 || _specifier == 'X') {
InitHex ((ulong)value);
return;
}
if (value < 0)
value = -value;
InitDecHexDigits ((uint)value);
_decPointPos = _digitsLen = DecHexLen ();
}
private void Init (string format, uint value, int defPrecision)
{
Init (format);
_defPrecision = defPrecision;
_positive = true;
if (value == 0 || _specifier == 'X') {
InitHex (value);
return;
}
InitDecHexDigits (value);
_decPointPos = _digitsLen = DecHexLen ();
}
private void Init (string format, long value)
{
Init (format);
_defPrecision = Int64DefPrecision;
_positive = value >= 0;
if (value == 0 || _specifier == 'X') {
InitHex ((ulong)value);
return;
}
if (value < 0)
value = -value;
InitDecHexDigits ((ulong)value);
_decPointPos = _digitsLen = DecHexLen ();
}
private void Init (string format, ulong value)
{
Init (format);
_defPrecision = UInt64DefPrecision;
_positive = true;
if (value == 0 || _specifier == 'X') {
InitHex ((ulong)value);
return;
}
InitDecHexDigits (value);
_decPointPos = _digitsLen = DecHexLen ();
}
unsafe private void Init (string format, double value, int defPrecision)
{
Init (format);
_defPrecision = defPrecision;
long bits = BitConverter.DoubleToInt64Bits (value);
_positive = bits >= 0;
bits &= Int64.MaxValue;
if (bits == 0) {
_decPointPos = 1;
_digitsLen = 0;
_positive = true;
return;
}
int e = (int)(bits >> DoubleBitsExponentShift);
long m = bits & DoubleBitsMantissaMask;
if (e == DoubleBitsExponentMask) {
_NaN = m != 0;
_infinity = m == 0;
return;
}
int expAdjust = 0;
if (e == 0) {
// We need 'm' to be large enough so we won't lose precision.
e = 1;
int scale = ScaleOrder (m);
if (scale < DoubleDefPrecision) {
expAdjust = scale - DoubleDefPrecision;
m *= GetTenPowerOf (-expAdjust);
}
}
else {
m = (m + DoubleBitsMantissaMask + 1) * 10;
expAdjust = -1;
}
// multiply the mantissa by 10 ^ N
ulong lo = (uint)m;
ulong hi = (ulong)m >> 32;
ulong lo2 = MantissaBitsTable [e];
ulong hi2 = lo2 >> 32;
lo2 = (uint)lo2;
ulong mm = hi * lo2 + lo * hi2 + ((lo * lo2) >> 32);
long res = (long)(hi * hi2 + (mm >> 32));
while (res < SeventeenDigitsThreshold) {
mm = (mm & UInt32.MaxValue) * 10;
res = res * 10 + (long)(mm >> 32);
expAdjust--;
}
if ((mm & 0x80000000) != 0)
res++;
int order = DoubleDefPrecision + 2;
_decPointPos = TensExponentTable [e] + expAdjust + order;
// Rescale 'res' to the initial precision (15-17 for doubles).
int initialPrecision = InitialFloatingPrecision ();
if (order > initialPrecision) {
long val = GetTenPowerOf (order - initialPrecision);
res = (res + (val >> 1)) / val;
order = initialPrecision;
}
if (res >= GetTenPowerOf (order)) {
order++;
_decPointPos++;
}
InitDecHexDigits ((ulong)res);
_offset = CountTrailingZeros ();
_digitsLen = order - _offset;
}
private void Init (string format, decimal value)
{
Init (format);
_defPrecision = DecimalDefPrecision;
int[] bits = decimal.GetBits (value);
int scale = (bits [3] & DecimalBitsScaleMask) >> 16;
_positive = bits [3] >= 0;
if (bits [0] == 0 && bits [1] == 0 && bits [2] == 0) {
_decPointPos = -scale;
_positive = true;
_digitsLen = 0;
return;
}
InitDecHexDigits ((uint)bits [2], ((ulong)bits [1] << 32) | (uint)bits [0]);
_digitsLen = DecHexLen ();
_decPointPos = _digitsLen - scale;
if (_precision != -1 || _specifier != 'G') {
_offset = CountTrailingZeros ();
_digitsLen -= _offset;
}
}
#endregion Constructors
#region Inner String Buffer
//_cbuf moved to before other fields to improve layout
private int _ind;
private void ResetCharBuf (int size)
{
_ind = 0;
if (_cbuf.Length < size)
_cbuf = new char [size];
}
private void Resize (int len)
{
Array.Resize (ref _cbuf, len);
}
private void Append (char c)
{
if (_ind == _cbuf.Length)
Resize (_ind + 10);
_cbuf [_ind++] = c;
}
private void Append (char c, int cnt)
{
if (_ind + cnt > _cbuf.Length)
Resize (_ind + cnt + 10);
while (cnt-- > 0)
_cbuf [_ind++] = c;
}
private void Append (string s)
{
int slen = s.Length;
if (_ind + slen > _cbuf.Length)
Resize (_ind + slen + 10);
for (int i = 0; i < slen; i++)
_cbuf [_ind++] = s [i];
}
#endregion Inner String Buffer
#region Helper properties
private NumberFormatInfo GetNumberFormatInstance (IFormatProvider fp)
{
if (_nfi != null && fp == null)
return _nfi;
return NumberFormatInfo.GetInstance (fp);
}
CultureInfo CurrentCulture {
set {
if (value != null && value.IsReadOnly)
_nfi = value.NumberFormat;
else
_nfi = null;
}
}
private int IntegerDigits {
get { return _decPointPos > 0 ? _decPointPos : 1; }
}
private int DecimalDigits {
get { return _digitsLen > _decPointPos ? _digitsLen - _decPointPos : 0; }
}
private bool IsFloatingSource {
get { return _defPrecision == DoubleDefPrecision || _defPrecision == SingleDefPrecision; }
}
private bool IsZero {
get { return _digitsLen == 0; }
}
private bool IsZeroInteger {
get { return _digitsLen == 0 || _decPointPos <= 0; }
}
#endregion Helper properties
#region Round
private void RoundPos (int pos)
{
RoundBits (_digitsLen - pos);
}
private bool RoundDecimal (int decimals)
{
return RoundBits (_digitsLen - _decPointPos - decimals);
}
private bool RoundBits (int shift)
{
if (shift <= 0)
return false;
if (shift > _digitsLen) {
_digitsLen = 0;
_decPointPos = 1;
_val1 = _val2 = _val3 = _val4 = 0;
_positive = true;
return false;
}
shift += _offset;
_digitsLen += _offset;
while (shift > 8) {
_val1 = _val2;
_val2 = _val3;
_val3 = _val4;
_val4 = 0;
_digitsLen -= 8;
shift -= 8;
}
shift = (shift - 1) << 2;
uint v = _val1 >> shift;
uint rem16 = v & 0xf;
_val1 = (v ^ rem16) << shift;
bool res = false;
if (rem16 >= 0x5) {
_val1 |= 0x99999999 >> (28 - shift);
AddOneToDecHex ();
int newlen = DecHexLen ();
res = newlen != _digitsLen;
_decPointPos = _decPointPos + newlen - _digitsLen;
_digitsLen = newlen;
}
RemoveTrailingZeros ();
return res;
}
private void RemoveTrailingZeros ()
{
_offset = CountTrailingZeros ();
_digitsLen -= _offset;
if (_digitsLen == 0) {
_offset = 0;
_decPointPos = 1;
_positive = true;
}
}
private void AddOneToDecHex ()
{
if (_val1 == 0x99999999) {
_val1 = 0;
if (_val2 == 0x99999999) {
_val2 = 0;
if (_val3 == 0x99999999) {
_val3 = 0;
_val4 = AddOneToDecHex (_val4);
}
else
_val3 = AddOneToDecHex (_val3);
}
else
_val2 = AddOneToDecHex (_val2);
}
else
_val1 = AddOneToDecHex (_val1);
}
// Assume val != 0x99999999
private static uint AddOneToDecHex (uint val)
{
if ((val & 0xffff) == 0x9999)
if ((val & 0xffffff) == 0x999999)
if ((val & 0xfffffff) == 0x9999999)
return val + 0x06666667;
else
return val + 0x00666667;
else if ((val & 0xfffff) == 0x99999)
return val + 0x00066667;
else
return val + 0x00006667;
else if ((val & 0xff) == 0x99)
if ((val & 0xfff) == 0x999)
return val + 0x00000667;
else
return val + 0x00000067;
else if ((val & 0xf) == 0x9)
return val + 0x00000007;
else
return val + 1;
}
private int CountTrailingZeros ()
{
if (_val1 != 0)
return CountTrailingZeros (_val1);
if (_val2 != 0)
return CountTrailingZeros (_val2) + 8;
if (_val3 != 0)
return CountTrailingZeros (_val3) + 16;
if (_val4 != 0)
return CountTrailingZeros (_val4) + 24;
return _digitsLen;
}
private static int CountTrailingZeros (uint val)
{
if ((val & 0xffff) == 0)
if ((val & 0xffffff) == 0)
if ((val & 0xfffffff) == 0)
return 7;
else
return 6;
else if ((val & 0xfffff) == 0)
return 5;
else
return 4;
else if ((val & 0xff) == 0)
if ((val & 0xfff) == 0)
return 3;
else
return 2;
else if ((val & 0xf) == 0)
return 1;
else
return 0;
}
#endregion Round
#region public number formatting methods
[ThreadStatic]
static NumberFormatter threadNumberFormatter;
[ThreadStatic]
static NumberFormatter userFormatProvider;
private static NumberFormatter GetInstance (IFormatProvider fp)
{
if (fp != null) {
if (userFormatProvider == null) {
Interlocked.CompareExchange (ref userFormatProvider, new NumberFormatter (null), null);
}
return userFormatProvider;
}
NumberFormatter res = threadNumberFormatter;
threadNumberFormatter = null;
if (res == null)
return new NumberFormatter (Thread.CurrentThread);
res.CurrentCulture = Thread.CurrentThread.CurrentCulture;
return res;
}
private void Release()
{
if (this != userFormatProvider)
threadNumberFormatter = this;
}
public static string NumberToString (string format, uint value, IFormatProvider fp)
{
NumberFormatter inst = GetInstance (fp);
inst.Init (format, value, Int32DefPrecision);
string res = inst.IntegerToString (format, fp);
inst.Release();
return res;
}
public static string NumberToString (string format, int value, IFormatProvider fp)
{
NumberFormatter inst = GetInstance (fp);
inst.Init (format, value, UInt32DefPrecision);
string res = inst.IntegerToString (format, fp);
inst.Release();
return res;
}
public static string NumberToString (string format, ulong value, IFormatProvider fp)
{
NumberFormatter inst = GetInstance (fp);
inst.Init (format, value);
string res = inst.IntegerToString (format, fp);
inst.Release();
return res;
}
public static string NumberToString (string format, long value, IFormatProvider fp)
{
NumberFormatter inst = GetInstance (fp);
inst.Init (format, value);
string res = inst.IntegerToString (format, fp);
inst.Release();
return res;
}
public static string NumberToString (string format, float value, IFormatProvider fp)
{
NumberFormatter inst = GetInstance (fp);
inst.Init (format, value, SingleDefPrecision);
NumberFormatInfo nfi = inst.GetNumberFormatInstance (fp);
string res;
if (inst._NaN)
res = nfi.NaNSymbol;
else if (inst._infinity)
if (inst._positive)
res = nfi.PositiveInfinitySymbol;
else
res = nfi.NegativeInfinitySymbol;
else if (inst._specifier == 'R')
res = inst.FormatRoundtrip (value, nfi);
else
res = inst.NumberToString (format, nfi);
inst.Release();
return res;
}
public static string NumberToString (string format, double value, IFormatProvider fp)
{
NumberFormatter inst = GetInstance (fp);
inst.Init (format, value, DoubleDefPrecision);
NumberFormatInfo nfi = inst.GetNumberFormatInstance (fp);
string res;
if (inst._NaN)
res = nfi.NaNSymbol;
else if (inst._infinity)
if (inst._positive)
res = nfi.PositiveInfinitySymbol;
else
res = nfi.NegativeInfinitySymbol;
else if (inst._specifier == 'R')
res = inst.FormatRoundtrip (value, nfi);
else
res = inst.NumberToString (format, nfi);
inst.Release();
return res;
}
public static string NumberToString (string format, decimal value, IFormatProvider fp)
{
NumberFormatter inst = GetInstance (fp);
inst.Init (format, value);
string res = inst.NumberToString (format, inst.GetNumberFormatInstance (fp));
inst.Release();
return res;
}
private string IntegerToString (string format, IFormatProvider fp)
{
NumberFormatInfo nfi = GetNumberFormatInstance (fp);
switch (_specifier) {
case 'C':
return FormatCurrency (_precision, nfi);
case 'D':
return FormatDecimal (_precision, nfi);
case 'E':
return FormatExponential (_precision, nfi);
case 'F':
return FormatFixedPoint (_precision, nfi);
case 'G':
if (_precision <= 0)
return FormatDecimal (-1, nfi);
return FormatGeneral (_precision, nfi);
case 'N':
return FormatNumber (_precision, nfi);
case 'P':
return FormatPercent (_precision, nfi);
case 'X':
return FormatHexadecimal (_precision);
default:
if (_isCustomFormat)
return FormatCustom (format, nfi);
throw new FormatException ("The specified format '" + format + "' is invalid");
}
}
private string NumberToString (string format, NumberFormatInfo nfi)
{
switch (_specifier) {
case 'C':
return FormatCurrency (_precision, nfi);
case 'E':
return FormatExponential (_precision, nfi);
case 'F':
return FormatFixedPoint (_precision, nfi);
case 'G':
return FormatGeneral (_precision, nfi);
case 'N':
return FormatNumber (_precision, nfi);
case 'P':
return FormatPercent (_precision, nfi);
case 'X':
default:
if (_isCustomFormat)
return FormatCustom (format, nfi);
throw new FormatException ("The specified format '" + format + "' is invalid");
}
}
string FormatCurrency (int precision, NumberFormatInfo nfi)
{
precision = (precision >= 0 ? precision : nfi.CurrencyDecimalDigits);
RoundDecimal (precision);
ResetCharBuf (IntegerDigits * 2 + precision * 2 + 16);
if (_positive) {
switch (nfi.CurrencyPositivePattern) {
case 0:
Append (nfi.CurrencySymbol);
break;
case 2:
Append (nfi.CurrencySymbol);
Append (' ');
break;
}
}
else {
switch (nfi.CurrencyNegativePattern) {
case 0:
Append ('(');
Append (nfi.CurrencySymbol);
break;
case 1:
Append (nfi.NegativeSign);
Append (nfi.CurrencySymbol);
break;
case 2:
Append (nfi.CurrencySymbol);
Append (nfi.NegativeSign);
break;
case 3:
Append (nfi.CurrencySymbol);
break;
case 4:
Append ('(');
break;
case 5:
Append (nfi.NegativeSign);
break;
case 8:
Append (nfi.NegativeSign);
break;
case 9:
Append (nfi.NegativeSign);
Append (nfi.CurrencySymbol);
Append (' ');
break;
case 11:
Append (nfi.CurrencySymbol);
Append (' ');
break;
case 12:
Append (nfi.CurrencySymbol);
Append (' ');
Append (nfi.NegativeSign);
break;
case 14:
Append ('(');
Append (nfi.CurrencySymbol);
Append (' ');
break;
case 15:
Append ('(');
break;
}
}
AppendIntegerStringWithGroupSeparator (nfi.CurrencyGroupSizes, nfi.CurrencyGroupSeparator);
if (precision > 0) {
Append (nfi.CurrencyDecimalSeparator);
AppendDecimalString (precision);
}
if (_positive) {
switch (nfi.CurrencyPositivePattern) {
case 1:
Append (nfi.CurrencySymbol);
break;
case 3:
Append (' ');
Append (nfi.CurrencySymbol);
break;
}
}
else {
switch (nfi.CurrencyNegativePattern) {
case 0:
Append (')');
break;
case 3:
Append (nfi.NegativeSign);
break;
case 4:
Append (nfi.CurrencySymbol);
Append (')');
break;
case 5:
Append (nfi.CurrencySymbol);
break;
case 6:
Append (nfi.NegativeSign);
Append (nfi.CurrencySymbol);
break;
case 7:
Append (nfi.CurrencySymbol);
Append (nfi.NegativeSign);
break;
case 8:
Append (' ');
Append (nfi.CurrencySymbol);
break;
case 10:
Append (' ');
Append (nfi.CurrencySymbol);
Append (nfi.NegativeSign);
break;
case 11:
Append (nfi.NegativeSign);
break;
case 13:
Append (nfi.NegativeSign);
Append (' ');
Append (nfi.CurrencySymbol);
break;
case 14:
Append (')');
break;
case 15:
Append (' ');
Append (nfi.CurrencySymbol);
Append (')');
break;
}
}
return new string (_cbuf, 0, _ind);
}
private string FormatDecimal (int precision, NumberFormatInfo nfi)
{
if (precision < _digitsLen)
precision = _digitsLen;
if (precision == 0)
return "0";
ResetCharBuf (precision + 1);
if (!_positive)
Append (nfi.NegativeSign);
AppendDigits (0, precision);
return new string (_cbuf, 0, _ind);
}
unsafe private string FormatHexadecimal (int precision)
{
int size = Math.Max (precision, _decPointPos);
char* digits = _specifierIsUpper ? DigitUpperTable : DigitLowerTable;
ResetCharBuf (size);
_ind = size;
ulong val = _val1 | ((ulong)_val2 << 32);
while (size > 0) {
_cbuf [--size] = digits [val & 0xf];
val >>= 4;
}
return new string (_cbuf, 0, _ind);
}
string FormatFixedPoint (int precision, NumberFormatInfo nfi)
{
if (precision == -1)
precision = nfi.NumberDecimalDigits;
RoundDecimal (precision);
ResetCharBuf (IntegerDigits + precision + 2);
if (!_positive)
Append (nfi.NegativeSign);
AppendIntegerString (IntegerDigits);
if (precision > 0) {
Append (nfi.NumberDecimalSeparator);
AppendDecimalString (precision);
}
return new string (_cbuf, 0, _ind);
}
private string FormatRoundtrip (double origval, NumberFormatInfo nfi)
{
NumberFormatter nfc = GetClone ();
if (origval >= MinRoundtripVal && origval <= MaxRoundtripVal) {
string shortRep = FormatGeneral (_defPrecision, nfi);
if (origval == Double.Parse (shortRep, nfi))
return shortRep;
}
return nfc.FormatGeneral (_defPrecision + 2, nfi);
}
private string FormatRoundtrip (float origval, NumberFormatInfo nfi)
{
NumberFormatter nfc = GetClone ();
string shortRep = FormatGeneral (_defPrecision, nfi);
// Check roundtrip only for "normal" double values.
if (origval == Single.Parse (shortRep, nfi))
return shortRep;
return nfc.FormatGeneral (_defPrecision + 2, nfi);
}
private string FormatGeneral (int precision, NumberFormatInfo nfi)
{
bool enableExp;
if (precision == -1) {
enableExp = IsFloatingSource;
precision = _defPrecision;
}
else {
enableExp = true;
if (precision == 0)
precision = _defPrecision;
RoundPos (precision);
}
int intDigits = _decPointPos;
int digits = _digitsLen;
int decDigits = digits - intDigits;
if ((intDigits > precision || intDigits <= -4) && enableExp)
return FormatExponential (digits - 1, nfi, 2);
if (decDigits < 0)
decDigits = 0;
if (intDigits < 0)
intDigits = 0;
ResetCharBuf (decDigits + intDigits + 3);
if (!_positive)
Append (nfi.NegativeSign);
if (intDigits == 0)
Append ('0');
else
AppendDigits (digits - intDigits, digits);
if (decDigits > 0) {
Append (nfi.NumberDecimalSeparator);
AppendDigits (0, decDigits);
}
return new string (_cbuf, 0, _ind);
}
string FormatNumber (int precision, NumberFormatInfo nfi)
{
precision = (precision >= 0 ? precision : nfi.NumberDecimalDigits);
ResetCharBuf (IntegerDigits * 3 + precision);
RoundDecimal (precision);
if (!_positive) {
switch (nfi.NumberNegativePattern) {
case 0:
Append ('(');
break;
case 1:
Append (nfi.NegativeSign);
break;
case 2:
Append (nfi.NegativeSign);
Append (' ');
break;
}
}
AppendIntegerStringWithGroupSeparator (nfi.NumberGroupSizes, nfi.NumberGroupSeparator);
if (precision > 0) {
Append (nfi.NumberDecimalSeparator);
AppendDecimalString (precision);
}
if (!_positive) {
switch (nfi.NumberNegativePattern) {
case 0:
Append (')');
break;
case 3:
Append (nfi.NegativeSign);
break;
case 4:
Append (' ');
Append (nfi.NegativeSign);
break;
}
}
return new string (_cbuf, 0, _ind);
}
string FormatPercent (int precision, NumberFormatInfo nfi)
{
precision = (precision >= 0 ? precision : nfi.PercentDecimalDigits);
Multiply10(2);
RoundDecimal (precision);
ResetCharBuf (IntegerDigits * 2 + precision + 16);
if (_positive) {
if (nfi.PercentPositivePattern == 2)
Append (nfi.PercentSymbol);
}
else {
switch (nfi.PercentNegativePattern) {
case 0:
Append (nfi.NegativeSign);
break;
case 1:
Append (nfi.NegativeSign);
break;
case 2:
Append (nfi.NegativeSign);
Append (nfi.PercentSymbol);
break;
}
}
AppendIntegerStringWithGroupSeparator (nfi.PercentGroupSizes, nfi.PercentGroupSeparator);
if (precision > 0) {
Append (nfi.PercentDecimalSeparator);
AppendDecimalString (precision);
}
if (_positive) {
switch (nfi.PercentPositivePattern) {
case 0:
Append (' ');
Append (nfi.PercentSymbol);
break;
case 1:
Append (nfi.PercentSymbol);
break;
}
}
else {
switch (nfi.PercentNegativePattern) {
case 0:
Append (' ');
Append (nfi.PercentSymbol);
break;
case 1:
Append (nfi.PercentSymbol);
break;
}
}
return new string (_cbuf, 0, _ind);
}
string FormatExponential (int precision, NumberFormatInfo nfi)
{
if (precision == -1)
precision = DefaultExpPrecision;
RoundPos (precision + 1);
return FormatExponential (precision, nfi, 3);
}
private string FormatExponential (int precision, NumberFormatInfo nfi, int expDigits)
{
int decDigits = _decPointPos;
int digits = _digitsLen;
int exponent = decDigits - 1;
decDigits = _decPointPos = 1;
ResetCharBuf (precision + 8);
if (!_positive)
Append (nfi.NegativeSign);
AppendOneDigit (digits - 1);
if (precision > 0) {
Append (nfi.NumberDecimalSeparator);
AppendDigits (digits - precision - 1, digits - _decPointPos);
}
AppendExponent (nfi, exponent, expDigits);
return new string (_cbuf, 0, _ind);
}
string FormatCustom (string format, NumberFormatInfo nfi)
{
bool p = _positive;
int offset = 0;
int length = 0;
CustomInfo.GetActiveSection (format, ref p, IsZero, ref offset, ref length);
if (length == 0)
return _positive ? string.Empty : nfi.NegativeSign;
_positive = p;
CustomInfo info = CustomInfo.Parse (format, offset, length, nfi);
#if false
Console.WriteLine ("Format : {0}",format);
Console.WriteLine ("DecimalDigits : {0}",info.DecimalDigits);
Console.WriteLine ("DecimalPointPos : {0}",info.DecimalPointPos);
Console.WriteLine ("DecimalTailSharpDigits : {0}",info.DecimalTailSharpDigits);
Console.WriteLine ("IntegerDigits : {0}",info.IntegerDigits);
Console.WriteLine ("IntegerHeadSharpDigits : {0}",info.IntegerHeadSharpDigits);
Console.WriteLine ("IntegerHeadPos : {0}",info.IntegerHeadPos);
Console.WriteLine ("UseExponent : {0}",info.UseExponent);
Console.WriteLine ("ExponentDigits : {0}",info.ExponentDigits);
Console.WriteLine ("ExponentTailSharpDigits : {0}",info.ExponentTailSharpDigits);
Console.WriteLine ("ExponentNegativeSignOnly : {0}",info.ExponentNegativeSignOnly);
Console.WriteLine ("DividePlaces : {0}",info.DividePlaces);
Console.WriteLine ("Percents : {0}",info.Percents);
Console.WriteLine ("Permilles : {0}",info.Permilles);
#endif
StringBuilder sb_int = new StringBuilder (info.IntegerDigits * 2);
StringBuilder sb_dec = new StringBuilder (info.DecimalDigits * 2);
StringBuilder sb_exp = (info.UseExponent ? new StringBuilder (info.ExponentDigits * 2) : null);
int diff = 0;
if (info.Percents > 0)
Multiply10(2 * info.Percents);
if (info.Permilles > 0)
Multiply10(3 * info.Permilles);
if (info.DividePlaces > 0)
Divide10(info.DividePlaces);
bool expPositive = true;
if (info.UseExponent && (info.DecimalDigits > 0 || info.IntegerDigits > 0)) {
if (!IsZero) {
RoundPos (info.DecimalDigits + info.IntegerDigits);
diff -= _decPointPos - info.IntegerDigits;
_decPointPos = info.IntegerDigits;
}
expPositive = diff <= 0;
AppendNonNegativeNumber (sb_exp, diff < 0 ? -diff : diff);
}
else
RoundDecimal (info.DecimalDigits);
if (info.IntegerDigits != 0 || !IsZeroInteger)
AppendIntegerString (IntegerDigits, sb_int);
AppendDecimalString (DecimalDigits, sb_dec);
if (info.UseExponent) {
if (info.DecimalDigits <= 0 && info.IntegerDigits <= 0)
_positive = true;
if (sb_int.Length < info.IntegerDigits)
sb_int.Insert (0, "0", info.IntegerDigits - sb_int.Length);
while (sb_exp.Length < info.ExponentDigits - info.ExponentTailSharpDigits)
sb_exp.Insert (0, '0');
if (expPositive && !info.ExponentNegativeSignOnly)
sb_exp.Insert (0, nfi.PositiveSign);
else if (!expPositive)
sb_exp.Insert (0, nfi.NegativeSign);
}
else {
if (sb_int.Length < info.IntegerDigits - info.IntegerHeadSharpDigits)
sb_int.Insert (0, "0", info.IntegerDigits - info.IntegerHeadSharpDigits - sb_int.Length);
if (info.IntegerDigits == info.IntegerHeadSharpDigits && IsZeroOnly (sb_int))
sb_int.Remove (0, sb_int.Length);
}
ZeroTrimEnd (sb_dec, true);
while (sb_dec.Length < info.DecimalDigits - info.DecimalTailSharpDigits)
sb_dec.Append ('0');
if (sb_dec.Length > info.DecimalDigits)
sb_dec.Remove (info.DecimalDigits, sb_dec.Length - info.DecimalDigits);
return info.Format (format, offset, length, nfi, _positive, sb_int, sb_dec, sb_exp);
}
#endregion public number formatting methods
#region StringBuilder formatting helpers
private static void ZeroTrimEnd (StringBuilder sb, bool canEmpty)
{
int len = 0;
for (int i = sb.Length - 1; (canEmpty ? i >= 0 : i > 0); i--) {
if (sb [i] != '0')
break;
len++;
}
if (len > 0)
sb.Remove (sb.Length - len, len);
}
private static bool IsZeroOnly (StringBuilder sb)
{
for (int i = 0; i < sb.Length; i++)
if (char.IsDigit (sb [i]) && sb [i] != '0')
return false;
return true;
}
private static void AppendNonNegativeNumber (StringBuilder sb, int v)
{
if (v < 0)
throw new ArgumentException ();
int i = ScaleOrder (v) - 1;
do {
int n = v / (int)GetTenPowerOf (i);
sb.Append ((char)('0' | n));
v -= (int)GetTenPowerOf (i--) * n;
} while (i >= 0);
}
#endregion StringBuilder formatting helpers
#region Append helpers
private void AppendIntegerString (int minLength, StringBuilder sb)
{
if (_decPointPos <= 0) {
sb.Append ('0', minLength);
return;
}
if (_decPointPos < minLength)
sb.Append ('0', minLength - _decPointPos);
AppendDigits (_digitsLen - _decPointPos, _digitsLen, sb);
}
private void AppendIntegerString (int minLength)
{
if (_decPointPos <= 0) {
Append ('0', minLength);
return;
}
if (_decPointPos < minLength)
Append ('0', minLength - _decPointPos);
AppendDigits (_digitsLen - _decPointPos, _digitsLen);
}
private void AppendDecimalString (int precision, StringBuilder sb)
{
AppendDigits (_digitsLen - precision - _decPointPos, _digitsLen - _decPointPos, sb);
}
private void AppendDecimalString (int precision)
{
AppendDigits (_digitsLen - precision - _decPointPos, _digitsLen - _decPointPos);
}
private void AppendIntegerStringWithGroupSeparator (int[] groups, string groupSeparator)
{
if (IsZeroInteger) {
Append ('0');
return;
}
int total = 0;
int groupIndex = 0;
for (int i = 0; i < groups.Length; i++) {
total += groups [i];
if (total <= _decPointPos)
groupIndex = i;
else
break;
}
if (groups.Length > 0 && total > 0) {
int counter;
int groupSize = groups [groupIndex];
int fraction = _decPointPos > total ? _decPointPos - total : 0;
if (groupSize == 0) {
while (groupIndex >= 0 && groups [groupIndex] == 0)
groupIndex--;
groupSize = fraction > 0 ? fraction : groups [groupIndex];
}
if (fraction == 0)
counter = groupSize;
else {
groupIndex += fraction / groupSize;
counter = fraction % groupSize;
if (counter == 0)
counter = groupSize;
else
groupIndex++;
}
if (total >= _decPointPos) {
int lastGroupSize = groups [0];
if (total > lastGroupSize) {
int lastGroupDiff = -(lastGroupSize - _decPointPos);
int lastGroupMod;
if (lastGroupDiff < lastGroupSize)
counter = lastGroupDiff;
else if (lastGroupSize > 0 && (lastGroupMod = _decPointPos % lastGroupSize) > 0)
counter = lastGroupMod;
}
}
for (int i = 0; ;) {
if ((_decPointPos - i) <= counter || counter == 0) {
AppendDigits (_digitsLen - _decPointPos, _digitsLen - i);
break;
}
AppendDigits (_digitsLen - i - counter, _digitsLen - i);
i += counter;
Append (groupSeparator);
if (--groupIndex < groups.Length && groupIndex >= 0)
groupSize = groups [groupIndex];
counter = groupSize;
}
}
else {
AppendDigits (_digitsLen - _decPointPos, _digitsLen);
}
}
// minDigits is in the range 1..3
private void AppendExponent (NumberFormatInfo nfi, int exponent, int minDigits)
{
if (_specifierIsUpper || _specifier == 'R')
Append ('E');
else
Append ('e');
if (exponent >= 0)
Append (nfi.PositiveSign);
else {
Append (nfi.NegativeSign);
exponent = -exponent;
}
if (exponent == 0)
Append ('0', minDigits);
else if (exponent < 10) {
Append ('0', minDigits - 1);
Append ((char)('0' | exponent));
}
else {
uint hexDigit = FastToDecHex (exponent);
if (exponent >= 100 || minDigits == 3)
Append ((char)('0' | (hexDigit >> 8)));
Append ((char)('0' | ((hexDigit >> 4) & 0xf)));
Append ((char)('0' | (hexDigit & 0xf)));
}
}
private void AppendOneDigit (int start)
{
if (_ind == _cbuf.Length)
Resize (_ind + 10);
start += _offset;
uint v;
if (start < 0)
v = 0;
else if (start < 8)
v = _val1;
else if (start < 16)
v = _val2;
else if (start < 24)
v = _val3;
else if (start < 32)
v = _val4;
else
v = 0;
v >>= (start & 0x7) << 2;
_cbuf [_ind++] = (char)('0' | v & 0xf);
}
private void AppendDigits (int start, int end)
{
if (start >= end)
return;
int i = _ind + (end - start);
if (i > _cbuf.Length)
Resize (i + 10);
_ind = i;
end += _offset;
start += _offset;
for (int next = start + 8 - (start & 0x7); ; start = next, next += 8) {
uint v;
if (next == 8)
v = _val1;
else if (next == 16)
v = _val2;
else if (next == 24)
v = _val3;
else if (next == 32)
v = _val4;
else
v = 0;
v >>= (start & 0x7) << 2;
if (next > end)
next = end;
_cbuf [--i] = (char)('0' | v & 0xf);
switch (next - start) {
case 8:
_cbuf [--i] = (char)('0' | (v >>= 4) & 0xf);
goto case 7;
case 7:
_cbuf [--i] = (char)('0' | (v >>= 4) & 0xf);
goto case 6;
case 6:
_cbuf [--i] = (char)('0' | (v >>= 4) & 0xf);
goto case 5;
case 5:
_cbuf [--i] = (char)('0' | (v >>= 4) & 0xf);
goto case 4;
case 4:
_cbuf [--i] = (char)('0' | (v >>= 4) & 0xf);
goto case 3;
case 3:
_cbuf [--i] = (char)('0' | (v >>= 4) & 0xf);
goto case 2;
case 2:
_cbuf [--i] = (char)('0' | (v >>= 4) & 0xf);
goto case 1;
case 1:
if (next == end)
return;
continue;
}
}
}
private void AppendDigits (int start, int end, StringBuilder sb)
{
if (start >= end)
return;
int i = sb.Length + (end - start);
sb.Length = i;
end += _offset;
start += _offset;
for (int next = start + 8 - (start & 0x7); ; start = next, next += 8) {
uint v;
if (next == 8)
v = _val1;
else if (next == 16)
v = _val2;
else if (next == 24)
v = _val3;
else if (next == 32)
v = _val4;
else
v = 0;
v >>= (start & 0x7) << 2;
if (next > end)
next = end;
sb [--i] = (char)('0' | v & 0xf);
switch (next - start) {
case 8:
sb [--i] = (char)('0' | (v >>= 4) & 0xf);
goto case 7;
case 7:
sb [--i] = (char)('0' | (v >>= 4) & 0xf);
goto case 6;
case 6:
sb [--i] = (char)('0' | (v >>= 4) & 0xf);
goto case 5;
case 5:
sb [--i] = (char)('0' | (v >>= 4) & 0xf);
goto case 4;
case 4:
sb [--i] = (char)('0' | (v >>= 4) & 0xf);
goto case 3;
case 3:
sb [--i] = (char)('0' | (v >>= 4) & 0xf);
goto case 2;
case 2:
sb [--i] = (char)('0' | (v >>= 4) & 0xf);
goto case 1;
case 1:
if (next == end)
return;
continue;
}
}
}
#endregion Append helpers
#region others
private void Multiply10(int count)
{
if (count <= 0 || _digitsLen == 0)
return;
_decPointPos += count;
}
private void Divide10(int count)
{
if (count <= 0 || _digitsLen == 0)
return;
_decPointPos -= count;
}
private NumberFormatter GetClone ()
{
return (NumberFormatter)this.MemberwiseClone ();
}
#endregion others
#region custom
private class CustomInfo
{
public bool UseGroup = false;
public int DecimalDigits = 0;
public int DecimalPointPos = -1;
public int DecimalTailSharpDigits = 0;
public int IntegerDigits = 0;
public int IntegerHeadSharpDigits = 0;
public int IntegerHeadPos = 0;
public bool UseExponent = false;
public int ExponentDigits = 0;
public int ExponentTailSharpDigits = 0;
public bool ExponentNegativeSignOnly = true;
public int DividePlaces = 0;
public int Percents = 0;
public int Permilles = 0;
public static void GetActiveSection (string format, ref bool positive, bool zero, ref int offset, ref int length)
{
int[] lens = new int [3];
int index = 0;
int lastPos = 0;
bool quoted = false;
for (int i = 0; i < format.Length; i++) {
char c = format [i];
if (c == '\"' || c == '\'') {
if (i == 0 || format [i - 1] != '\\')
quoted = !quoted;
continue;
}
if (c == ';' && !quoted && (i == 0 || format [i - 1] != '\\')) {
lens [index++] = i - lastPos;
lastPos = i + 1;
if (index == 3)
break;
}
}
if (index == 0) {
offset = 0;
length = format.Length;
return;
}
if (index == 1) {
if (positive || zero) {
offset = 0;
length = lens [0];
return;
}
if (lens [0] + 1 < format.Length) {
positive = true;
offset = lens [0] + 1;
length = format.Length - offset;
return;
}
else {
offset = 0;
length = lens [0];
return;
}
}
if (zero) {
if (index == 2) {
if (format.Length - lastPos == 0) {
offset = 0;
length = lens [0];
} else {
offset = lens [0] + lens [1] + 2;
length = format.Length - offset;
}
return;
}
if (lens [2] == 0) {
offset = 0;
length = lens [0];
} else {
offset = lens [0] + lens [1] + 2;
length = lens [2];
}
return;
}
if (positive) {
offset = 0;
length = lens [0];
return;
}
if (lens [1] > 0) {
positive = true;
offset = lens [0] + 1;
length = lens [1];
return;
}
offset = 0;
length = lens [0];
}
public static CustomInfo Parse (string format, int offset, int length, NumberFormatInfo nfi)
{
char literal = '\0';
bool integerArea = true;
bool decimalArea = false;
bool exponentArea = false;
bool sharpContinues = true;
CustomInfo info = new CustomInfo ();
int groupSeparatorCounter = 0;
for (int i = offset; i - offset < length; i++) {
char c = format [i];
if (c == literal && c != '\0') {
literal = '\0';
continue;
}
if (literal != '\0')
continue;
if (exponentArea && (c != '\0' && c != '0' && c != '#')) {
exponentArea = false;
integerArea = (info.DecimalPointPos < 0);
decimalArea = !integerArea;
i--;
continue;
}
switch (c) {
case '\\':
i++;
continue;
case '\'':
case '\"':
if (c == '\"' || c == '\'') {
literal = c;
}
continue;
case '#':
if (sharpContinues && integerArea)
info.IntegerHeadSharpDigits++;
else if (decimalArea)
info.DecimalTailSharpDigits++;
else if (exponentArea)
info.ExponentTailSharpDigits++;
goto case '0';
case '0':
if (c != '#') {
sharpContinues = false;
if (decimalArea)
info.DecimalTailSharpDigits = 0;
else if (exponentArea)
info.ExponentTailSharpDigits = 0;
}
if (info.IntegerHeadPos == -1)
info.IntegerHeadPos = i;
if (integerArea) {
info.IntegerDigits++;
if (groupSeparatorCounter > 0)
info.UseGroup = true;
groupSeparatorCounter = 0;
}
else if (decimalArea)
info.DecimalDigits++;
else if (exponentArea)
info.ExponentDigits++;
break;
case 'e':
case 'E':
if (info.UseExponent)
break;
info.UseExponent = true;
integerArea = false;
decimalArea = false;
exponentArea = true;
if (i + 1 - offset < length) {
char nc = format [i + 1];
if (nc == '+')
info.ExponentNegativeSignOnly = false;
if (nc == '+' || nc == '-')
i++;
else if (nc != '0' && nc != '#') {
info.UseExponent = false;
if (info.DecimalPointPos < 0)
integerArea = true;
}
}
break;
case '.':
integerArea = false;
decimalArea = true;
exponentArea = false;
if (info.DecimalPointPos == -1)
info.DecimalPointPos = i;
break;
case '%':
info.Percents++;
break;
case '\u2030':
info.Permilles++;
break;
case ',':
if (integerArea && info.IntegerDigits > 0)
groupSeparatorCounter++;
break;
default:
break;
}
}
if (info.ExponentDigits == 0)
info.UseExponent = false;
else
info.IntegerHeadSharpDigits = 0;
if (info.DecimalDigits == 0)
info.DecimalPointPos = -1;
info.DividePlaces += groupSeparatorCounter * 3;
return info;
}
public string Format (string format, int offset, int length, NumberFormatInfo nfi, bool positive, StringBuilder sb_int, StringBuilder sb_dec, StringBuilder sb_exp)
{
StringBuilder sb = new StringBuilder ();
char literal = '\0';
bool integerArea = true;
bool decimalArea = false;
int intSharpCounter = 0;
int sb_int_index = 0;
int sb_dec_index = 0;
int[] groups = nfi.NumberGroupSizes;
string groupSeparator = nfi.NumberGroupSeparator;
int intLen = 0, total = 0, groupIndex = 0, counter = 0, groupSize = 0;
if (UseGroup && groups.Length > 0) {
intLen = sb_int.Length;
for (int i = 0; i < groups.Length; i++) {
total += groups [i];
if (total <= intLen)
groupIndex = i;
}
groupSize = groups [groupIndex];
int fraction = intLen > total ? intLen - total : 0;
if (groupSize == 0) {
while (groupIndex >= 0 && groups [groupIndex] == 0)
groupIndex--;
groupSize = fraction > 0 ? fraction : groups [groupIndex];
}
if (fraction == 0)
counter = groupSize;
else {
groupIndex += fraction / groupSize;
counter = fraction % groupSize;
if (counter == 0)
counter = groupSize;
else
groupIndex++;
}
}
else
UseGroup = false;
for (int i = offset; i - offset < length; i++) {
char c = format [i];
if (c == literal && c != '\0') {
literal = '\0';
continue;
}
if (literal != '\0') {
sb.Append (c);
continue;
}
switch (c) {
case '\\':
i++;
if (i - offset < length)
sb.Append (format [i]);
continue;
case '\'':
case '\"':
if (c == '\"' || c == '\'')
literal = c;
continue;
case '#':
goto case '0';
case '0':
if (integerArea) {
intSharpCounter++;
if (IntegerDigits - intSharpCounter < sb_int.Length + sb_int_index || c == '0')
while (IntegerDigits - intSharpCounter + sb_int_index < sb_int.Length) {
sb.Append (sb_int [sb_int_index++]);
if (UseGroup && --intLen > 0 && --counter == 0) {
sb.Append (groupSeparator);
if (--groupIndex < groups.Length && groupIndex >= 0)
groupSize = groups [groupIndex];
counter = groupSize;
}
}
break;
}
else if (decimalArea) {
if (sb_dec_index < sb_dec.Length)
sb.Append (sb_dec [sb_dec_index++]);
break;
}
sb.Append (c);
break;
case 'e':
case 'E':
if (sb_exp == null || !UseExponent) {
sb.Append (c);
break;
}
bool flag1 = true;
bool flag2 = false;
int q;
for (q = i + 1; q - offset < length; q++) {
if (format [q] == '0') {
flag2 = true;
continue;
}
if (q == i + 1 && (format [q] == '+' || format [q] == '-'))
continue;
if (!flag2)
flag1 = false;
break;
}
if (flag1) {
i = q - 1;
integerArea = (DecimalPointPos < 0);
decimalArea = !integerArea;
sb.Append (c);
sb.Append (sb_exp);
sb_exp = null;
}
else
sb.Append (c);
break;
case '.':
if (DecimalPointPos == i) {
if (DecimalDigits > 0) {
while (sb_int_index < sb_int.Length)
sb.Append (sb_int [sb_int_index++]);
}
if (sb_dec.Length > 0)
sb.Append (nfi.NumberDecimalSeparator);
}
integerArea = false;
decimalArea = true;
break;
case ',':
break;
case '%':
sb.Append (nfi.PercentSymbol);
break;
case '\u2030':
sb.Append (nfi.PerMilleSymbol);
break;
default:
sb.Append (c);
break;
}
}
if (!positive)
sb.Insert (0, nfi.NegativeSign);
return sb.ToString ();
}
}
#endregion
}
}
|