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
|
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 1997-2015, International Business Machines Corporation
* and others. All Rights Reserved.
*******************************************************************************
*/
#include <_foundation_unicode/utypes.h>
#include "utypeinfo.h" // for 'typeid' to work
#include <_foundation_unicode/rbnf.h>
#if U_HAVE_RBNF
#include <_foundation_unicode/normlzr.h>
#include <_foundation_unicode/plurfmt.h>
#include <_foundation_unicode/tblcoll.h>
#include <_foundation_unicode/uchar.h>
#include <_foundation_unicode/ucol.h>
#include <_foundation_unicode/uloc.h>
#include <_foundation_unicode/unum.h>
#include <_foundation_unicode/ures.h>
#include <_foundation_unicode/ustring.h>
#include <_foundation_unicode/utf16.h>
#include <_foundation_unicode/udata.h>
#include <_foundation_unicode/udisplaycontext.h>
#include <_foundation_unicode/brkiter.h>
#include <_foundation_unicode/ucasemap.h>
#include "cmemory.h"
#include "cstring.h"
#include "patternprops.h"
#include "uresimp.h"
#include "nfrs.h"
#include "number_decimalquantity.h"
// debugging
// #define RBNF_DEBUG
#ifdef RBNF_DEBUG
#include <stdio.h>
#endif
#define U_ICUDATA_RBNF U_ICUDATA_NAME U_TREE_SEPARATOR_STRING "rbnf"
static const char16_t gPercentPercent[] =
{
0x25, 0x25, 0
}; /* "%%" */
// All urbnf objects are created through openRules, so we init all of the
// Unicode string constants required by rbnf, nfrs, or nfr here.
static const char16_t gLenientParse[] =
{
0x25, 0x25, 0x6C, 0x65, 0x6E, 0x69, 0x65, 0x6E, 0x74, 0x2D, 0x70, 0x61, 0x72, 0x73, 0x65, 0x3A, 0
}; /* "%%lenient-parse:" */
static const char16_t gSemiColon = 0x003B;
static const char16_t gSemiPercent[] =
{
0x3B, 0x25, 0
}; /* ";%" */
#define kSomeNumberOfBitsDiv2 22
#define kHalfMaxDouble (double)(1 << kSomeNumberOfBitsDiv2)
#define kMaxDouble (kHalfMaxDouble * kHalfMaxDouble)
U_NAMESPACE_BEGIN
using number::impl::DecimalQuantity;
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(RuleBasedNumberFormat)
/*
This is a utility class. It does not use ICU's RTTI.
If ICU's RTTI is needed again, you can uncomment the RTTI code and derive from UObject.
Please make sure that intltest passes on Windows in Release mode,
since the string pooling per compilation unit will mess up how RTTI works.
The RTTI code was also removed due to lack of code coverage.
*/
class LocalizationInfo : public UMemory {
protected:
virtual ~LocalizationInfo();
uint32_t refcount;
public:
LocalizationInfo() : refcount(0) {}
LocalizationInfo* ref() {
++refcount;
return this;
}
LocalizationInfo* unref() {
if (refcount && --refcount == 0) {
delete this;
}
return nullptr;
}
virtual bool operator==(const LocalizationInfo* rhs) const;
inline bool operator!=(const LocalizationInfo* rhs) const { return !operator==(rhs); }
virtual int32_t getNumberOfRuleSets() const = 0;
virtual const char16_t* getRuleSetName(int32_t index) const = 0;
virtual int32_t getNumberOfDisplayLocales() const = 0;
virtual const char16_t* getLocaleName(int32_t index) const = 0;
virtual const char16_t* getDisplayName(int32_t localeIndex, int32_t ruleIndex) const = 0;
virtual int32_t indexForLocale(const char16_t* locale) const;
virtual int32_t indexForRuleSet(const char16_t* ruleset) const;
// virtual UClassID getDynamicClassID() const = 0;
// static UClassID getStaticClassID();
};
LocalizationInfo::~LocalizationInfo() {}
//UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(LocalizationInfo)
// if both strings are nullptr, this returns true
static UBool
streq(const char16_t* lhs, const char16_t* rhs) {
if (rhs == lhs) {
return true;
}
if (lhs && rhs) {
return u_strcmp(lhs, rhs) == 0;
}
return false;
}
bool
LocalizationInfo::operator==(const LocalizationInfo* rhs) const {
if (rhs) {
if (this == rhs) {
return true;
}
int32_t rsc = getNumberOfRuleSets();
if (rsc == rhs->getNumberOfRuleSets()) {
for (int i = 0; i < rsc; ++i) {
if (!streq(getRuleSetName(i), rhs->getRuleSetName(i))) {
return false;
}
}
int32_t dlc = getNumberOfDisplayLocales();
if (dlc == rhs->getNumberOfDisplayLocales()) {
for (int i = 0; i < dlc; ++i) {
const char16_t* locale = getLocaleName(i);
int32_t ix = rhs->indexForLocale(locale);
// if no locale, ix is -1, getLocaleName returns null, so streq returns false
if (!streq(locale, rhs->getLocaleName(ix))) {
return false;
}
for (int j = 0; j < rsc; ++j) {
if (!streq(getDisplayName(i, j), rhs->getDisplayName(ix, j))) {
return false;
}
}
}
return true;
}
}
}
return false;
}
int32_t
LocalizationInfo::indexForLocale(const char16_t* locale) const {
for (int i = 0; i < getNumberOfDisplayLocales(); ++i) {
if (streq(locale, getLocaleName(i))) {
return i;
}
}
return -1;
}
int32_t
LocalizationInfo::indexForRuleSet(const char16_t* ruleset) const {
if (ruleset) {
for (int i = 0; i < getNumberOfRuleSets(); ++i) {
if (streq(ruleset, getRuleSetName(i))) {
return i;
}
}
}
return -1;
}
typedef void (*Fn_Deleter)(void*);
class VArray {
void** buf;
int32_t cap;
int32_t size;
Fn_Deleter deleter;
public:
VArray() : buf(nullptr), cap(0), size(0), deleter(nullptr) {}
VArray(Fn_Deleter del) : buf(nullptr), cap(0), size(0), deleter(del) {}
~VArray() {
if (deleter) {
for (int i = 0; i < size; ++i) {
(*deleter)(buf[i]);
}
}
uprv_free(buf);
}
int32_t length() {
return size;
}
void add(void* elem, UErrorCode& status) {
if (U_SUCCESS(status)) {
if (size == cap) {
if (cap == 0) {
cap = 1;
} else if (cap < 256) {
cap *= 2;
} else {
cap += 256;
}
if (buf == nullptr) {
buf = (void**)uprv_malloc(cap * sizeof(void*));
} else {
buf = (void**)uprv_realloc(buf, cap * sizeof(void*));
}
if (buf == nullptr) {
// if we couldn't realloc, we leak the memory we've already allocated, but we're in deep trouble anyway
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
void* start = &buf[size];
size_t count = (cap - size) * sizeof(void*);
uprv_memset(start, 0, count); // fill with nulls, just because
}
buf[size++] = elem;
}
}
void** release() {
void** result = buf;
buf = nullptr;
cap = 0;
size = 0;
return result;
}
};
class LocDataParser;
class StringLocalizationInfo : public LocalizationInfo {
char16_t* info;
char16_t*** data;
int32_t numRuleSets;
int32_t numLocales;
friend class LocDataParser;
StringLocalizationInfo(char16_t* i, char16_t*** d, int32_t numRS, int32_t numLocs)
: info(i), data(d), numRuleSets(numRS), numLocales(numLocs)
{
}
public:
static StringLocalizationInfo* create(const UnicodeString& info, UParseError& perror, UErrorCode& status);
virtual ~StringLocalizationInfo();
virtual int32_t getNumberOfRuleSets() const override { return numRuleSets; }
virtual const char16_t* getRuleSetName(int32_t index) const override;
virtual int32_t getNumberOfDisplayLocales() const override { return numLocales; }
virtual const char16_t* getLocaleName(int32_t index) const override;
virtual const char16_t* getDisplayName(int32_t localeIndex, int32_t ruleIndex) const override;
// virtual UClassID getDynamicClassID() const;
// static UClassID getStaticClassID();
private:
void init(UErrorCode& status) const;
};
enum {
OPEN_ANGLE = 0x003c, /* '<' */
CLOSE_ANGLE = 0x003e, /* '>' */
COMMA = 0x002c,
TICK = 0x0027,
QUOTE = 0x0022,
SPACE = 0x0020
};
/**
* Utility for parsing a localization string and returning a StringLocalizationInfo*.
*/
class LocDataParser {
char16_t* data;
const char16_t* e;
char16_t* p;
char16_t ch;
UParseError& pe;
UErrorCode& ec;
public:
LocDataParser(UParseError& parseError, UErrorCode& status)
: data(nullptr), e(nullptr), p(nullptr), ch(0xffff), pe(parseError), ec(status) {}
~LocDataParser() {}
/*
* On a successful parse, return a StringLocalizationInfo*, otherwise delete locData, set perror and status,
* and return nullptr. The StringLocalizationInfo will adopt locData if it is created.
*/
StringLocalizationInfo* parse(char16_t* data, int32_t len);
private:
inline void inc() {
++p;
ch = 0xffff;
}
inline UBool checkInc(char16_t c) {
if (p < e && (ch == c || *p == c)) {
inc();
return true;
}
return false;
}
inline UBool check(char16_t c) {
return p < e && (ch == c || *p == c);
}
inline void skipWhitespace() {
while (p < e && PatternProps::isWhiteSpace(ch != 0xffff ? ch : *p)) {
inc();
}
}
inline UBool inList(char16_t c, const char16_t* list) const {
if (*list == SPACE && PatternProps::isWhiteSpace(c)) {
return true;
}
while (*list && *list != c) {
++list;
}
return *list == c;
}
void parseError(const char* msg);
StringLocalizationInfo* doParse();
char16_t** nextArray(int32_t& requiredLength);
char16_t* nextString();
};
#ifdef RBNF_DEBUG
#define ERROR(msg) UPRV_BLOCK_MACRO_BEGIN { \
parseError(msg); \
return nullptr; \
} UPRV_BLOCK_MACRO_END
#define EXPLANATION_ARG explanationArg
#else
#define ERROR(msg) UPRV_BLOCK_MACRO_BEGIN { \
parseError(nullptr); \
return nullptr; \
} UPRV_BLOCK_MACRO_END
#define EXPLANATION_ARG
#endif
static const char16_t DQUOTE_STOPLIST[] = {
QUOTE, 0
};
static const char16_t SQUOTE_STOPLIST[] = {
TICK, 0
};
static const char16_t NOQUOTE_STOPLIST[] = {
SPACE, COMMA, CLOSE_ANGLE, OPEN_ANGLE, TICK, QUOTE, 0
};
static void
DeleteFn(void* p) {
uprv_free(p);
}
StringLocalizationInfo*
LocDataParser::parse(char16_t* _data, int32_t len) {
if (U_FAILURE(ec)) {
if (_data) uprv_free(_data);
return nullptr;
}
pe.line = 0;
pe.offset = -1;
pe.postContext[0] = 0;
pe.preContext[0] = 0;
if (_data == nullptr) {
ec = U_ILLEGAL_ARGUMENT_ERROR;
return nullptr;
}
if (len <= 0) {
ec = U_ILLEGAL_ARGUMENT_ERROR;
uprv_free(_data);
return nullptr;
}
data = _data;
e = data + len;
p = _data;
ch = 0xffff;
return doParse();
}
StringLocalizationInfo*
LocDataParser::doParse() {
skipWhitespace();
if (!checkInc(OPEN_ANGLE)) {
ERROR("Missing open angle");
} else {
VArray array(DeleteFn);
UBool mightHaveNext = true;
int32_t requiredLength = -1;
while (mightHaveNext) {
mightHaveNext = false;
char16_t** elem = nextArray(requiredLength);
skipWhitespace();
UBool haveComma = check(COMMA);
if (elem) {
array.add(elem, ec);
if (haveComma) {
inc();
mightHaveNext = true;
}
} else if (haveComma) {
ERROR("Unexpected character");
}
}
skipWhitespace();
if (!checkInc(CLOSE_ANGLE)) {
if (check(OPEN_ANGLE)) {
ERROR("Missing comma in outer array");
} else {
ERROR("Missing close angle bracket in outer array");
}
}
skipWhitespace();
if (p != e) {
ERROR("Extra text after close of localization data");
}
array.add(nullptr, ec);
if (U_SUCCESS(ec)) {
int32_t numLocs = array.length() - 2; // subtract first, nullptr
char16_t*** result = (char16_t***)array.release();
return new StringLocalizationInfo(data, result, requiredLength-2, numLocs); // subtract first, nullptr
}
}
ERROR("Unknown error");
}
char16_t**
LocDataParser::nextArray(int32_t& requiredLength) {
if (U_FAILURE(ec)) {
return nullptr;
}
skipWhitespace();
if (!checkInc(OPEN_ANGLE)) {
ERROR("Missing open angle");
}
VArray array;
UBool mightHaveNext = true;
while (mightHaveNext) {
mightHaveNext = false;
char16_t* elem = nextString();
skipWhitespace();
UBool haveComma = check(COMMA);
if (elem) {
array.add(elem, ec);
if (haveComma) {
inc();
mightHaveNext = true;
}
} else if (haveComma) {
ERROR("Unexpected comma");
}
}
skipWhitespace();
if (!checkInc(CLOSE_ANGLE)) {
if (check(OPEN_ANGLE)) {
ERROR("Missing close angle bracket in inner array");
} else {
ERROR("Missing comma in inner array");
}
}
array.add(nullptr, ec);
if (U_SUCCESS(ec)) {
if (requiredLength == -1) {
requiredLength = array.length() + 1;
} else if (array.length() != requiredLength) {
ec = U_ILLEGAL_ARGUMENT_ERROR;
ERROR("Array not of required length");
}
return (char16_t**)array.release();
}
ERROR("Unknown Error");
}
char16_t*
LocDataParser::nextString() {
char16_t* result = nullptr;
skipWhitespace();
if (p < e) {
const char16_t* terminators;
char16_t c = *p;
UBool haveQuote = c == QUOTE || c == TICK;
if (haveQuote) {
inc();
terminators = c == QUOTE ? DQUOTE_STOPLIST : SQUOTE_STOPLIST;
} else {
terminators = NOQUOTE_STOPLIST;
}
char16_t* start = p;
while (p < e && !inList(*p, terminators)) ++p;
if (p == e) {
ERROR("Unexpected end of data");
}
char16_t x = *p;
if (p > start) {
ch = x;
*p = 0x0; // terminate by writing to data
result = start; // just point into data
}
if (haveQuote) {
if (x != c) {
ERROR("Missing matching quote");
} else if (p == start) {
ERROR("Empty string");
}
inc();
} else if (x == OPEN_ANGLE || x == TICK || x == QUOTE) {
ERROR("Unexpected character in string");
}
}
// ok for there to be no next string
return result;
}
void LocDataParser::parseError(const char* EXPLANATION_ARG)
{
if (!data) {
return;
}
const char16_t* start = p - U_PARSE_CONTEXT_LEN - 1;
if (start < data) {
start = data;
}
for (char16_t* x = p; --x >= start;) {
if (!*x) {
start = x+1;
break;
}
}
const char16_t* limit = p + U_PARSE_CONTEXT_LEN - 1;
if (limit > e) {
limit = e;
}
u_strncpy(pe.preContext, start, (int32_t)(p-start));
pe.preContext[p-start] = 0;
u_strncpy(pe.postContext, p, (int32_t)(limit-p));
pe.postContext[limit-p] = 0;
pe.offset = (int32_t)(p - data);
#ifdef RBNF_DEBUG
fprintf(stderr, "%s at or near character %ld: ", EXPLANATION_ARG, p-data);
UnicodeString msg;
msg.append(start, p - start);
msg.append((char16_t)0x002f); /* SOLIDUS/SLASH */
msg.append(p, limit-p);
msg.append(UNICODE_STRING_SIMPLE("'"));
char buf[128];
int32_t len = msg.extract(0, msg.length(), buf, 128);
if (len >= 128) {
buf[127] = 0;
} else {
buf[len] = 0;
}
fprintf(stderr, "%s\n", buf);
fflush(stderr);
#endif
uprv_free(data);
data = nullptr;
p = nullptr;
e = nullptr;
if (U_SUCCESS(ec)) {
ec = U_PARSE_ERROR;
}
}
//UOBJECT_DEFINE_RTTI_IMPLEMENTATION(StringLocalizationInfo)
StringLocalizationInfo*
StringLocalizationInfo::create(const UnicodeString& info, UParseError& perror, UErrorCode& status) {
if (U_FAILURE(status)) {
return nullptr;
}
int32_t len = info.length();
if (len == 0) {
return nullptr; // no error;
}
char16_t* p = (char16_t*)uprv_malloc(len * sizeof(char16_t));
if (!p) {
status = U_MEMORY_ALLOCATION_ERROR;
return nullptr;
}
info.extract(p, len, status);
if (!U_FAILURE(status)) {
status = U_ZERO_ERROR; // clear warning about non-termination
}
LocDataParser parser(perror, status);
return parser.parse(p, len);
}
StringLocalizationInfo::~StringLocalizationInfo() {
for (char16_t*** p = (char16_t***)data; *p; ++p) {
// remaining data is simply pointer into our unicode string data.
if (*p) uprv_free(*p);
}
if (data) uprv_free(data);
if (info) uprv_free(info);
}
const char16_t*
StringLocalizationInfo::getRuleSetName(int32_t index) const {
if (index >= 0 && index < getNumberOfRuleSets()) {
return data[0][index];
}
return nullptr;
}
const char16_t*
StringLocalizationInfo::getLocaleName(int32_t index) const {
if (index >= 0 && index < getNumberOfDisplayLocales()) {
return data[index+1][0];
}
return nullptr;
}
const char16_t*
StringLocalizationInfo::getDisplayName(int32_t localeIndex, int32_t ruleIndex) const {
if (localeIndex >= 0 && localeIndex < getNumberOfDisplayLocales() &&
ruleIndex >= 0 && ruleIndex < getNumberOfRuleSets()) {
return data[localeIndex+1][ruleIndex+1];
}
return nullptr;
}
// ----------
RuleBasedNumberFormat::RuleBasedNumberFormat(const UnicodeString& description,
const UnicodeString& locs,
const Locale& alocale, UParseError& perror, UErrorCode& status)
: fRuleSets(nullptr)
, ruleSetDescriptions(nullptr)
, numRuleSets(0)
, defaultRuleSet(nullptr)
, locale(alocale)
, collator(nullptr)
, decimalFormatSymbols(nullptr)
, defaultInfinityRule(nullptr)
, defaultNaNRule(nullptr)
, fRoundingMode(DecimalFormat::ERoundingMode::kRoundUnnecessary)
, lenient(false)
, lenientParseRules(nullptr)
, localizations(nullptr)
, capitalizationInfoSet(false)
, capitalizationForUIListMenu(false)
, capitalizationForStandAlone(false)
, capitalizationBrkIter(nullptr)
{
LocalizationInfo* locinfo = StringLocalizationInfo::create(locs, perror, status);
init(description, locinfo, perror, status);
}
RuleBasedNumberFormat::RuleBasedNumberFormat(const UnicodeString& description,
const UnicodeString& locs,
UParseError& perror, UErrorCode& status)
: fRuleSets(nullptr)
, ruleSetDescriptions(nullptr)
, numRuleSets(0)
, defaultRuleSet(nullptr)
, locale(Locale::getDefault())
, collator(nullptr)
, decimalFormatSymbols(nullptr)
, defaultInfinityRule(nullptr)
, defaultNaNRule(nullptr)
, fRoundingMode(DecimalFormat::ERoundingMode::kRoundUnnecessary)
, lenient(false)
, lenientParseRules(nullptr)
, localizations(nullptr)
, capitalizationInfoSet(false)
, capitalizationForUIListMenu(false)
, capitalizationForStandAlone(false)
, capitalizationBrkIter(nullptr)
{
LocalizationInfo* locinfo = StringLocalizationInfo::create(locs, perror, status);
init(description, locinfo, perror, status);
}
RuleBasedNumberFormat::RuleBasedNumberFormat(const UnicodeString& description,
LocalizationInfo* info,
const Locale& alocale, UParseError& perror, UErrorCode& status)
: fRuleSets(nullptr)
, ruleSetDescriptions(nullptr)
, numRuleSets(0)
, defaultRuleSet(nullptr)
, locale(alocale)
, collator(nullptr)
, decimalFormatSymbols(nullptr)
, defaultInfinityRule(nullptr)
, defaultNaNRule(nullptr)
, fRoundingMode(DecimalFormat::ERoundingMode::kRoundUnnecessary)
, lenient(false)
, lenientParseRules(nullptr)
, localizations(nullptr)
, capitalizationInfoSet(false)
, capitalizationForUIListMenu(false)
, capitalizationForStandAlone(false)
, capitalizationBrkIter(nullptr)
{
init(description, info, perror, status);
}
RuleBasedNumberFormat::RuleBasedNumberFormat(const UnicodeString& description,
UParseError& perror,
UErrorCode& status)
: fRuleSets(nullptr)
, ruleSetDescriptions(nullptr)
, numRuleSets(0)
, defaultRuleSet(nullptr)
, locale(Locale::getDefault())
, collator(nullptr)
, decimalFormatSymbols(nullptr)
, defaultInfinityRule(nullptr)
, defaultNaNRule(nullptr)
, fRoundingMode(DecimalFormat::ERoundingMode::kRoundUnnecessary)
, lenient(false)
, lenientParseRules(nullptr)
, localizations(nullptr)
, capitalizationInfoSet(false)
, capitalizationForUIListMenu(false)
, capitalizationForStandAlone(false)
, capitalizationBrkIter(nullptr)
{
init(description, nullptr, perror, status);
}
RuleBasedNumberFormat::RuleBasedNumberFormat(const UnicodeString& description,
const Locale& aLocale,
UParseError& perror,
UErrorCode& status)
: fRuleSets(nullptr)
, ruleSetDescriptions(nullptr)
, numRuleSets(0)
, defaultRuleSet(nullptr)
, locale(aLocale)
, collator(nullptr)
, decimalFormatSymbols(nullptr)
, defaultInfinityRule(nullptr)
, defaultNaNRule(nullptr)
, fRoundingMode(DecimalFormat::ERoundingMode::kRoundUnnecessary)
, lenient(false)
, lenientParseRules(nullptr)
, localizations(nullptr)
, capitalizationInfoSet(false)
, capitalizationForUIListMenu(false)
, capitalizationForStandAlone(false)
, capitalizationBrkIter(nullptr)
{
init(description, nullptr, perror, status);
}
RuleBasedNumberFormat::RuleBasedNumberFormat(URBNFRuleSetTag tag, const Locale& alocale, UErrorCode& status)
: fRuleSets(nullptr)
, ruleSetDescriptions(nullptr)
, numRuleSets(0)
, defaultRuleSet(nullptr)
, locale(alocale)
, collator(nullptr)
, decimalFormatSymbols(nullptr)
, defaultInfinityRule(nullptr)
, defaultNaNRule(nullptr)
, fRoundingMode(DecimalFormat::ERoundingMode::kRoundUnnecessary)
, lenient(false)
, lenientParseRules(nullptr)
, localizations(nullptr)
, capitalizationInfoSet(false)
, capitalizationForUIListMenu(false)
, capitalizationForStandAlone(false)
, capitalizationBrkIter(nullptr)
{
if (U_FAILURE(status)) {
return;
}
const char* rules_tag = "RBNFRules";
const char* fmt_tag = "";
switch (tag) {
case URBNF_SPELLOUT: fmt_tag = "SpelloutRules"; break;
case URBNF_ORDINAL: fmt_tag = "OrdinalRules"; break;
case URBNF_DURATION: fmt_tag = "DurationRules"; break;
case URBNF_NUMBERING_SYSTEM: fmt_tag = "NumberingSystemRules"; break;
default: status = U_ILLEGAL_ARGUMENT_ERROR; return;
}
// TODO: read localization info from resource
LocalizationInfo* locinfo = nullptr;
UResourceBundle* nfrb = ures_open(U_ICUDATA_RBNF, locale.getName(), &status);
if (U_SUCCESS(status)) {
setLocaleIDs(ures_getLocaleByType(nfrb, ULOC_VALID_LOCALE, &status),
ures_getLocaleByType(nfrb, ULOC_ACTUAL_LOCALE, &status));
UResourceBundle* rbnfRules = ures_getByKeyWithFallback(nfrb, rules_tag, nullptr, &status);
if (U_FAILURE(status)) {
ures_close(nfrb);
}
UResourceBundle* ruleSets = ures_getByKeyWithFallback(rbnfRules, fmt_tag, nullptr, &status);
if (U_FAILURE(status)) {
ures_close(rbnfRules);
ures_close(nfrb);
return;
}
UnicodeString desc;
while (ures_hasNext(ruleSets)) {
desc.append(ures_getNextUnicodeString(ruleSets,nullptr,&status));
}
UParseError perror;
init(desc, locinfo, perror, status);
ures_close(ruleSets);
ures_close(rbnfRules);
}
ures_close(nfrb);
}
RuleBasedNumberFormat::RuleBasedNumberFormat(const RuleBasedNumberFormat& rhs)
: NumberFormat(rhs)
, fRuleSets(nullptr)
, ruleSetDescriptions(nullptr)
, numRuleSets(0)
, defaultRuleSet(nullptr)
, locale(rhs.locale)
, collator(nullptr)
, decimalFormatSymbols(nullptr)
, defaultInfinityRule(nullptr)
, defaultNaNRule(nullptr)
, fRoundingMode(DecimalFormat::ERoundingMode::kRoundUnnecessary)
, lenient(false)
, lenientParseRules(nullptr)
, localizations(nullptr)
, capitalizationInfoSet(false)
, capitalizationForUIListMenu(false)
, capitalizationForStandAlone(false)
, capitalizationBrkIter(nullptr)
{
this->operator=(rhs);
}
// --------
RuleBasedNumberFormat&
RuleBasedNumberFormat::operator=(const RuleBasedNumberFormat& rhs)
{
if (this == &rhs) {
return *this;
}
NumberFormat::operator=(rhs);
UErrorCode status = U_ZERO_ERROR;
dispose();
locale = rhs.locale;
lenient = rhs.lenient;
UParseError perror;
setDecimalFormatSymbols(*rhs.getDecimalFormatSymbols());
init(rhs.originalDescription, rhs.localizations ? rhs.localizations->ref() : nullptr, perror, status);
setDefaultRuleSet(rhs.getDefaultRuleSetName(), status);
setRoundingMode(rhs.getRoundingMode());
capitalizationInfoSet = rhs.capitalizationInfoSet;
capitalizationForUIListMenu = rhs.capitalizationForUIListMenu;
capitalizationForStandAlone = rhs.capitalizationForStandAlone;
#if !UCONFIG_NO_BREAK_ITERATION
capitalizationBrkIter = (rhs.capitalizationBrkIter!=nullptr)? rhs.capitalizationBrkIter->clone(): nullptr;
#endif
return *this;
}
RuleBasedNumberFormat::~RuleBasedNumberFormat()
{
dispose();
}
RuleBasedNumberFormat*
RuleBasedNumberFormat::clone() const
{
return new RuleBasedNumberFormat(*this);
}
bool
RuleBasedNumberFormat::operator==(const Format& other) const
{
if (this == &other) {
return true;
}
if (typeid(*this) == typeid(other)) {
const RuleBasedNumberFormat& rhs = static_cast<const RuleBasedNumberFormat&>(other);
// test for capitalization info equality is adequately handled
// by the NumberFormat test for fCapitalizationContext equality;
// the info here is just derived from that.
if (locale == rhs.locale &&
lenient == rhs.lenient &&
(localizations == nullptr
? rhs.localizations == nullptr
: (rhs.localizations == nullptr
? false
: *localizations == rhs.localizations))) {
NFRuleSet** p = fRuleSets;
NFRuleSet** q = rhs.fRuleSets;
if (p == nullptr) {
return q == nullptr;
} else if (q == nullptr) {
return false;
}
while (*p && *q && (**p == **q)) {
++p;
++q;
}
return *q == nullptr && *p == nullptr;
}
}
return false;
}
UnicodeString
RuleBasedNumberFormat::getRules() const
{
UnicodeString result;
if (fRuleSets != nullptr) {
for (NFRuleSet** p = fRuleSets; *p; ++p) {
(*p)->appendRules(result);
}
}
return result;
}
UnicodeString
RuleBasedNumberFormat::getRuleSetName(int32_t index) const
{
if (localizations) {
UnicodeString string(true, localizations->getRuleSetName(index), (int32_t)-1);
return string;
}
else if (fRuleSets) {
UnicodeString result;
for (NFRuleSet** p = fRuleSets; *p; ++p) {
NFRuleSet* rs = *p;
if (rs->isPublic()) {
if (--index == -1) {
rs->getName(result);
return result;
}
}
}
}
UnicodeString empty;
return empty;
}
int32_t
RuleBasedNumberFormat::getNumberOfRuleSetNames() const
{
int32_t result = 0;
if (localizations) {
result = localizations->getNumberOfRuleSets();
}
else if (fRuleSets) {
for (NFRuleSet** p = fRuleSets; *p; ++p) {
if ((**p).isPublic()) {
++result;
}
}
}
return result;
}
int32_t
RuleBasedNumberFormat::getNumberOfRuleSetDisplayNameLocales() const {
if (localizations) {
return localizations->getNumberOfDisplayLocales();
}
return 0;
}
Locale
RuleBasedNumberFormat::getRuleSetDisplayNameLocale(int32_t index, UErrorCode& status) const {
if (U_FAILURE(status)) {
return Locale("");
}
if (localizations && index >= 0 && index < localizations->getNumberOfDisplayLocales()) {
UnicodeString name(true, localizations->getLocaleName(index), -1);
char buffer[64];
int32_t cap = name.length() + 1;
char* bp = buffer;
if (cap > 64) {
bp = (char *)uprv_malloc(cap);
if (bp == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return Locale("");
}
}
name.extract(0, name.length(), bp, cap, UnicodeString::kInvariant);
Locale retLocale(bp);
if (bp != buffer) {
uprv_free(bp);
}
return retLocale;
}
status = U_ILLEGAL_ARGUMENT_ERROR;
Locale retLocale;
return retLocale;
}
UnicodeString
RuleBasedNumberFormat::getRuleSetDisplayName(int32_t index, const Locale& localeParam) {
if (localizations && index >= 0 && index < localizations->getNumberOfRuleSets()) {
UnicodeString localeName(localeParam.getBaseName(), -1, UnicodeString::kInvariant);
int32_t len = localeName.length();
char16_t* localeStr = localeName.getBuffer(len + 1);
while (len >= 0) {
localeStr[len] = 0;
int32_t ix = localizations->indexForLocale(localeStr);
if (ix >= 0) {
UnicodeString name(true, localizations->getDisplayName(ix, index), -1);
return name;
}
// trim trailing portion, skipping over omitted sections
do { --len;} while (len > 0 && localeStr[len] != 0x005f); // underscore
while (len > 0 && localeStr[len-1] == 0x005F) --len;
}
UnicodeString name(true, localizations->getRuleSetName(index), -1);
return name;
}
UnicodeString bogus;
bogus.setToBogus();
return bogus;
}
UnicodeString
RuleBasedNumberFormat::getRuleSetDisplayName(const UnicodeString& ruleSetName, const Locale& localeParam) {
if (localizations) {
UnicodeString rsn(ruleSetName);
int32_t ix = localizations->indexForRuleSet(rsn.getTerminatedBuffer());
return getRuleSetDisplayName(ix, localeParam);
}
UnicodeString bogus;
bogus.setToBogus();
return bogus;
}
NFRuleSet*
RuleBasedNumberFormat::findRuleSet(const UnicodeString& name, UErrorCode& status) const
{
if (U_SUCCESS(status) && fRuleSets) {
for (NFRuleSet** p = fRuleSets; *p; ++p) {
NFRuleSet* rs = *p;
if (rs->isNamed(name)) {
return rs;
}
}
status = U_ILLEGAL_ARGUMENT_ERROR;
}
return nullptr;
}
UnicodeString&
RuleBasedNumberFormat::format(const DecimalQuantity &number,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode &status) const {
if (U_FAILURE(status)) {
return appendTo;
}
DecimalQuantity copy(number);
if (copy.fitsInLong()) {
format(number.toLong(), appendTo, pos, status);
}
else {
copy.roundToMagnitude(0, number::impl::RoundingMode::UNUM_ROUND_HALFEVEN, status);
if (copy.fitsInLong()) {
format(number.toDouble(), appendTo, pos, status);
}
else {
// We're outside of our normal range that this framework can handle.
// The DecimalFormat will provide more accurate results.
// TODO this section should probably be optimized. The DecimalFormat is shared in ICU4J.
LocalPointer<NumberFormat> decimalFormat(NumberFormat::createInstance(locale, UNUM_DECIMAL, status), status);
if (decimalFormat.isNull()) {
return appendTo;
}
Formattable f;
LocalPointer<DecimalQuantity> decimalQuantity(new DecimalQuantity(number), status);
if (decimalQuantity.isNull()) {
return appendTo;
}
f.adoptDecimalQuantity(decimalQuantity.orphan()); // f now owns decimalQuantity.
decimalFormat->format(f, appendTo, pos, status);
}
}
return appendTo;
}
UnicodeString&
RuleBasedNumberFormat::format(int32_t number,
UnicodeString& toAppendTo,
FieldPosition& pos) const
{
return format((int64_t)number, toAppendTo, pos);
}
UnicodeString&
RuleBasedNumberFormat::format(int64_t number,
UnicodeString& toAppendTo,
FieldPosition& /* pos */) const
{
if (defaultRuleSet) {
UErrorCode status = U_ZERO_ERROR;
format(number, defaultRuleSet, toAppendTo, status);
}
return toAppendTo;
}
UnicodeString&
RuleBasedNumberFormat::format(double number,
UnicodeString& toAppendTo,
FieldPosition& /* pos */) const
{
UErrorCode status = U_ZERO_ERROR;
if (defaultRuleSet) {
format(number, *defaultRuleSet, toAppendTo, status);
}
return toAppendTo;
}
UnicodeString&
RuleBasedNumberFormat::format(int32_t number,
const UnicodeString& ruleSetName,
UnicodeString& toAppendTo,
FieldPosition& pos,
UErrorCode& status) const
{
return format((int64_t)number, ruleSetName, toAppendTo, pos, status);
}
UnicodeString&
RuleBasedNumberFormat::format(int64_t number,
const UnicodeString& ruleSetName,
UnicodeString& toAppendTo,
FieldPosition& /* pos */,
UErrorCode& status) const
{
if (U_SUCCESS(status)) {
if (ruleSetName.indexOf(gPercentPercent, 2, 0) == 0) {
// throw new IllegalArgumentException("Can't use internal rule set");
status = U_ILLEGAL_ARGUMENT_ERROR;
} else {
NFRuleSet *rs = findRuleSet(ruleSetName, status);
if (rs) {
format(number, rs, toAppendTo, status);
}
}
}
return toAppendTo;
}
UnicodeString&
RuleBasedNumberFormat::format(double number,
const UnicodeString& ruleSetName,
UnicodeString& toAppendTo,
FieldPosition& /* pos */,
UErrorCode& status) const
{
if (U_SUCCESS(status)) {
if (ruleSetName.indexOf(gPercentPercent, 2, 0) == 0) {
// throw new IllegalArgumentException("Can't use internal rule set");
status = U_ILLEGAL_ARGUMENT_ERROR;
} else {
NFRuleSet *rs = findRuleSet(ruleSetName, status);
if (rs) {
format(number, *rs, toAppendTo, status);
}
}
}
return toAppendTo;
}
void
RuleBasedNumberFormat::format(double number,
NFRuleSet& rs,
UnicodeString& toAppendTo,
UErrorCode& status) const
{
int32_t startPos = toAppendTo.length();
if (getRoundingMode() != DecimalFormat::ERoundingMode::kRoundUnnecessary && !uprv_isNaN(number) && !uprv_isInfinite(number)) {
DecimalQuantity digitList;
digitList.setToDouble(number);
digitList.roundToMagnitude(
-getMaximumFractionDigits(),
static_cast<UNumberFormatRoundingMode>(getRoundingMode()),
status);
number = digitList.toDouble();
}
rs.format(number, toAppendTo, toAppendTo.length(), 0, status);
adjustForCapitalizationContext(startPos, toAppendTo, status);
}
/**
* Bottleneck through which all the public format() methods
* that take a long pass. By the time we get here, we know
* which rule set we're using to do the formatting.
* @param number The number to format
* @param ruleSet The rule set to use to format the number
* @return The text that resulted from formatting the number
*/
UnicodeString&
RuleBasedNumberFormat::format(int64_t number, NFRuleSet *ruleSet, UnicodeString& toAppendTo, UErrorCode& status) const
{
// all API format() routines that take a double vector through
// here. We have these two identical functions-- one taking a
// double and one taking a long-- the couple digits of precision
// that long has but double doesn't (both types are 8 bytes long,
// but double has to borrow some of the mantissa bits to hold
// the exponent).
// Create an empty string buffer where the result will
// be built, and pass it to the rule set (along with an insertion
// position of 0 and the number being formatted) to the rule set
// for formatting
if (U_SUCCESS(status)) {
if (number == U_INT64_MIN) {
// We can't handle this value right now. Provide an accurate default value.
// TODO this section should probably be optimized. The DecimalFormat is shared in ICU4J.
NumberFormat *decimalFormat = NumberFormat::createInstance(locale, UNUM_DECIMAL, status);
if (decimalFormat == nullptr) {
return toAppendTo;
}
Formattable f;
FieldPosition pos(FieldPosition::DONT_CARE);
DecimalQuantity *decimalQuantity = new DecimalQuantity();
if (decimalQuantity == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
delete decimalFormat;
return toAppendTo;
}
decimalQuantity->setToLong(number);
f.adoptDecimalQuantity(decimalQuantity); // f now owns decimalQuantity.
decimalFormat->format(f, toAppendTo, pos, status);
delete decimalFormat;
}
else {
int32_t startPos = toAppendTo.length();
ruleSet->format(number, toAppendTo, toAppendTo.length(), 0, status);
adjustForCapitalizationContext(startPos, toAppendTo, status);
}
}
return toAppendTo;
}
UnicodeString&
RuleBasedNumberFormat::adjustForCapitalizationContext(int32_t startPos,
UnicodeString& currentResult,
UErrorCode& status) const
{
#if !UCONFIG_NO_BREAK_ITERATION
UDisplayContext capitalizationContext = getContext(UDISPCTX_TYPE_CAPITALIZATION, status);
if (capitalizationContext != UDISPCTX_CAPITALIZATION_NONE && startPos == 0 && currentResult.length() > 0) {
// capitalize currentResult according to context
UChar32 ch = currentResult.char32At(0);
if (u_islower(ch) && U_SUCCESS(status) && capitalizationBrkIter != nullptr &&
( capitalizationContext == UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE ||
(capitalizationContext == UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU && capitalizationForUIListMenu) ||
(capitalizationContext == UDISPCTX_CAPITALIZATION_FOR_STANDALONE && capitalizationForStandAlone)) ) {
// titlecase first word of currentResult, here use sentence iterator unlike current implementations
// in LocaleDisplayNamesImpl::adjustForUsageAndContext and RelativeDateFormat::format
currentResult.toTitle(capitalizationBrkIter, locale, U_TITLECASE_NO_LOWERCASE | U_TITLECASE_NO_BREAK_ADJUSTMENT);
}
}
#endif
return currentResult;
}
void
RuleBasedNumberFormat::parse(const UnicodeString& text,
Formattable& result,
ParsePosition& parsePosition) const
{
if (!fRuleSets) {
parsePosition.setErrorIndex(0);
return;
}
UnicodeString workingText(text, parsePosition.getIndex());
ParsePosition workingPos(0);
ParsePosition high_pp(0);
Formattable high_result;
for (NFRuleSet** p = fRuleSets; *p; ++p) {
NFRuleSet *rp = *p;
if (rp->isPublic() && rp->isParseable()) {
ParsePosition working_pp(0);
Formattable working_result;
#if APPLE_ICU_CHANGES
// rdar://
rp->parse(workingText, working_pp, kMaxDouble, 0, working_result, lenient);
#else
rp->parse(workingText, working_pp, kMaxDouble, 0, working_result);
#endif // APPLE_ICU_CHANGES
if (working_pp.getIndex() > high_pp.getIndex()) {
high_pp = working_pp;
high_result = working_result;
if (high_pp.getIndex() == workingText.length()) {
break;
}
}
}
}
int32_t startIndex = parsePosition.getIndex();
parsePosition.setIndex(startIndex + high_pp.getIndex());
if (high_pp.getIndex() > 0) {
parsePosition.setErrorIndex(-1);
} else {
int32_t errorIndex = (high_pp.getErrorIndex()>0)? high_pp.getErrorIndex(): 0;
parsePosition.setErrorIndex(startIndex + errorIndex);
}
result = high_result;
if (result.getType() == Formattable::kDouble) {
double d = result.getDouble();
if (!uprv_isNaN(d) && d == uprv_trunc(d) && INT32_MIN <= d && d <= INT32_MAX) {
// Note: casting a double to an int when the double is too large or small
// to fit the destination is undefined behavior. The explicit range checks,
// above, are required. Just casting and checking the result value is undefined.
result.setLong(static_cast<int32_t>(d));
}
}
}
#if !UCONFIG_NO_COLLATION
void
RuleBasedNumberFormat::setLenient(UBool enabled)
{
lenient = enabled;
if (!enabled && collator) {
delete collator;
collator = nullptr;
}
}
#endif
void
RuleBasedNumberFormat::setDefaultRuleSet(const UnicodeString& ruleSetName, UErrorCode& status) {
if (U_SUCCESS(status)) {
if (ruleSetName.isEmpty()) {
if (localizations) {
UnicodeString name(true, localizations->getRuleSetName(0), -1);
defaultRuleSet = findRuleSet(name, status);
} else {
initDefaultRuleSet();
}
} else if (ruleSetName.startsWith(UNICODE_STRING_SIMPLE("%%"))) {
status = U_ILLEGAL_ARGUMENT_ERROR;
} else {
NFRuleSet* result = findRuleSet(ruleSetName, status);
if (result != nullptr) {
defaultRuleSet = result;
}
}
}
}
UnicodeString
RuleBasedNumberFormat::getDefaultRuleSetName() const {
UnicodeString result;
if (defaultRuleSet && defaultRuleSet->isPublic()) {
defaultRuleSet->getName(result);
} else {
result.setToBogus();
}
return result;
}
void
RuleBasedNumberFormat::initDefaultRuleSet()
{
defaultRuleSet = nullptr;
if (!fRuleSets) {
return;
}
const UnicodeString spellout(UNICODE_STRING_SIMPLE("%spellout-numbering"));
const UnicodeString ordinal(UNICODE_STRING_SIMPLE("%digits-ordinal"));
const UnicodeString duration(UNICODE_STRING_SIMPLE("%duration"));
NFRuleSet**p = &fRuleSets[0];
while (*p) {
if ((*p)->isNamed(spellout) || (*p)->isNamed(ordinal) || (*p)->isNamed(duration)) {
defaultRuleSet = *p;
return;
} else {
++p;
}
}
defaultRuleSet = *--p;
if (!defaultRuleSet->isPublic()) {
while (p != fRuleSets) {
if ((*--p)->isPublic()) {
defaultRuleSet = *p;
break;
}
}
}
}
void
RuleBasedNumberFormat::init(const UnicodeString& rules, LocalizationInfo* localizationInfos,
UParseError& pErr, UErrorCode& status)
{
// TODO: implement UParseError
uprv_memset(&pErr, 0, sizeof(UParseError));
// Note: this can leave ruleSets == nullptr, so remaining code should check
if (U_FAILURE(status)) {
return;
}
initializeDecimalFormatSymbols(status);
initializeDefaultInfinityRule(status);
initializeDefaultNaNRule(status);
if (U_FAILURE(status)) {
return;
}
this->localizations = localizationInfos == nullptr ? nullptr : localizationInfos->ref();
UnicodeString description(rules);
if (!description.length()) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
// start by stripping the trailing whitespace from all the rules
// (this is all the whitespace following each semicolon in the
// description). This allows us to look for rule-set boundaries
// by searching for ";%" without having to worry about whitespace
// between the ; and the %
stripWhitespace(description);
// check to see if there's a set of lenient-parse rules. If there
// is, pull them out into our temporary holding place for them,
// and delete them from the description before the real desciption-
// parsing code sees them
int32_t lp = description.indexOf(gLenientParse, -1, 0);
if (lp != -1) {
// we've got to make sure we're not in the middle of a rule
// (where "%%lenient-parse" would actually get treated as
// rule text)
if (lp == 0 || description.charAt(lp - 1) == gSemiColon) {
// locate the beginning and end of the actual collation
// rules (there may be whitespace between the name and
// the first token in the description)
int lpEnd = description.indexOf(gSemiPercent, 2, lp);
if (lpEnd == -1) {
lpEnd = description.length() - 1;
}
int lpStart = lp + u_strlen(gLenientParse);
while (PatternProps::isWhiteSpace(description.charAt(lpStart))) {
++lpStart;
}
// copy out the lenient-parse rules and delete them
// from the description
lenientParseRules = new UnicodeString();
/* test for nullptr */
if (lenientParseRules == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
lenientParseRules->setTo(description, lpStart, lpEnd - lpStart);
description.remove(lp, lpEnd + 1 - lp);
}
}
// pre-flight parsing the description and count the number of
// rule sets (";%" marks the end of one rule set and the beginning
// of the next)
numRuleSets = 0;
for (int32_t p = description.indexOf(gSemiPercent, 2, 0); p != -1; p = description.indexOf(gSemiPercent, 2, p)) {
++numRuleSets;
++p;
}
++numRuleSets;
// our rule list is an array of the appropriate size
fRuleSets = (NFRuleSet **)uprv_malloc((numRuleSets + 1) * sizeof(NFRuleSet *));
/* test for nullptr */
if (fRuleSets == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
for (int i = 0; i <= numRuleSets; ++i) {
fRuleSets[i] = nullptr;
}
// divide up the descriptions into individual rule-set descriptions
// and store them in a temporary array. At each step, we also
// new up a rule set, but all this does is initialize its name
// and remove it from its description. We can't actually parse
// the rest of the descriptions and finish initializing everything
// because we have to know the names and locations of all the rule
// sets before we can actually set everything up
if(!numRuleSets) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
ruleSetDescriptions = new UnicodeString[numRuleSets];
if (ruleSetDescriptions == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
{
int curRuleSet = 0;
int32_t start = 0;
for (int32_t p = description.indexOf(gSemiPercent, 2, 0); p != -1; p = description.indexOf(gSemiPercent, 2, start)) {
ruleSetDescriptions[curRuleSet].setTo(description, start, p + 1 - start);
fRuleSets[curRuleSet] = new NFRuleSet(this, ruleSetDescriptions, curRuleSet, status);
if (fRuleSets[curRuleSet] == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
++curRuleSet;
start = p + 1;
}
ruleSetDescriptions[curRuleSet].setTo(description, start, description.length() - start);
fRuleSets[curRuleSet] = new NFRuleSet(this, ruleSetDescriptions, curRuleSet, status);
if (fRuleSets[curRuleSet] == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
// now we can take note of the formatter's default rule set, which
// is the last public rule set in the description (it's the last
// rather than the first so that a user can create a new formatter
// from an existing formatter and change its default behavior just
// by appending more rule sets to the end)
// {dlf} Initialization of a fraction rule set requires the default rule
// set to be known. For purposes of initialization, this is always the
// last public rule set, no matter what the localization data says.
initDefaultRuleSet();
// finally, we can go back through the temporary descriptions
// list and finish setting up the substructure (and we throw
// away the temporary descriptions as we go)
{
for (int i = 0; i < numRuleSets; i++) {
fRuleSets[i]->parseRules(ruleSetDescriptions[i], status);
}
}
// Now that the rules are initialized, the 'real' default rule
// set can be adjusted by the localization data.
// The C code keeps the localization array as is, rather than building
// a separate array of the public rule set names, so we have less work
// to do here-- but we still need to check the names.
if (localizationInfos) {
// confirm the names, if any aren't in the rules, that's an error
// it is ok if the rules contain public rule sets that are not in this list
for (int32_t i = 0; i < localizationInfos->getNumberOfRuleSets(); ++i) {
UnicodeString name(true, localizationInfos->getRuleSetName(i), -1);
NFRuleSet* rs = findRuleSet(name, status);
if (rs == nullptr) {
break; // error
}
if (i == 0) {
defaultRuleSet = rs;
}
}
} else {
defaultRuleSet = getDefaultRuleSet();
}
originalDescription = rules;
}
// override the NumberFormat implementation in order to
// lazily initialize relevant items
void
RuleBasedNumberFormat::setContext(UDisplayContext value, UErrorCode& status)
{
NumberFormat::setContext(value, status);
if (U_SUCCESS(status)) {
if (!capitalizationInfoSet &&
(value==UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU || value==UDISPCTX_CAPITALIZATION_FOR_STANDALONE)) {
initCapitalizationContextInfo(locale);
capitalizationInfoSet = true;
}
#if !UCONFIG_NO_BREAK_ITERATION
if ( capitalizationBrkIter == nullptr && (value==UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE ||
(value==UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU && capitalizationForUIListMenu) ||
(value==UDISPCTX_CAPITALIZATION_FOR_STANDALONE && capitalizationForStandAlone)) ) {
status = U_ZERO_ERROR;
capitalizationBrkIter = BreakIterator::createSentenceInstance(locale, status);
if (U_FAILURE(status)) {
delete capitalizationBrkIter;
capitalizationBrkIter = nullptr;
}
}
#endif
}
}
void
RuleBasedNumberFormat::initCapitalizationContextInfo(const Locale& thelocale)
{
#if !UCONFIG_NO_BREAK_ITERATION
const char * localeID = (thelocale != nullptr)? thelocale.getBaseName(): nullptr;
UErrorCode status = U_ZERO_ERROR;
UResourceBundle *rb = ures_open(nullptr, localeID, &status);
rb = ures_getByKeyWithFallback(rb, "contextTransforms", rb, &status);
rb = ures_getByKeyWithFallback(rb, "number-spellout", rb, &status);
if (U_SUCCESS(status) && rb != nullptr) {
int32_t len = 0;
const int32_t * intVector = ures_getIntVector(rb, &len, &status);
if (U_SUCCESS(status) && intVector != nullptr && len >= 2) {
capitalizationForUIListMenu = static_cast<UBool>(intVector[0]);
capitalizationForStandAlone = static_cast<UBool>(intVector[1]);
}
}
ures_close(rb);
#endif
}
void
RuleBasedNumberFormat::stripWhitespace(UnicodeString& description)
{
// iterate through the characters...
UnicodeString result;
int start = 0;
while (start != -1 && start < description.length()) {
// seek to the first non-whitespace character...
while (start < description.length()
&& PatternProps::isWhiteSpace(description.charAt(start))) {
++start;
}
// locate the next semicolon in the text and copy the text from
// our current position up to that semicolon into the result
int32_t p = description.indexOf(gSemiColon, start);
if (p == -1) {
// or if we don't find a semicolon, just copy the rest of
// the string into the result
result.append(description, start, description.length() - start);
start = -1;
}
else if (p < description.length()) {
result.append(description, start, p + 1 - start);
start = p + 1;
}
// when we get here, we've seeked off the end of the string, and
// we terminate the loop (we continue until *start* is -1 rather
// than until *p* is -1, because otherwise we'd miss the last
// rule in the description)
else {
start = -1;
}
}
description.setTo(result);
}
void
RuleBasedNumberFormat::dispose()
{
if (fRuleSets) {
for (NFRuleSet** p = fRuleSets; *p; ++p) {
delete *p;
}
uprv_free(fRuleSets);
fRuleSets = nullptr;
}
if (ruleSetDescriptions) {
delete [] ruleSetDescriptions;
ruleSetDescriptions = nullptr;
}
#if !UCONFIG_NO_COLLATION
delete collator;
#endif
collator = nullptr;
delete decimalFormatSymbols;
decimalFormatSymbols = nullptr;
delete defaultInfinityRule;
defaultInfinityRule = nullptr;
delete defaultNaNRule;
defaultNaNRule = nullptr;
delete lenientParseRules;
lenientParseRules = nullptr;
#if !UCONFIG_NO_BREAK_ITERATION
delete capitalizationBrkIter;
capitalizationBrkIter = nullptr;
#endif
if (localizations) {
localizations = localizations->unref();
}
}
//-----------------------------------------------------------------------
// package-internal API
//-----------------------------------------------------------------------
/**
* Returns the collator to use for lenient parsing. The collator is lazily created:
* this function creates it the first time it's called.
* @return The collator to use for lenient parsing, or null if lenient parsing
* is turned off.
*/
const RuleBasedCollator*
RuleBasedNumberFormat::getCollator() const
{
#if !UCONFIG_NO_COLLATION
if (!fRuleSets) {
return nullptr;
}
// lazy-evaluate the collator
if (collator == nullptr && lenient) {
// create a default collator based on the formatter's locale,
// then pull out that collator's rules, append any additional
// rules specified in the description, and create a _new_
// collator based on the combination of those rules
UErrorCode status = U_ZERO_ERROR;
Collator* temp = Collator::createInstance(locale, status);
RuleBasedCollator* newCollator;
if (U_SUCCESS(status) && (newCollator = dynamic_cast<RuleBasedCollator*>(temp)) != nullptr) {
if (lenientParseRules) {
UnicodeString rules(newCollator->getRules());
rules.append(*lenientParseRules);
newCollator = new RuleBasedCollator(rules, status);
// Exit if newCollator could not be created.
if (newCollator == nullptr) {
return nullptr;
}
} else {
temp = nullptr;
}
if (U_SUCCESS(status)) {
newCollator->setAttribute(UCOL_DECOMPOSITION_MODE, UCOL_ON, status);
// cast away const
((RuleBasedNumberFormat*)this)->collator = newCollator;
} else {
delete newCollator;
}
}
delete temp;
}
#endif
// if lenient-parse mode is off, this will be null
// (see setLenientParseMode())
return collator;
}
DecimalFormatSymbols*
RuleBasedNumberFormat::initializeDecimalFormatSymbols(UErrorCode &status)
{
// lazy-evaluate the DecimalFormatSymbols object. This object
// is shared by all DecimalFormat instances belonging to this
// formatter
if (decimalFormatSymbols == nullptr) {
LocalPointer<DecimalFormatSymbols> temp(new DecimalFormatSymbols(locale, status), status);
if (U_SUCCESS(status)) {
decimalFormatSymbols = temp.orphan();
}
}
return decimalFormatSymbols;
}
/**
* Returns the DecimalFormatSymbols object that should be used by all DecimalFormat
* instances owned by this formatter.
*/
const DecimalFormatSymbols*
RuleBasedNumberFormat::getDecimalFormatSymbols() const
{
return decimalFormatSymbols;
}
NFRule*
RuleBasedNumberFormat::initializeDefaultInfinityRule(UErrorCode &status)
{
if (U_FAILURE(status)) {
return nullptr;
}
if (defaultInfinityRule == nullptr) {
UnicodeString rule(UNICODE_STRING_SIMPLE("Inf: "));
rule.append(getDecimalFormatSymbols()->getSymbol(DecimalFormatSymbols::kInfinitySymbol));
LocalPointer<NFRule> temp(new NFRule(this, rule, status), status);
if (U_SUCCESS(status)) {
defaultInfinityRule = temp.orphan();
}
}
return defaultInfinityRule;
}
const NFRule*
RuleBasedNumberFormat::getDefaultInfinityRule() const
{
return defaultInfinityRule;
}
NFRule*
RuleBasedNumberFormat::initializeDefaultNaNRule(UErrorCode &status)
{
if (U_FAILURE(status)) {
return nullptr;
}
if (defaultNaNRule == nullptr) {
UnicodeString rule(UNICODE_STRING_SIMPLE("NaN: "));
rule.append(getDecimalFormatSymbols()->getSymbol(DecimalFormatSymbols::kNaNSymbol));
LocalPointer<NFRule> temp(new NFRule(this, rule, status), status);
if (U_SUCCESS(status)) {
defaultNaNRule = temp.orphan();
}
}
return defaultNaNRule;
}
const NFRule*
RuleBasedNumberFormat::getDefaultNaNRule() const
{
return defaultNaNRule;
}
// De-owning the current localized symbols and adopt the new symbols.
void
RuleBasedNumberFormat::adoptDecimalFormatSymbols(DecimalFormatSymbols* symbolsToAdopt)
{
if (symbolsToAdopt == nullptr) {
return; // do not allow caller to set decimalFormatSymbols to nullptr
}
if (decimalFormatSymbols != nullptr) {
delete decimalFormatSymbols;
}
decimalFormatSymbols = symbolsToAdopt;
{
// Apply the new decimalFormatSymbols by reparsing the rulesets
UErrorCode status = U_ZERO_ERROR;
delete defaultInfinityRule;
defaultInfinityRule = nullptr;
initializeDefaultInfinityRule(status); // Reset with the new DecimalFormatSymbols
delete defaultNaNRule;
defaultNaNRule = nullptr;
initializeDefaultNaNRule(status); // Reset with the new DecimalFormatSymbols
if (fRuleSets) {
for (int32_t i = 0; i < numRuleSets; i++) {
fRuleSets[i]->setDecimalFormatSymbols(*symbolsToAdopt, status);
}
}
}
}
// Setting the symbols is equivalent to adopting a newly created localized symbols.
void
RuleBasedNumberFormat::setDecimalFormatSymbols(const DecimalFormatSymbols& symbols)
{
adoptDecimalFormatSymbols(new DecimalFormatSymbols(symbols));
}
PluralFormat *
RuleBasedNumberFormat::createPluralFormat(UPluralType pluralType,
const UnicodeString &pattern,
UErrorCode& status) const
{
auto *pf = new PluralFormat(locale, pluralType, pattern, status);
if (pf == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
}
return pf;
}
/**
* Get the rounding mode.
* @return A rounding mode
*/
DecimalFormat::ERoundingMode RuleBasedNumberFormat::getRoundingMode() const {
return fRoundingMode;
}
/**
* Set the rounding mode. This has no effect unless the rounding
* increment is greater than zero.
* @param roundingMode A rounding mode
*/
void RuleBasedNumberFormat::setRoundingMode(DecimalFormat::ERoundingMode roundingMode) {
fRoundingMode = roundingMode;
}
U_NAMESPACE_END
/* U_HAVE_RBNF */
#endif
|