#include "utypeinfo.h" // for 'typeid' to work
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/measfmt.h"
#include "unicode/numfmt.h"
#include "currfmt.h"
#include "unicode/localpointer.h"
#include "resource.h"
#include "unicode/simpleformatter.h"
#include "quantityformatter.h"
#include "unicode/plurrule.h"
#include "unicode/decimfmt.h"
#include "uresimp.h"
#include "unicode/ures.h"
#include "unicode/ustring.h"
#include "ureslocs.h"
#include "cstring.h"
#include "mutex.h"
#include "ucln_in.h"
#include "unicode/listformatter.h"
#include "charstr.h"
#include "unicode/putil.h"
#include "unicode/smpdtfmt.h"
#include "uassert.h"
#include "unicode/numberformatter.h"
#include "number_longnames.h"
#include "unicode/uameasureformat.h"
#include "fphdlimp.h"
#include "sharednumberformat.h"
#include "sharedpluralrules.h"
#include "standardplural.h"
#include "unifiedcache.h"
U_NAMESPACE_BEGIN
static constexpr int32_t WIDTH_INDEX_COUNT = UMEASFMT_WIDTH_NARROW + 1;
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(MeasureFormat)
class NumericDateFormatters : public UMemory {
public:
SimpleDateFormat hourMinute;
SimpleDateFormat minuteSecond;
SimpleDateFormat hourMinuteSecond;
NumericDateFormatters(
const UnicodeString &hm,
const UnicodeString &ms,
const UnicodeString &hms,
UErrorCode &status) :
hourMinute(hm, status),
minuteSecond(ms, status),
hourMinuteSecond(hms, status) {
const TimeZone *gmt = TimeZone::getGMT();
hourMinute.setTimeZone(*gmt);
minuteSecond.setTimeZone(*gmt);
hourMinuteSecond.setTimeZone(*gmt);
}
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;
}
}
class MeasureFormatCacheData : public SharedObject {
public:
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];
}
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 UChar *resStr = ures_getString(resource, &len, &status);
if (U_FAILURE(status)) {
return FALSE;
}
result.setTo(TRUE, resStr, len);
return TRUE;
}
static const UAMeasureUnit indexToUAMsasUnit[] = {
UAMEASUNIT_ACCELERATION_G_FORCE, UAMEASUNIT_ACCELERATION_METER_PER_SECOND_SQUARED, UAMEASUNIT_ANGLE_ARC_MINUTE, UAMEASUNIT_ANGLE_ARC_SECOND, UAMEASUNIT_ANGLE_DEGREE, UAMEASUNIT_ANGLE_RADIAN, UAMEASUNIT_ANGLE_REVOLUTION, UAMEASUNIT_AREA_ACRE, UAMEASUNIT_AREA_DUNAM, UAMEASUNIT_AREA_HECTARE, UAMEASUNIT_AREA_SQUARE_CENTIMETER, UAMEASUNIT_AREA_SQUARE_FOOT, UAMEASUNIT_AREA_SQUARE_INCH, UAMEASUNIT_AREA_SQUARE_KILOMETER, UAMEASUNIT_AREA_SQUARE_METER, UAMEASUNIT_AREA_SQUARE_MILE, UAMEASUNIT_AREA_SQUARE_YARD, UAMEASUNIT_CONCENTRATION_KARAT, UAMEASUNIT_CONCENTRATION_MILLIGRAM_PER_DECILITER, UAMEASUNIT_CONCENTRATION_MILLIMOLE_PER_LITER, UAMEASUNIT_CONCENTRATION_MOLE, UAMEASUNIT_CONCENTRATION_PART_PER_MILLION, UAMEASUNIT_CONCENTRATION_PERCENT, UAMEASUNIT_CONCENTRATION_PERMILLE, UAMEASUNIT_CONCENTRATION_PERMYRIAD, UAMEASUNIT_CONSUMPTION_LITER_PER_100_KILOMETERs, UAMEASUNIT_CONSUMPTION_LITER_PER_KILOMETER, UAMEASUNIT_CONSUMPTION_MILE_PER_GALLON, UAMEASUNIT_CONSUMPTION_MILE_PER_GALLON_IMPERIAL, UAMEASUNIT_DIGITAL_BIT, UAMEASUNIT_DIGITAL_BYTE, UAMEASUNIT_DIGITAL_GIGABIT, UAMEASUNIT_DIGITAL_GIGABYTE, UAMEASUNIT_DIGITAL_KILOBIT, UAMEASUNIT_DIGITAL_KILOBYTE, UAMEASUNIT_DIGITAL_MEGABIT, UAMEASUNIT_DIGITAL_MEGABYTE, UAMEASUNIT_DIGITAL_PETABYTE, UAMEASUNIT_DIGITAL_TERABIT, UAMEASUNIT_DIGITAL_TERABYTE, UAMEASUNIT_DURATION_CENTURY, UAMEASUNIT_DURATION_DAY, UAMEASUNIT_DURATION_DAY_PERSON, UAMEASUNIT_DURATION_HOUR, UAMEASUNIT_DURATION_MICROSECOND, UAMEASUNIT_DURATION_MILLISECOND, UAMEASUNIT_DURATION_MINUTE, UAMEASUNIT_DURATION_MONTH, UAMEASUNIT_DURATION_MONTH_PERSON, UAMEASUNIT_DURATION_NANOSECOND, UAMEASUNIT_DURATION_SECOND, UAMEASUNIT_DURATION_WEEK, UAMEASUNIT_DURATION_WEEK_PERSON, UAMEASUNIT_DURATION_YEAR, UAMEASUNIT_DURATION_YEAR_PERSON, UAMEASUNIT_ELECTRIC_AMPERE, UAMEASUNIT_ELECTRIC_MILLIAMPERE, UAMEASUNIT_ELECTRIC_OHM, UAMEASUNIT_ELECTRIC_VOLT, UAMEASUNIT_ENERGY_BRITISH_THERMAL_UNIT, UAMEASUNIT_ENERGY_CALORIE, UAMEASUNIT_ENERGY_ELECTRONVOLT, UAMEASUNIT_ENERGY_FOODCALORIE, UAMEASUNIT_ENERGY_JOULE, UAMEASUNIT_ENERGY_KILOCALORIE, UAMEASUNIT_ENERGY_KILOJOULE, UAMEASUNIT_ENERGY_KILOWATT_HOUR, UAMEASUNIT_FORCE_NEWTON, UAMEASUNIT_FORCE_POUND_FORCE, UAMEASUNIT_FREQUENCY_GIGAHERTZ, UAMEASUNIT_FREQUENCY_HERTZ, UAMEASUNIT_FREQUENCY_KILOHERTZ, UAMEASUNIT_FREQUENCY_MEGAHERTZ, UAMEASUNIT_LENGTH_ASTRONOMICAL_UNIT, UAMEASUNIT_LENGTH_CENTIMETER, UAMEASUNIT_LENGTH_DECIMETER, UAMEASUNIT_LENGTH_FATHOM, UAMEASUNIT_LENGTH_FOOT, UAMEASUNIT_LENGTH_FURLONG, UAMEASUNIT_LENGTH_INCH, UAMEASUNIT_LENGTH_KILOMETER, UAMEASUNIT_LENGTH_LIGHT_YEAR, UAMEASUNIT_LENGTH_METER, UAMEASUNIT_LENGTH_MICROMETER, UAMEASUNIT_LENGTH_MILE, UAMEASUNIT_LENGTH_MILE_SCANDINAVIAN, UAMEASUNIT_LENGTH_MILLIMETER, UAMEASUNIT_LENGTH_NANOMETER, UAMEASUNIT_LENGTH_NAUTICAL_MILE, UAMEASUNIT_LENGTH_PARSEC, UAMEASUNIT_LENGTH_PICOMETER, UAMEASUNIT_LENGTH_POINT, UAMEASUNIT_LENGTH_SOLAR_RADIUS, UAMEASUNIT_LENGTH_YARD, UAMEASUNIT_LIGHT_LUX, UAMEASUNIT_LIGHT_SOLAR_LUMINOSITY, UAMEASUNIT_MASS_CARAT, UAMEASUNIT_MASS_DALTON, UAMEASUNIT_MASS_EARTH_MASS, UAMEASUNIT_MASS_GRAM, UAMEASUNIT_MASS_KILOGRAM, UAMEASUNIT_MASS_METRIC_TON, UAMEASUNIT_MASS_MICROGRAM, UAMEASUNIT_MASS_MILLIGRAM, UAMEASUNIT_MASS_OUNCE, UAMEASUNIT_MASS_OUNCE_TROY, UAMEASUNIT_MASS_POUND, UAMEASUNIT_MASS_SOLAR_MASS, UAMEASUNIT_MASS_STONE, UAMEASUNIT_MASS_TON, UAMEASUNIT_CONCENTRATION_PERCENT, UAMEASUNIT_CONCENTRATION_PERCENT, UAMEASUNIT_CONCENTRATION_PERMILLE, UAMEASUNIT_POWER_GIGAWATT, UAMEASUNIT_POWER_HORSEPOWER, UAMEASUNIT_POWER_KILOWATT, UAMEASUNIT_POWER_MEGAWATT, UAMEASUNIT_POWER_MILLIWATT, UAMEASUNIT_POWER_WATT, UAMEASUNIT_PRESSURE_ATMOSPHERE, UAMEASUNIT_PRESSURE_HECTOPASCAL, UAMEASUNIT_PRESSURE_INCH_HG, UAMEASUNIT_PRESSURE_KILOPASCAL, UAMEASUNIT_PRESSURE_MEGAPASCAL, UAMEASUNIT_PRESSURE_MILLIBAR, UAMEASUNIT_PRESSURE_MILLIMETER_OF_MERCURY, UAMEASUNIT_PRESSURE_POUND_PER_SQUARE_INCH, UAMEASUNIT_SPEED_KILOMETER_PER_HOUR, UAMEASUNIT_SPEED_KNOT, UAMEASUNIT_SPEED_METER_PER_SECOND, UAMEASUNIT_SPEED_MILE_PER_HOUR, UAMEASUNIT_TEMPERATURE_CELSIUS, UAMEASUNIT_TEMPERATURE_FAHRENHEIT, UAMEASUNIT_TEMPERATURE_GENERIC, UAMEASUNIT_TEMPERATURE_KELVIN, UAMEASUNIT_TORQUE_NEWTON_METER, UAMEASUNIT_TORQUE_POUND_FOOT, UAMEASUNIT_VOLUME_ACRE_FOOT, UAMEASUNIT_VOLUME_BARREL, UAMEASUNIT_VOLUME_BUSHEL, UAMEASUNIT_VOLUME_CENTILITER, UAMEASUNIT_VOLUME_CUBIC_CENTIMETER, UAMEASUNIT_VOLUME_CUBIC_FOOT, UAMEASUNIT_VOLUME_CUBIC_INCH, UAMEASUNIT_VOLUME_CUBIC_KILOMETER, UAMEASUNIT_VOLUME_CUBIC_METER, UAMEASUNIT_VOLUME_CUBIC_MILE, UAMEASUNIT_VOLUME_CUBIC_YARD, UAMEASUNIT_VOLUME_CUP, UAMEASUNIT_VOLUME_CUP_METRIC, UAMEASUNIT_VOLUME_DECILITER, UAMEASUNIT_VOLUME_FLUID_OUNCE, UAMEASUNIT_VOLUME_FLUID_OUNCE_IMPERIAL, UAMEASUNIT_VOLUME_GALLON, UAMEASUNIT_VOLUME_GALLON_IMPERIAL, UAMEASUNIT_VOLUME_HECTOLITER, UAMEASUNIT_VOLUME_LITER, UAMEASUNIT_VOLUME_MEGALITER, UAMEASUNIT_VOLUME_MILLILITER, UAMEASUNIT_VOLUME_PINT, UAMEASUNIT_VOLUME_PINT_METRIC, UAMEASUNIT_VOLUME_QUART, UAMEASUNIT_VOLUME_TABLESPOON, UAMEASUNIT_VOLUME_TEASPOON, };
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(),
NULL,
&status));
if (U_FAILURE(status)) {
return result;
}
getString(patternBundle.getAlias(), result, status);
int32_t len = result.length();
UChar *buffer = result.getBuffer(len);
for (int32_t i = 0; i < len; ++i) {
if (buffer[i] == 0x68) { buffer[i] = 0x48; }
}
result.releaseBuffer(len);
return result;
}
static NumericDateFormatters *loadNumericDateFormatters(
const UResourceBundle *resource,
UErrorCode &status) {
if (U_FAILURE(status)) {
return NULL;
}
NumericDateFormatters *result = new NumericDateFormatters(
loadNumericDateFormatterPattern(resource, "hm", status),
loadNumericDateFormatterPattern(resource, "ms", status),
loadNumericDateFormatterPattern(resource, "hms", status),
status);
if (U_FAILURE(status)) {
delete result;
return NULL;
}
return result;
}
template<> U_I18N_API
const MeasureFormatCacheData *LocaleCacheKey<MeasureFormatCacheData>::createObject(
const void * , 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 NULL;
}
result->adoptNumericDateFormatters(loadNumericDateFormatters(
unitsBundle.getAlias(), status));
if (U_FAILURE(status)) {
return NULL;
}
for (int32_t i = 0; i < WIDTH_INDEX_COUNT; ++i) {
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 NULL;
}
}
NumberFormat *inf = NumberFormat::createInstance(
localeId, UNUM_DECIMAL, status);
if (U_FAILURE(status)) {
return NULL;
}
inf->setMaximumFractionDigits(0);
DecimalFormat *decfmt = dynamic_cast<DecimalFormat *>(inf);
if (decfmt != NULL) {
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;
}
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;
}
for (int32_t i = 0; i < measureCount; ++i) {
if (isTimeUnit(measures[i].getUnit(), "hour")) {
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")) {
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")) {
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(NULL),
numberFormat(NULL),
pluralRules(NULL),
fWidth((w==UMEASFMT_WIDTH_SHORTER)? UMEASFMT_WIDTH_SHORT: w),
stripPatternSpaces(w==UMEASFMT_WIDTH_SHORTER),
listFormatter(NULL),
listFormatterStd(NULL) {
initMeasureFormat(locale, (w==UMEASFMT_WIDTH_SHORTER)? UMEASFMT_WIDTH_SHORT: w, NULL, status);
}
MeasureFormat::MeasureFormat(
const Locale &locale,
UMeasureFormatWidth w,
NumberFormat *nfToAdopt,
UErrorCode &status)
: cache(NULL),
numberFormat(NULL),
pluralRules(NULL),
fWidth((w==UMEASFMT_WIDTH_SHORTER)? UMEASFMT_WIDTH_SHORT: w),
stripPatternSpaces(w==UMEASFMT_WIDTH_SHORTER),
listFormatter(NULL),
listFormatterStd(NULL) {
initMeasureFormat(locale, (w==UMEASFMT_WIDTH_SHORTER)? UMEASFMT_WIDTH_SHORT: w, nfToAdopt, status);
}
MeasureFormat::MeasureFormat(const MeasureFormat &other) :
Format(other),
cache(other.cache),
numberFormat(other.numberFormat),
pluralRules(other.pluralRules),
fWidth(other.fWidth),
stripPatternSpaces(other.stripPatternSpaces),
listFormatter(NULL),
listFormatterStd(NULL) {
cache->addRef();
numberFormat->addRef();
pluralRules->addRef();
if (other.listFormatter != NULL) {
listFormatter = new ListFormatter(*other.listFormatter);
}
if (other.listFormatterStd != NULL) {
listFormatterStd = new ListFormatter(*other.listFormatterStd);
}
}
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;
stripPatternSpaces = other.stripPatternSpaces;
delete listFormatter;
if (other.listFormatter != NULL) {
listFormatter = new ListFormatter(*other.listFormatter);
} else {
listFormatter = NULL;
}
delete listFormatterStd;
if (other.listFormatterStd != NULL) {
listFormatterStd = new ListFormatter(*other.listFormatterStd);
} else {
listFormatterStd = NULL;
}
return *this;
}
MeasureFormat::MeasureFormat() :
cache(NULL),
numberFormat(NULL),
pluralRules(NULL),
fWidth(UMEASFMT_WIDTH_SHORT),
stripPatternSpaces(FALSE),
listFormatter(NULL),
listFormatterStd(NULL) {
}
MeasureFormat::~MeasureFormat() {
if (cache != NULL) {
cache->removeRef();
}
if (numberFormat != NULL) {
numberFormat->removeRef();
}
if (pluralRules != NULL) {
pluralRules->removeRef();
}
delete listFormatter;
delete listFormatterStd;
}
UBool MeasureFormat::operator==(const Format &other) const {
if (this == &other) { return TRUE;
}
if (!Format::operator==(other)) {
return FALSE;
}
const MeasureFormat &rhs = static_cast<const MeasureFormat &>(other);
if (fWidth != rhs.fWidth || stripPatternSpaces != rhs.stripPatternSpaces) {
return FALSE;
}
if (cache != rhs.cache) {
UErrorCode status = U_ZERO_ERROR;
const char *localeId = getLocaleID(status);
const char *rhsLocaleId = rhs.getLocaleID(status);
if (U_FAILURE(status)) {
return FALSE;
}
if (uprv_strcmp(localeId, rhsLocaleId) != 0) {
return FALSE;
}
}
return (
numberFormat == rhs.numberFormat ||
**numberFormat == **rhs.numberFormat);
}
Format *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 != NULL) {
return formatMeasure(
*amount, **numberFormat, appendTo, pos, status);
}
}
status = U_ILLEGAL_ARGUMENT_ERROR;
return appendTo;
}
void MeasureFormat::parseObject(
const UnicodeString & ,
Formattable & ,
ParsePosition& ) 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) {
status = U_UNSUPPORTED_ERROR;
return appendTo;
}
number::FormattedNumber result;
if (auto* lnf = df->toNumberFormatter(status)) {
result = lnf->unit(measure.getUnit())
.perUnit(perUnit)
.unitWidth(getUnitWidth(fWidth))
.formatDouble(measure.getNumber().getDouble(status), 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) {
FieldPositionIteratorHandler handler((FieldPositionIterator*)NULL, status);
return formatNumeric(hms, bitMap, appendTo, handler, status);
}
}
if (pos.getField() != FieldPosition::DONT_CARE) {
return formatMeasuresSlowTrack(
measures, measureCount, appendTo, pos, status);
}
UnicodeString *results = new UnicodeString[measureCount];
if (results == NULL) {
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;
}
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 = indexToUAMsasUnit[measures[0].getUnit().getIndex()];
FieldPosition pos(UAMEASFMT_NUMERIC_FIELD_FLAG); 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, handler, 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 = indexToUAMsasUnit[measures[i].getUnit().getIndex()];
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;
}
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 char *listStyles[] = {"unit", "unit-short", "unit-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()) {
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 (stripPatternSpaces) {
w = UMEASFMT_WIDTH_NARROW;
}
delete listFormatter;
listFormatter = ListFormatter::createInstance(
locale,
listStyles[getRegularWidth(w)],
status);
delete listFormatterStd;
listFormatterStd = ListFormatter::createInstance(
locale,
"standard",
status);
}
void MeasureFormat::adoptNumberFormat(
NumberFormat *nfToAdopt, UErrorCode &status) {
LocalPointer<NumberFormat> nf(nfToAdopt);
if (U_FAILURE(status)) {
return;
}
SharedNumberFormat *shared = new SharedNumberFormat(nf.getAlias());
if (shared == NULL) {
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, NULL, status);
return U_SUCCESS(status);
}
UMeasureFormatWidth MeasureFormat::getWidth() const {
return fWidth;
}
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);
}
UnicodeString &MeasureFormat::getUnitName(
const MeasureUnit* unit,
UnicodeString &result ) const {
UErrorCode status = U_ZERO_ERROR;
result = getUnitDisplayName(*unit, status); return result;
}
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;
}
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)) {
UChar isoCode[4];
u_charsToUChars(amtUnit.getSubtype(), isoCode, 4);
return cache->getCurrencyFormat(fWidth)->format(
new CurrencyAmount(amtNumber, isoCode, status),
appendTo,
pos,
status);
}
int32_t cur = appendTo.length();
UBool posForFullNumericPart = (pos.getField() == UAMEASFMT_NUMERIC_FIELD_FLAG);
if (posForFullNumericPart) {
pos.setField(FieldPosition::DONT_CARE);
}
auto* df = dynamic_cast<const DecimalFormat*>(&nf);
if (df == nullptr) {
UnicodeString formattedNumber;
StandardPlural::Form pluralForm = QuantityFormatter::selectPlural(
amtNumber, nf, **pluralRules, formattedNumber, pos, status);
if (posForFullNumericPart) {
pos.setField(UAMEASFMT_NUMERIC_FIELD_FLAG);
pos.setBeginIndex(0);
pos.setEndIndex(formattedNumber.length());
}
UnicodeString pattern = number::impl::LongNameHandler::getUnitPattern(getLocale(status),
amtUnit, getUnitWidth(fWidth), pluralForm, status);
if (pattern.isBogus() && pluralForm != StandardPlural::Form::OTHER) {
pattern = number::impl::LongNameHandler::getUnitPattern(getLocale(status),
amtUnit, getUnitWidth(fWidth), StandardPlural::Form::OTHER, status);
}
if (U_FAILURE(status)) {
return appendTo;
}
SimpleFormatter formatter(pattern, 0, 1, status);
QuantityFormatter::format(formatter, formattedNumber, appendTo, pos, status);
} else {
number::FormattedNumber result;
if (auto* lnf = df->toNumberFormatter(status)) {
result = lnf->unit(amtUnit)
.unitWidth(getUnitWidth(fWidth))
.formatDouble(amtNumber.getDouble(status), 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) {
pos.setBeginIndex(intBegin);
if (fracBegin >= intEnd && fracEnd > fracBegin) {
pos.setEndIndex(fracEnd);
} else {
pos.setEndIndex(intEnd);
}
} else if (fracBegin >= 0 && fracEnd > fracBegin) {
pos.setBeginIndex(fracBegin);
pos.setEndIndex(fracEnd);
} else {
pos.setBeginIndex(0);
pos.setEndIndex(0);
}
pos.setField(UAMEASFMT_NUMERIC_FIELD_FLAG);
}
appendTo.append(result.toTempString(status));
}
if (stripPatternSpaces) {
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) {
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);
}
}
}
}
}
}
return appendTo;
}
UnicodeString &MeasureFormat::formatNumeric(
const Formattable *hms, int32_t bitMap, UnicodeString &appendTo,
FieldPositionHandler& handler,
UErrorCode &status) const {
if (U_FAILURE(status)) {
return appendTo;
}
UDate millis =
(UDate) (((uprv_trunc(hms[0].getDouble(status)) * 60.0
+ uprv_trunc(hms[1].getDouble(status))) * 60.0
+ uprv_trunc(hms[2].getDouble(status))) * 1000.0);
switch (bitMap) {
case 5: case 7: return formatNumeric(
millis,
cache->getNumericDateFormatters()->hourMinuteSecond,
UDAT_SECOND_FIELD,
hms[2],
appendTo,
handler,
status);
break;
case 6: return formatNumeric(
millis,
cache->getNumericDateFormatters()->minuteSecond,
UDAT_SECOND_FIELD,
hms[2],
appendTo,
handler,
status);
break;
case 3: return formatNumeric(
millis,
cache->getNumericDateFormatters()->hourMinute,
UDAT_MINUTE_FIELD,
hms[1],
appendTo,
handler,
status);
break;
default:
status = U_INTERNAL_PROGRAM_ERROR;
return appendTo;
break;
}
}
static void appendRange(
const UnicodeString &src,
int32_t start,
int32_t end,
UnicodeString &dest) {
dest.append(src, start, end - start);
}
static void appendRange(
const UnicodeString &src,
int32_t end,
UnicodeString &dest) {
dest.append(src, end, src.length() - end);
}
UnicodeString &MeasureFormat::formatNumeric(
UDate date, const DateFormat &dateFmt, UDateFormatField smallestField, const Formattable &smallestAmount, UnicodeString &appendTo,
FieldPositionHandler& handler,
UErrorCode &status) const {
if (U_FAILURE(status)) {
return appendTo;
}
UnicodeString smallestAmountFormatted;
FieldPosition intFieldPosition(UNUM_INTEGER_FIELD);
(*numberFormat)->format(
smallestAmount, smallestAmountFormatted, intFieldPosition, status);
if (
intFieldPosition.getBeginIndex() == 0 &&
intFieldPosition.getEndIndex() == 0) {
status = U_INTERNAL_PROGRAM_ERROR;
return appendTo;
}
FieldPositionIterator posIter;
UnicodeString draft;
static UMutex *dateFmtMutex = STATIC_NEW(UMutex);
umtx_lock(dateFmtMutex);
dateFmt.format(date, draft, &posIter, status);
umtx_unlock(dateFmtMutex);
int32_t start = appendTo.length();
FieldPosition smallestFieldPosition(smallestField);
FieldPosition fp;
int32_t measField = -1;
while (posIter.next(fp)) {
int32_t dateField = fp.getField();
switch (dateField) {
case UDAT_HOUR_OF_DAY1_FIELD:
case UDAT_HOUR_OF_DAY0_FIELD:
case UDAT_HOUR1_FIELD:
case UDAT_HOUR0_FIELD:
measField = UAMEASUNIT_DURATION_HOUR; break;
case UDAT_MINUTE_FIELD:
measField = UAMEASUNIT_DURATION_MINUTE; break;
case UDAT_SECOND_FIELD:
measField = UAMEASUNIT_DURATION_SECOND; break;
default:
measField = -1; break;
}
if (dateField != smallestField) {
if (measField >= 0) {
handler.addAttribute(measField, start + fp.getBeginIndex(), start + fp.getEndIndex());
handler.addAttribute(measField | UAMEASFMT_NUMERIC_FIELD_FLAG, start + fp.getBeginIndex(), start + fp.getEndIndex());
}
} else {
smallestFieldPosition.setBeginIndex(fp.getBeginIndex());
smallestFieldPosition.setEndIndex(fp.getEndIndex());
break;
}
}
if (smallestFieldPosition.getBeginIndex() != 0 ||
smallestFieldPosition.getEndIndex() != 0) {
appendRange(draft, 0, smallestFieldPosition.getBeginIndex(), appendTo);
appendRange(
smallestAmountFormatted,
0,
intFieldPosition.getBeginIndex(),
appendTo);
appendRange(
draft,
smallestFieldPosition.getBeginIndex(),
smallestFieldPosition.getEndIndex(),
appendTo);
appendRange(
smallestAmountFormatted,
intFieldPosition.getEndIndex(),
appendTo);
appendRange(
draft,
smallestFieldPosition.getEndIndex(),
appendTo);
handler.addAttribute(measField, start + smallestFieldPosition.getBeginIndex(), appendTo.length());
handler.addAttribute(measField | UAMEASFMT_NUMERIC_FIELD_FLAG, start + smallestFieldPosition.getBeginIndex(), appendTo.length());
} else {
appendTo.append(draft);
}
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;
}
if (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