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
|
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
**********************************************************************
* Copyright (c) 2004-2016, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* Author: Alan Liu
* Created: April 20, 2004
* Since: ICU 3.0
**********************************************************************
*/
#include "utypeinfo.h" // for 'typeid' to work
#include <_foundation_unicode/utypes.h>
#if !UCONFIG_NO_FORMATTING
#include <_foundation_unicode/measfmt.h>
#include <_foundation_unicode/numfmt.h>
#include "currfmt.h"
#include <_foundation_unicode/localpointer.h>
#include "resource.h"
#include <_foundation_unicode/simpleformatter.h>
#include "quantityformatter.h"
#include <_foundation_unicode/plurrule.h>
#include <_foundation_unicode/decimfmt.h>
#include "uresimp.h"
#include <_foundation_unicode/ures.h>
#include <_foundation_unicode/ustring.h>
#include "ureslocs.h"
#include "cstring.h"
#include "mutex.h"
#include "ucln_in.h"
#include <_foundation_unicode/listformatter.h>
#include "charstr.h"
#include <_foundation_unicode/putil.h>
#include <_foundation_unicode/smpdtfmt.h>
#include "uassert.h"
#include <_foundation_unicode/numberformatter.h>
#include "number_longnames.h"
#include "number_utypes.h"
#if APPLE_ICU_CHANGES
// rdar:/
// Apple-specific
#include <_foundation_unicode/uameasureformat.h>
#include "fphdlimp.h"
#endif // APPLE_ICU_CHANGES
#include "sharednumberformat.h"
#include "sharedpluralrules.h"
#include "standardplural.h"
#include "unifiedcache.h"
U_NAMESPACE_BEGIN
using number::impl::UFormattedNumberData;
static constexpr int32_t WIDTH_INDEX_COUNT = UMEASFMT_WIDTH_NARROW + 1;
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(MeasureFormat)
// Used to format durations like 5:47 or 21:35:42.
class NumericDateFormatters : public UMemory {
public:
// Formats like H:mm
UnicodeString hourMinute;
// formats like M:ss
UnicodeString minuteSecond;
// formats like H:mm:ss
UnicodeString hourMinuteSecond;
// Constructor that takes the actual patterns for hour-minute,
// minute-second, and hour-minute-second respectively.
NumericDateFormatters(
const UnicodeString &hm,
const UnicodeString &ms,
const UnicodeString &hms) :
hourMinute(hm),
minuteSecond(ms),
hourMinuteSecond(hms) {
}
private:
NumericDateFormatters(const NumericDateFormatters &other);
NumericDateFormatters &operator=(const NumericDateFormatters &other);
};
static UMeasureFormatWidth getRegularWidth(UMeasureFormatWidth width) {
if (width >= WIDTH_INDEX_COUNT) {
return UMEASFMT_WIDTH_NARROW;
}
return width;
}
static UNumberUnitWidth getUnitWidth(UMeasureFormatWidth width) {
switch (width) {
case UMEASFMT_WIDTH_WIDE:
return UNUM_UNIT_WIDTH_FULL_NAME;
case UMEASFMT_WIDTH_NARROW:
case UMEASFMT_WIDTH_NUMERIC:
return UNUM_UNIT_WIDTH_NARROW;
case UMEASFMT_WIDTH_SHORT:
default:
return UNUM_UNIT_WIDTH_SHORT;
}
}
/**
* Instances contain all MeasureFormat specific data for a particular locale.
* This data is cached. It is never copied, but is shared via shared pointers.
*
* Note: We might change the cache data to have an array[WIDTH_INDEX_COUNT] of
* complete sets of unit & per patterns,
* to correspond to the resource data and its aliases.
*
* TODO: Maybe store more sparsely in general, with pointers rather than potentially-empty objects.
*/
class MeasureFormatCacheData : public SharedObject {
public:
/**
* Redirection data from root-bundle, top-level sideways aliases.
* - UMEASFMT_WIDTH_COUNT: initial value, just fall back to root
* - UMEASFMT_WIDTH_WIDE/SHORT/NARROW: sideways alias for missing data
*/
UMeasureFormatWidth widthFallback[WIDTH_INDEX_COUNT];
MeasureFormatCacheData();
virtual ~MeasureFormatCacheData();
void adoptCurrencyFormat(int32_t widthIndex, NumberFormat *nfToAdopt) {
delete currencyFormats[widthIndex];
currencyFormats[widthIndex] = nfToAdopt;
}
const NumberFormat *getCurrencyFormat(UMeasureFormatWidth width) const {
return currencyFormats[getRegularWidth(width)];
}
void adoptIntegerFormat(NumberFormat *nfToAdopt) {
delete integerFormat;
integerFormat = nfToAdopt;
}
const NumberFormat *getIntegerFormat() const {
return integerFormat;
}
void adoptNumericDateFormatters(NumericDateFormatters *formattersToAdopt) {
delete numericDateFormatters;
numericDateFormatters = formattersToAdopt;
}
const NumericDateFormatters *getNumericDateFormatters() const {
return numericDateFormatters;
}
private:
NumberFormat* currencyFormats[WIDTH_INDEX_COUNT];
NumberFormat* integerFormat;
NumericDateFormatters* numericDateFormatters;
MeasureFormatCacheData(const MeasureFormatCacheData &other);
MeasureFormatCacheData &operator=(const MeasureFormatCacheData &other);
};
MeasureFormatCacheData::MeasureFormatCacheData()
: integerFormat(nullptr), numericDateFormatters(nullptr) {
for (int32_t i = 0; i < WIDTH_INDEX_COUNT; ++i) {
widthFallback[i] = UMEASFMT_WIDTH_COUNT;
}
memset(currencyFormats, 0, sizeof(currencyFormats));
}
MeasureFormatCacheData::~MeasureFormatCacheData() {
for (int32_t i = 0; i < UPRV_LENGTHOF(currencyFormats); ++i) {
delete currencyFormats[i];
}
// Note: the contents of 'dnams' are pointers into the resource bundle
delete integerFormat;
delete numericDateFormatters;
}
static UBool isCurrency(const MeasureUnit &unit) {
return (uprv_strcmp(unit.getType(), "currency") == 0);
}
static UBool getString(
const UResourceBundle *resource,
UnicodeString &result,
UErrorCode &status) {
int32_t len = 0;
const char16_t *resStr = ures_getString(resource, &len, &status);
if (U_FAILURE(status)) {
return false;
}
result.setTo(true, resStr, len);
return true;
}
static UnicodeString loadNumericDateFormatterPattern(
const UResourceBundle *resource,
const char *pattern,
UErrorCode &status) {
UnicodeString result;
if (U_FAILURE(status)) {
return result;
}
CharString chs;
chs.append("durationUnits", status)
.append("/", status).append(pattern, status);
LocalUResourceBundlePointer patternBundle(
ures_getByKeyWithFallback(
resource,
chs.data(),
nullptr,
&status));
if (U_FAILURE(status)) {
return result;
}
getString(patternBundle.getAlias(), result, status);
// Replace 'h' with 'H'
int32_t len = result.length();
char16_t *buffer = result.getBuffer(len);
for (int32_t i = 0; i < len; ++i) {
if (buffer[i] == 0x68) { // 'h'
buffer[i] = 0x48; // 'H'
}
}
result.releaseBuffer(len);
return result;
}
static NumericDateFormatters *loadNumericDateFormatters(
const UResourceBundle *resource,
UErrorCode &status) {
if (U_FAILURE(status)) {
return nullptr;
}
NumericDateFormatters *result = new NumericDateFormatters(
loadNumericDateFormatterPattern(resource, "hm", status),
loadNumericDateFormatterPattern(resource, "ms", status),
loadNumericDateFormatterPattern(resource, "hms", status));
if (U_FAILURE(status)) {
delete result;
return nullptr;
}
return result;
}
template<>
const MeasureFormatCacheData *LocaleCacheKey<MeasureFormatCacheData>::createObject(
const void * /*unused*/, UErrorCode &status) const {
const char *localeId = fLoc.getName();
LocalUResourceBundlePointer unitsBundle(ures_open(U_ICUDATA_UNIT, localeId, &status));
static UNumberFormatStyle currencyStyles[] = {
UNUM_CURRENCY_PLURAL, UNUM_CURRENCY_ISO, UNUM_CURRENCY};
LocalPointer<MeasureFormatCacheData> result(new MeasureFormatCacheData(), status);
if (U_FAILURE(status)) {
return nullptr;
}
result->adoptNumericDateFormatters(loadNumericDateFormatters(
unitsBundle.getAlias(), status));
if (U_FAILURE(status)) {
return nullptr;
}
for (int32_t i = 0; i < WIDTH_INDEX_COUNT; ++i) {
// NumberFormat::createInstance can erase warning codes from status, so pass it
// a separate status instance
UErrorCode localStatus = U_ZERO_ERROR;
result->adoptCurrencyFormat(i, NumberFormat::createInstance(
localeId, currencyStyles[i], localStatus));
if (localStatus != U_ZERO_ERROR) {
status = localStatus;
}
if (U_FAILURE(status)) {
return nullptr;
}
}
NumberFormat *inf = NumberFormat::createInstance(
localeId, UNUM_DECIMAL, status);
if (U_FAILURE(status)) {
return nullptr;
}
inf->setMaximumFractionDigits(0);
DecimalFormat *decfmt = dynamic_cast<DecimalFormat *>(inf);
if (decfmt != nullptr) {
decfmt->setRoundingMode(DecimalFormat::kRoundDown);
}
result->adoptIntegerFormat(inf);
result->addRef();
return result.orphan();
}
static UBool isTimeUnit(const MeasureUnit &mu, const char *tu) {
return uprv_strcmp(mu.getType(), "duration") == 0 &&
uprv_strcmp(mu.getSubtype(), tu) == 0;
}
// Converts a composite measure into hours-minutes-seconds and stores at hms
// array. [0] is hours; [1] is minutes; [2] is seconds. Returns a bit map of
// units found: 1=hours, 2=minutes, 4=seconds. For example, if measures
// contains hours-minutes, this function would return 3.
//
// If measures cannot be converted into hours, minutes, seconds or if amounts
// are negative, or if hours, minutes, seconds are out of order, returns 0.
static int32_t toHMS(
const Measure *measures,
int32_t measureCount,
Formattable *hms,
UErrorCode &status) {
if (U_FAILURE(status)) {
return 0;
}
int32_t result = 0;
if (U_FAILURE(status)) {
return 0;
}
// We use copy constructor to ensure that both sides of equality operator
// are instances of MeasureUnit base class and not a subclass. Otherwise,
// operator== will immediately return false.
for (int32_t i = 0; i < measureCount; ++i) {
if (isTimeUnit(measures[i].getUnit(), "hour")) {
// hour must come first
if (result >= 1) {
return 0;
}
hms[0] = measures[i].getNumber();
if (hms[0].getDouble() < 0.0) {
return 0;
}
result |= 1;
} else if (isTimeUnit(measures[i].getUnit(), "minute")) {
// minute must come after hour
if (result >= 2) {
return 0;
}
hms[1] = measures[i].getNumber();
if (hms[1].getDouble() < 0.0) {
return 0;
}
result |= 2;
} else if (isTimeUnit(measures[i].getUnit(), "second")) {
// second must come after hour and minute
if (result >= 4) {
return 0;
}
hms[2] = measures[i].getNumber();
if (hms[2].getDouble() < 0.0) {
return 0;
}
result |= 4;
} else {
return 0;
}
}
return result;
}
MeasureFormat::MeasureFormat(
const Locale &locale, UMeasureFormatWidth w, UErrorCode &status)
: cache(nullptr),
numberFormat(nullptr),
pluralRules(nullptr),
#if APPLE_ICU_CHANGES
// rdar:/
fWidth((w==UMEASFMT_WIDTH_SHORTER)? UMEASFMT_WIDTH_SHORT: w),
stripPatternSpaces(w==UMEASFMT_WIDTH_SHORTER),
listFormatter(nullptr),
listFormatterStd(nullptr) {
initMeasureFormat(locale, (w==UMEASFMT_WIDTH_SHORTER)? UMEASFMT_WIDTH_SHORT: w, nullptr, status);
#else
fWidth(w),
listFormatter(nullptr) {
initMeasureFormat(locale, w, nullptr, status);
#endif // APPLE_ICU_CHANGES
}
MeasureFormat::MeasureFormat(
const Locale &locale,
UMeasureFormatWidth w,
NumberFormat *nfToAdopt,
UErrorCode &status)
: cache(nullptr),
numberFormat(nullptr),
pluralRules(nullptr),
#if APPLE_ICU_CHANGES
// rdar:/
fWidth((w==UMEASFMT_WIDTH_SHORTER)? UMEASFMT_WIDTH_SHORT: w),
stripPatternSpaces(w==UMEASFMT_WIDTH_SHORTER),
listFormatter(nullptr),
listFormatterStd(nullptr) {
initMeasureFormat(locale, (w==UMEASFMT_WIDTH_SHORTER)? UMEASFMT_WIDTH_SHORT: w, nfToAdopt, status);
#else
fWidth(w),
listFormatter(nullptr) {
initMeasureFormat(locale, w, nfToAdopt, status);
#endif // APPLE_ICU_CHANGES
}
MeasureFormat::MeasureFormat(const MeasureFormat &other) :
Format(other),
cache(other.cache),
numberFormat(other.numberFormat),
pluralRules(other.pluralRules),
fWidth(other.fWidth),
#if APPLE_ICU_CHANGES
// rdar:/
stripPatternSpaces(other.stripPatternSpaces),
listFormatter(nullptr),
listFormatterStd(nullptr) {
#else
listFormatter(nullptr) {
#endif // APPLE_ICU_CHANGES
cache->addRef();
numberFormat->addRef();
pluralRules->addRef();
if (other.listFormatter != nullptr) {
listFormatter = new ListFormatter(*other.listFormatter);
}
#if APPLE_ICU_CHANGES
// rdar:/
if (other.listFormatterStd != NULL) {
listFormatterStd = new ListFormatter(*other.listFormatterStd);
}
#endif // APPLE_ICU_CHANGES
}
MeasureFormat &MeasureFormat::operator=(const MeasureFormat &other) {
if (this == &other) {
return *this;
}
Format::operator=(other);
SharedObject::copyPtr(other.cache, cache);
SharedObject::copyPtr(other.numberFormat, numberFormat);
SharedObject::copyPtr(other.pluralRules, pluralRules);
fWidth = other.fWidth;
#if APPLE_ICU_CHANGES
// rdar:/
stripPatternSpaces = other.stripPatternSpaces;
#endif // APPLE_ICU_CHANGES
delete listFormatter;
if (other.listFormatter != nullptr) {
listFormatter = new ListFormatter(*other.listFormatter);
} else {
listFormatter = nullptr;
}
#if APPLE_ICU_CHANGES
// rdar:/
delete listFormatterStd;
if (other.listFormatterStd != NULL) {
listFormatterStd = new ListFormatter(*other.listFormatterStd);
} else {
listFormatterStd = NULL;
}
#endif // APPLE_ICU_CHANGES
return *this;
}
MeasureFormat::MeasureFormat() :
cache(nullptr),
numberFormat(nullptr),
pluralRules(nullptr),
fWidth(UMEASFMT_WIDTH_SHORT),
#if APPLE_ICU_CHANGES
// rdar:/
stripPatternSpaces(false),
listFormatter(nullptr),
listFormatterStd(nullptr) {
#else
listFormatter(nullptr) {
#endif // APPLE_ICU_CHANGES
}
MeasureFormat::~MeasureFormat() {
if (cache != nullptr) {
cache->removeRef();
}
if (numberFormat != nullptr) {
numberFormat->removeRef();
}
if (pluralRules != nullptr) {
pluralRules->removeRef();
}
delete listFormatter;
#if APPLE_ICU_CHANGES
// rdar:/
delete listFormatterStd;
#endif // APPLE_ICU_CHANGES
}
bool MeasureFormat::operator==(const Format &other) const {
if (this == &other) { // Same object, equal
return true;
}
if (!Format::operator==(other)) {
return false;
}
const MeasureFormat &rhs = static_cast<const MeasureFormat &>(other);
// Note: Since the ListFormatter depends only on Locale and width, we
// don't have to check it here.
// differing widths aren't equivalent
#if APPLE_ICU_CHANGES
// rdar:/
if (fWidth != rhs.fWidth || stripPatternSpaces != rhs.stripPatternSpaces) {
#else
if (fWidth != rhs.fWidth) {
#endif // APPLE_ICU_CHANGES
return false;
}
// Width the same check locales.
// We don't need to check locales if both objects have same cache.
if (cache != rhs.cache) {
UErrorCode status = U_ZERO_ERROR;
const char *localeId = getLocaleID(status);
const char *rhsLocaleId = rhs.getLocaleID(status);
if (U_FAILURE(status)) {
// On failure, assume not equal
return false;
}
if (uprv_strcmp(localeId, rhsLocaleId) != 0) {
return false;
}
}
// Locales same, check NumberFormat if shared data differs.
return (
numberFormat == rhs.numberFormat ||
**numberFormat == **rhs.numberFormat);
}
MeasureFormat *MeasureFormat::clone() const {
return new MeasureFormat(*this);
}
UnicodeString &MeasureFormat::format(
const Formattable &obj,
UnicodeString &appendTo,
FieldPosition &pos,
UErrorCode &status) const {
if (U_FAILURE(status)) return appendTo;
if (obj.getType() == Formattable::kObject) {
const UObject* formatObj = obj.getObject();
const Measure* amount = dynamic_cast<const Measure*>(formatObj);
if (amount != nullptr) {
return formatMeasure(
*amount, **numberFormat, appendTo, pos, status);
}
}
status = U_ILLEGAL_ARGUMENT_ERROR;
return appendTo;
}
void MeasureFormat::parseObject(
const UnicodeString & /*source*/,
Formattable & /*result*/,
ParsePosition& /*pos*/) const {
return;
}
UnicodeString &MeasureFormat::formatMeasurePerUnit(
const Measure &measure,
const MeasureUnit &perUnit,
UnicodeString &appendTo,
FieldPosition &pos,
UErrorCode &status) const {
if (U_FAILURE(status)) {
return appendTo;
}
auto* df = dynamic_cast<const DecimalFormat*>(&getNumberFormatInternal());
if (df == nullptr) {
// Don't know how to handle other types of NumberFormat
status = U_UNSUPPORTED_ERROR;
return appendTo;
}
UFormattedNumberData result;
if (auto* lnf = df->toNumberFormatter(status)) {
result.quantity.setToDouble(measure.getNumber().getDouble(status));
lnf->unit(measure.getUnit())
.perUnit(perUnit)
.unitWidth(getUnitWidth(fWidth))
.formatImpl(&result, status);
}
DecimalFormat::fieldPositionHelper(result, pos, appendTo.length(), status);
appendTo.append(result.toTempString(status));
return appendTo;
}
UnicodeString &MeasureFormat::formatMeasures(
const Measure *measures,
int32_t measureCount,
UnicodeString &appendTo,
FieldPosition &pos,
UErrorCode &status) const {
if (U_FAILURE(status)) {
return appendTo;
}
if (measureCount == 0) {
return appendTo;
}
if (measureCount == 1) {
return formatMeasure(measures[0], **numberFormat, appendTo, pos, status);
}
if (fWidth == UMEASFMT_WIDTH_NUMERIC) {
Formattable hms[3];
int32_t bitMap = toHMS(measures, measureCount, hms, status);
if (bitMap > 0) {
return formatNumeric(hms, bitMap, appendTo, status);
}
}
if (pos.getField() != FieldPosition::DONT_CARE) {
return formatMeasuresSlowTrack(
measures, measureCount, appendTo, pos, status);
}
UnicodeString *results = new UnicodeString[measureCount];
if (results == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return appendTo;
}
for (int32_t i = 0; i < measureCount; ++i) {
const NumberFormat *nf = cache->getIntegerFormat();
if (i == measureCount - 1) {
nf = numberFormat->get();
}
formatMeasure(
measures[i],
*nf,
results[i],
pos,
status);
}
listFormatter->format(results, measureCount, appendTo, status);
delete [] results;
return appendTo;
}
#if APPLE_ICU_CHANGES
// rdar:/
// Apple-specific version for now;
// uses FieldPositionIterator* instead of FieldPosition&
UnicodeString &MeasureFormat::formatMeasures(
const Measure *measures,
int32_t measureCount,
UnicodeString &appendTo,
FieldPositionIterator* posIter,
UErrorCode &status) const {
if (U_FAILURE(status)) {
return appendTo;
}
FieldPositionIteratorHandler handler(posIter, status);
if (measureCount == 0) {
return appendTo;
}
if (measureCount == 1) {
int32_t start = appendTo.length();
int32_t field = measures[0].getUnit().getUAMeasureUnit();
FieldPosition pos(UAMEASFMT_NUMERIC_FIELD_FLAG); // special field value to request range of entire numeric part
formatMeasure(measures[0], **numberFormat, appendTo, pos, status);
handler.addAttribute(field, start, appendTo.length());
handler.addAttribute(field | UAMEASFMT_NUMERIC_FIELD_FLAG, pos.getBeginIndex(), pos.getEndIndex());
return appendTo;
}
if (fWidth == UMEASFMT_WIDTH_NUMERIC) {
Formattable hms[3];
int32_t bitMap = toHMS(measures, measureCount, hms, status);
if (bitMap > 0) {
return formatNumeric(hms, bitMap, appendTo, status);
}
}
UnicodeString *results = new UnicodeString[measureCount];
if (results == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
return appendTo;
}
FieldPosition *numPositions = new FieldPosition[measureCount];
if (results == NULL) {
delete [] results;
status = U_MEMORY_ALLOCATION_ERROR;
return appendTo;
}
for (int32_t i = 0; i < measureCount; ++i) {
const NumberFormat *nf = cache->getIntegerFormat();
if (i == measureCount - 1) {
nf = numberFormat->get();
}
numPositions[i].setField(UAMEASFMT_NUMERIC_FIELD_FLAG);
formatMeasure(
measures[i],
*nf,
results[i],
numPositions[i],
status);
}
listFormatter->format(results, measureCount, appendTo, status);
for (int32_t i = 0; i < measureCount; ++i) {
int32_t begin = appendTo.indexOf(results[i]);
if (begin >= 0) {
int32_t field = measures[i].getUnit().getUAMeasureUnit();
handler.addAttribute(field, begin, begin + results[i].length());
int32_t numPosBegin = numPositions[i].getBeginIndex();
int32_t numPosEnd = numPositions[i].getEndIndex();
if (numPosBegin >= 0 && numPosEnd > numPosBegin) {
handler.addAttribute(field | UAMEASFMT_NUMERIC_FIELD_FLAG, begin + numPosBegin, begin + numPosEnd);
}
}
}
delete [] results;
delete [] numPositions;
return appendTo;
}
#endif // APPLE_ICU_CHANGES
UnicodeString MeasureFormat::getUnitDisplayName(const MeasureUnit& unit, UErrorCode& status) const {
return number::impl::LongNameHandler::getUnitDisplayName(
getLocale(status),
unit,
getUnitWidth(fWidth),
status);
}
void MeasureFormat::initMeasureFormat(
const Locale &locale,
UMeasureFormatWidth w,
NumberFormat *nfToAdopt,
UErrorCode &status) {
static const UListFormatterWidth listWidths[] = {
ULISTFMT_WIDTH_WIDE,
ULISTFMT_WIDTH_SHORT,
ULISTFMT_WIDTH_NARROW};
LocalPointer<NumberFormat> nf(nfToAdopt);
if (U_FAILURE(status)) {
return;
}
const char *name = locale.getName();
setLocaleIDs(name, name);
UnifiedCache::getByLocale(locale, cache, status);
if (U_FAILURE(status)) {
return;
}
const SharedPluralRules *pr = PluralRules::createSharedInstance(
locale, UPLURAL_TYPE_CARDINAL, status);
if (U_FAILURE(status)) {
return;
}
SharedObject::copyPtr(pr, pluralRules);
pr->removeRef();
if (nf.isNull()) {
// TODO: Clean this up
const SharedNumberFormat *shared = NumberFormat::createSharedInstance(
locale, UNUM_DECIMAL, status);
if (U_FAILURE(status)) {
return;
}
SharedObject::copyPtr(shared, numberFormat);
shared->removeRef();
} else {
adoptNumberFormat(nf.orphan(), status);
if (U_FAILURE(status)) {
return;
}
}
fWidth = w;
#if APPLE_ICU_CHANGES
// rdar:/
if (stripPatternSpaces) {
w = UMEASFMT_WIDTH_NARROW;
}
#endif // APPLE_ICU_CHANGES
delete listFormatter;
listFormatter = ListFormatter::createInstance(
locale,
ULISTFMT_TYPE_UNITS,
#if APPLE_ICU_CHANGES
// rdar:/
listWidths[getRegularWidth(w)],
#else
listWidths[getRegularWidth(fWidth)],
#endif // APPLE_ICU_CHANGES
status);
#if APPLE_ICU_CHANGES
// rdar:/
delete listFormatterStd;
listFormatterStd = ListFormatter::createInstance(
locale,
ULISTFMT_TYPE_AND,
ULISTFMT_WIDTH_WIDE,
status);
#endif // APPLE_ICU_CHANGES
}
void MeasureFormat::adoptNumberFormat(
NumberFormat *nfToAdopt, UErrorCode &status) {
LocalPointer<NumberFormat> nf(nfToAdopt);
if (U_FAILURE(status)) {
return;
}
SharedNumberFormat *shared = new SharedNumberFormat(nf.getAlias());
if (shared == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
nf.orphan();
SharedObject::copyPtr(shared, numberFormat);
}
UBool MeasureFormat::setMeasureFormatLocale(const Locale &locale, UErrorCode &status) {
if (U_FAILURE(status) || locale == getLocale(status)) {
return false;
}
initMeasureFormat(locale, fWidth, nullptr, status);
return U_SUCCESS(status);
}
#if APPLE_ICU_CHANGES
// rdar:/
// Apple-specific for now
UMeasureFormatWidth MeasureFormat::getWidth() const {
return fWidth;
}
#endif // APPLE_ICU_CHANGES
const NumberFormat &MeasureFormat::getNumberFormatInternal() const {
return **numberFormat;
}
const NumberFormat &MeasureFormat::getCurrencyFormatInternal() const {
return *cache->getCurrencyFormat(UMEASFMT_WIDTH_NARROW);
}
const PluralRules &MeasureFormat::getPluralRules() const {
return **pluralRules;
}
Locale MeasureFormat::getLocale(UErrorCode &status) const {
return Format::getLocale(ULOC_VALID_LOCALE, status);
}
const char *MeasureFormat::getLocaleID(UErrorCode &status) const {
return Format::getLocaleID(ULOC_VALID_LOCALE, status);
}
#if APPLE_ICU_CHANGES
// rdar:/
// Apple=specific
// now just re-implement using standard getUnitDisplayName
// so we no longer use cache->getDisplayName
UnicodeString &MeasureFormat::getUnitName(
const MeasureUnit* unit,
UnicodeString &result ) const {
UErrorCode status = U_ZERO_ERROR;
result = getUnitDisplayName(*unit, status); // does not use or set status
return result;
}
// Apple=specific
UnicodeString &MeasureFormat::getMultipleUnitNames(
const MeasureUnit** units,
int32_t unitCount,
UAMeasureNameListStyle listStyle,
UnicodeString &result ) const {
if (unitCount == 0) {
return result.remove();
}
if (unitCount == 1) {
return getUnitName(units[0], result);
}
UnicodeString *results = new UnicodeString[unitCount];
if (results != NULL) {
for (int32_t i = 0; i < unitCount; ++i) {
getUnitName(units[i], results[i]);
}
UErrorCode status = U_ZERO_ERROR;
if (listStyle == UAMEASNAME_LIST_STANDARD) {
listFormatterStd->format(results, unitCount, result, status);
} else {
listFormatter->format(results, unitCount, result, status);
}
delete [] results;
if (U_SUCCESS(status)) {
return result;
}
}
result.setToBogus();
return result;
}
#endif // APPLE_ICU_CHANGES
UnicodeString &MeasureFormat::formatMeasure(
const Measure &measure,
const NumberFormat &nf,
UnicodeString &appendTo,
FieldPosition &pos,
UErrorCode &status) const {
if (U_FAILURE(status)) {
return appendTo;
}
const Formattable& amtNumber = measure.getNumber();
const MeasureUnit& amtUnit = measure.getUnit();
if (isCurrency(amtUnit)) {
char16_t isoCode[4];
u_charsToUChars(amtUnit.getSubtype(), isoCode, 4);
return cache->getCurrencyFormat(fWidth)->format(
new CurrencyAmount(amtNumber, isoCode, status),
appendTo,
pos,
status);
}
#if APPLE_ICU_CHANGES
// rdar:/
int32_t cur = appendTo.length();
UBool posForFullNumericPart = (pos.getField() == UAMEASFMT_NUMERIC_FIELD_FLAG);
if (posForFullNumericPart) {
pos.setField(FieldPosition::DONT_CARE);
}
#endif // APPLE_ICU_CHANGES
auto* df = dynamic_cast<const DecimalFormat*>(&nf);
if (df == nullptr) {
// Handle other types of NumberFormat using the ICU 63 code, modified to
// get the unitPattern from LongNameHandler and handle fallback to OTHER.
UnicodeString formattedNumber;
StandardPlural::Form pluralForm = QuantityFormatter::selectPlural(
amtNumber, nf, **pluralRules, formattedNumber, pos, status);
#if APPLE_ICU_CHANGES
// rdar:/
if (posForFullNumericPart) {
pos.setField(UAMEASFMT_NUMERIC_FIELD_FLAG);
pos.setBeginIndex(0);
pos.setEndIndex(formattedNumber.length());
}
#endif // APPLE_ICU_CHANGES
UnicodeString pattern = number::impl::LongNameHandler::getUnitPattern(getLocale(status),
amtUnit, getUnitWidth(fWidth), pluralForm, status);
// The above handles fallback from other widths to short, and from other plural forms to OTHER
if (U_FAILURE(status)) {
return appendTo;
}
SimpleFormatter formatter(pattern, 0, 1, status);
#if APPLE_ICU_CHANGES
// rdar:/
QuantityFormatter::format(formatter, formattedNumber, appendTo, pos, status);
} else {
// This is the current code
UFormattedNumberData result;
if (auto* lnf = df->toNumberFormatter(status)) {
result.quantity.setToDouble(amtNumber.getDouble(status));
lnf->unit(amtUnit)
.unitWidth(getUnitWidth(fWidth))
.formatImpl(&result, status);
}
DecimalFormat::fieldPositionHelper(result, pos, appendTo.length(), status);
if (posForFullNumericPart) {
pos.setField(UNUM_INTEGER_FIELD);
DecimalFormat::fieldPositionHelper(result, pos, appendTo.length(), status);
int32_t intBegin = pos.getBeginIndex();
int32_t intEnd = pos.getEndIndex();
pos.setField(UNUM_FRACTION_FIELD);
DecimalFormat::fieldPositionHelper(result, pos, appendTo.length(), status);
int32_t fracBegin = pos.getBeginIndex();
int32_t fracEnd = pos.getEndIndex();
if (intBegin >= 0 && intEnd > intBegin) {
// we have an integer part
pos.setBeginIndex(intBegin);
if (fracBegin >= intEnd && fracEnd > fracBegin) {
// we have a fraction part, include it too
pos.setEndIndex(fracEnd);
} else {
pos.setEndIndex(intEnd);
}
} else if (fracBegin >= 0 && fracEnd > fracBegin) {
// only a fract part, use it
pos.setBeginIndex(fracBegin);
pos.setEndIndex(fracEnd);
} else {
// no numeric part
pos.setBeginIndex(0);
pos.setEndIndex(0);
}
pos.setField(UAMEASFMT_NUMERIC_FIELD_FLAG);
}
appendTo.append(result.toTempString(status));
}
if (stripPatternSpaces) {
// Get the narrow pattern for OTHER.
// If there are spaces in that, then do not continue to strip spaces
// (i.e. even in the narrowest form this locale keeps spaces).
UnicodeString narrowPattern = number::impl::LongNameHandler::getUnitPattern(getLocale(status),
amtUnit, UNUM_UNIT_WIDTH_NARROW, StandardPlural::Form::OTHER, status);
if (U_SUCCESS(status)) {
if (narrowPattern.indexOf((UChar)0x0020) == -1 && narrowPattern.indexOf((UChar)0x00A0) == -1 && narrowPattern.indexOf((UChar)0x202F) == -1) {
int32_t end = appendTo.length();
for (; cur < end; cur++) {
if (appendTo.charAt(cur) == 0x0020) {
appendTo.remove(cur, 1);
if (pos.getBeginIndex() > cur) {
pos.setBeginIndex(pos.getBeginIndex() - 1);
pos.setEndIndex(pos.getEndIndex() - 1);
}
}
}
}
}
}
#else
return QuantityFormatter::format(formatter, formattedNumber, appendTo, pos, status);
}
UFormattedNumberData result;
if (auto* lnf = df->toNumberFormatter(status)) {
result.quantity.setToDouble(amtNumber.getDouble(status));
lnf->unit(amtUnit)
.unitWidth(getUnitWidth(fWidth))
.formatImpl(&result, status);
}
DecimalFormat::fieldPositionHelper(result, pos, appendTo.length(), status);
appendTo.append(result.toTempString(status));
#endif // APPLE_ICU_CHANGES
return appendTo;
}
// Formats numeric time duration as 5:00:47 or 3:54.
UnicodeString &MeasureFormat::formatNumeric(
const Formattable *hms, // always length 3
int32_t bitMap, // 1=hour set, 2=minute set, 4=second set
UnicodeString &appendTo,
UErrorCode &status) const {
if (U_FAILURE(status)) {
return appendTo;
}
UnicodeString pattern;
double hours = hms[0].getDouble(status);
double minutes = hms[1].getDouble(status);
double seconds = hms[2].getDouble(status);
if (U_FAILURE(status)) {
return appendTo;
}
// All possible combinations: "h", "m", "s", "hm", "hs", "ms", "hms"
if (bitMap == 5 || bitMap == 7) { // "hms" & "hs" (we add minutes if "hs")
pattern = cache->getNumericDateFormatters()->hourMinuteSecond;
hours = uprv_trunc(hours);
minutes = uprv_trunc(minutes);
} else if (bitMap == 3) { // "hm"
pattern = cache->getNumericDateFormatters()->hourMinute;
hours = uprv_trunc(hours);
} else if (bitMap == 6) { // "ms"
pattern = cache->getNumericDateFormatters()->minuteSecond;
minutes = uprv_trunc(minutes);
} else { // h m s, handled outside formatNumeric. No value is also an error.
status = U_INTERNAL_PROGRAM_ERROR;
return appendTo;
}
const DecimalFormat *numberFormatter = dynamic_cast<const DecimalFormat*>(numberFormat->get());
if (!numberFormatter) {
status = U_INTERNAL_PROGRAM_ERROR;
return appendTo;
}
number::LocalizedNumberFormatter numberFormatter2;
if (auto* lnf = numberFormatter->toNumberFormatter(status)) {
numberFormatter2 = lnf->integerWidth(number::IntegerWidth::zeroFillTo(2));
} else {
return appendTo;
}
#if APPLE_ICU_CHANGES
// rdar:/
LocalPointer<DecimalFormat> intFmtClone;
const DecimalFormat *intFmt = dynamic_cast<const DecimalFormat*>(cache->getIntegerFormat());
if (intFmt) {
intFmtClone.adoptInstead((DecimalFormat *)intFmt->clone());
}
if (intFmtClone.isNull()) {
status = U_INTERNAL_PROGRAM_ERROR;
return appendTo;
}
#endif // APPLE_ICU_CHANGES
FormattedStringBuilder fsb;
UBool protect = false;
const int32_t patternLength = pattern.length();
for (int32_t i = 0; i < patternLength; i++) {
char16_t c = pattern[i];
// Also set the proper field in this switch
// We don't use DateFormat.Field because this is not a date / time, is a duration.
double value = 0;
switch (c) {
case u'H': value = hours; break;
case u'm': value = minutes; break;
case u's': value = seconds; break;
}
// There is not enough info to add Field(s) for the unit because all we have are plain
// text patterns. For example in "21:51" there is no text for something like "hour",
// while in something like "21h51" there is ("h"). But we can't really tell...
switch (c) {
case u'H':
case u'm':
case u's':
if (protect) {
fsb.appendChar16(c, kUndefinedField, status);
} else {
UnicodeString tmp;
#if APPLE_ICU_CHANGES
// rdar:/
UBool lastNumField = ((c == u's') || (c == u'm' && bitMap == 3));
#endif // APPLE_ICU_CHANGES
if ((i + 1 < patternLength) && pattern[i + 1] == c) { // doubled
#if APPLE_ICU_CHANGES
// rdar:/
if (!lastNumField) {
intFmtClone->setMinimumIntegerDigits(2);
intFmtClone->format(value, tmp, status);
} else {
tmp = numberFormatter2.formatDouble(value, status).toString(status);
}
#else
tmp = numberFormatter2.formatDouble(value, status).toString(status);
#endif // APPLE_ICU_CHANGES
i++;
} else {
#if APPLE_ICU_CHANGES
// rdar:/
if (!lastNumField) {
intFmtClone->setMinimumIntegerDigits(1);
intFmtClone->format(value, tmp, status);
} else {
numberFormatter->format(value, tmp, status);
}
#else
numberFormatter->format(value, tmp, status);
#endif // APPLE_ICU_CHANGES
}
// TODO: Use proper Field
fsb.append(tmp, kUndefinedField, status);
}
break;
case u'\'':
// '' is escaped apostrophe
if ((i + 1 < patternLength) && pattern[i + 1] == c) {
fsb.appendChar16(c, kUndefinedField, status);
i++;
} else {
protect = !protect;
}
break;
default:
fsb.appendChar16(c, kUndefinedField, status);
}
}
appendTo.append(fsb.toTempUnicodeString());
return appendTo;
}
UnicodeString &MeasureFormat::formatMeasuresSlowTrack(
const Measure *measures,
int32_t measureCount,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& status) const {
if (U_FAILURE(status)) {
return appendTo;
}
FieldPosition dontCare(FieldPosition::DONT_CARE);
FieldPosition fpos(pos.getField());
LocalArray<UnicodeString> results(new UnicodeString[measureCount], status);
int32_t fieldPositionFoundIndex = -1;
for (int32_t i = 0; i < measureCount; ++i) {
const NumberFormat *nf = cache->getIntegerFormat();
if (i == measureCount - 1) {
nf = numberFormat->get();
}
if (fieldPositionFoundIndex == -1) {
formatMeasure(measures[i], *nf, results[i], fpos, status);
if (U_FAILURE(status)) {
return appendTo;
}
if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
fieldPositionFoundIndex = i;
}
} else {
formatMeasure(measures[i], *nf, results[i], dontCare, status);
}
}
int32_t offset;
listFormatter->format(
results.getAlias(),
measureCount,
appendTo,
fieldPositionFoundIndex,
offset,
status);
if (U_FAILURE(status)) {
return appendTo;
}
// Fix up FieldPosition indexes if our field is found.
if (fieldPositionFoundIndex != -1 && offset != -1) {
pos.setBeginIndex(fpos.getBeginIndex() + offset);
pos.setEndIndex(fpos.getEndIndex() + offset);
}
return appendTo;
}
MeasureFormat* U_EXPORT2 MeasureFormat::createCurrencyFormat(const Locale& locale,
UErrorCode& ec) {
if (U_FAILURE(ec)) {
return nullptr;
}
LocalPointer<CurrencyFormat> fmt(new CurrencyFormat(locale, ec), ec);
return fmt.orphan();
}
MeasureFormat* U_EXPORT2 MeasureFormat::createCurrencyFormat(UErrorCode& ec) {
if (U_FAILURE(ec)) {
return nullptr;
}
return MeasureFormat::createCurrencyFormat(Locale::getDefault(), ec);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
|