deps: update to ICU 67.1

Refs: https://github.com/unicode-org/icu/releases/tag/release-67-1

PR-URL: https://github.com/nodejs/node/pull/33324
Reviewed-By: Ujjwal Sharma <ryzokuken@disroot.org>
Reviewed-By: Steven R Loomis <srloomis@us.ibm.com>
This commit is contained in:
Michaël Zasso committed 2020-05-12 08:19:43 +02:00
1 parent 8c5d58b5a7
commit cfec30fef3
172 files changed
+6406 -3466

No files matched your search

+2 -2
View File
@@ -1,8 +1,8 @@
ICU sources - auto generated by shrink-icu-src.py
This directory contains the ICU subset used by --with-intl=full-icu
It is a strict subset of ICU 66 source files with the following exception(s):
* deps/icu-small/source/data/in/icudt66l.dat.bz2 : compressed data file
It is a strict subset of ICU 67 source files with the following exception(s):
* deps/icu-small/source/data/in/icudt67l.dat.bz2 : compressed data file
To rebuild this directory, see ../../tools/icu/README.md
+27 -8
View File
@@ -38,6 +38,7 @@
#include "uresimp.h"
#include "uassert.h"
#include "ubrkimpl.h"
#include "utracimp.h"
#include "charstr.h"
// *****************************************************************************
@@ -412,14 +413,23 @@ BreakIterator::makeInstance(const Locale& loc, int32_t kind, UErrorCode& status)
BreakIterator *result = NULL;
switch (kind) {
case UBRK_CHARACTER:
result = BreakIterator::buildInstance(loc, "grapheme", status);
{
UTRACE_ENTRY(UTRACE_UBRK_CREATE_CHARACTER);
result = BreakIterator::buildInstance(loc, "grapheme", status);
UTRACE_EXIT_STATUS(status);
}
break;
case UBRK_WORD:
result = BreakIterator::buildInstance(loc, "word", status);
{
UTRACE_ENTRY(UTRACE_UBRK_CREATE_WORD);
result = BreakIterator::buildInstance(loc, "word", status);
UTRACE_EXIT_STATUS(status);
}
break;
case UBRK_LINE:
uprv_strcpy(lbType, "line");
{
UTRACE_ENTRY(UTRACE_UBRK_CREATE_LINE);
uprv_strcpy(lbType, "line");
char lbKeyValue[kKeyValueLenMax] = {0};
UErrorCode kvStatus = U_ZERO_ERROR;
int32_t kLen = loc.getKeywordValue("lb", lbKeyValue, kKeyValueLenMax, kvStatus);
@@ -427,13 +437,17 @@ BreakIterator::makeInstance(const Locale& loc, int32_t kind, UErrorCode& status)
uprv_strcat(lbType, "_");
uprv_strcat(lbType, lbKeyValue);
}
result = BreakIterator::buildInstance(loc, lbType, status);
UTRACE_DATA1(UTRACE_INFO, "lb=%s", lbKeyValue);
UTRACE_EXIT_STATUS(status);
}
result = BreakIterator::buildInstance(loc, lbType, status);
break;
case UBRK_SENTENCE:
result = BreakIterator::buildInstance(loc, "sentence", status);
#if !UCONFIG_NO_FILTERED_BREAK_ITERATION
{
UTRACE_ENTRY(UTRACE_UBRK_CREATE_SENTENCE);
result = BreakIterator::buildInstance(loc, "sentence", status);
#if !UCONFIG_NO_FILTERED_BREAK_ITERATION
char ssKeyValue[kKeyValueLenMax] = {0};
UErrorCode kvStatus = U_ZERO_ERROR;
int32_t kLen = loc.getKeywordValue("ss", ssKeyValue, kKeyValueLenMax, kvStatus);
@@ -444,11 +458,16 @@ BreakIterator::makeInstance(const Locale& loc, int32_t kind, UErrorCode& status)
delete fbiBuilder;
}
}
}
#endif
UTRACE_EXIT_STATUS(status);
}
break;
case UBRK_TITLE:
result = BreakIterator::buildInstance(loc, "title", status);
{
UTRACE_ENTRY(UTRACE_UBRK_CREATE_TITLE);
result = BreakIterator::buildInstance(loc, "title", status);
UTRACE_EXIT_STATUS(status);
}
break;
default:
status = U_ILLEGAL_ARGUMENT_ERROR;
+102 -18
View File
@@ -274,7 +274,10 @@ inline T *LocalMemory<T>::allocateInsteadAndCopy(int32_t newCapacity, int32_t le
*
* WARNING: MaybeStackArray only works with primitive (plain-old data) types.
* It does NOT know how to call a destructor! If you work with classes with
* destructors, consider LocalArray in localpointer.h or MemoryPool.
* destructors, consider:
*
* - LocalArray in localpointer.h if you know the length ahead of time
* - MaybeStackVector if you know the length at runtime
*/
template<typename T, int32_t stackCapacity>
class MaybeStackArray {
@@ -684,26 +687,26 @@ inline H *MaybeStackHeaderAndArray<H, T, stackCapacity>::orphanOrClone(int32_t l
template<typename T, int32_t stackCapacity = 8>
class MemoryPool : public UMemory {
public:
MemoryPool() : count(0), pool() {}
MemoryPool() : fCount(0), fPool() {}
~MemoryPool() {
for (int32_t i = 0; i < count; ++i) {
delete pool[i];
for (int32_t i = 0; i < fCount; ++i) {
delete fPool[i];
}
}
MemoryPool(const MemoryPool&) = delete;
MemoryPool& operator=(const MemoryPool&) = delete;
MemoryPool(MemoryPool&& other) U_NOEXCEPT : count(other.count),
pool(std::move(other.pool)) {
other.count = 0;
MemoryPool(MemoryPool&& other) U_NOEXCEPT : fCount(other.fCount),
fPool(std::move(other.fPool)) {
other.fCount = 0;
}
MemoryPool& operator=(MemoryPool&& other) U_NOEXCEPT {
count = other.count;
pool = std::move(other.pool);
other.count = 0;
fCount = other.fCount;
fPool = std::move(other.fPool);
other.fCount = 0;
return *this;
}
@@ -716,20 +719,101 @@ public:
*/
template<typename... Args>
T* create(Args&&... args) {
int32_t capacity = pool.getCapacity();
if (count == capacity &&
pool.resize(capacity == stackCapacity ? 4 * capacity : 2 * capacity,
capacity) == nullptr) {
int32_t capacity = fPool.getCapacity();
if (fCount == capacity &&
fPool.resize(capacity == stackCapacity ? 4 * capacity : 2 * capacity,
capacity) == nullptr) {
return nullptr;
}
return pool[count++] = new T(std::forward<Args>(args)...);
return fPool[fCount++] = new T(std::forward<Args>(args)...);
}
private:
int32_t count;
MaybeStackArray<T*, stackCapacity> pool;
/**
* @return Number of elements that have been allocated.
*/
int32_t count() const {
return fCount;
}
protected:
int32_t fCount;
MaybeStackArray<T*, stackCapacity> fPool;
};
/**
* An internal Vector-like implementation based on MemoryPool.
*
* Heap-allocates each element and stores pointers.
*
* To append an item to the vector, use emplaceBack.
*
* MaybeStackVector<MyType> vector;
* MyType* element = vector.emplaceBack();
* if (!element) {
* status = U_MEMORY_ALLOCATION_ERROR;
* }
* // do stuff with element
*
* To loop over the vector, use a for loop with indices:
*
* for (int32_t i = 0; i < vector.length(); i++) {
* MyType* element = vector[i];
* }
*/
template<typename T, int32_t stackCapacity = 8>
class MaybeStackVector : protected MemoryPool<T, stackCapacity> {
public:
using MemoryPool<T, stackCapacity>::MemoryPool;
using MemoryPool<T, stackCapacity>::operator=;
template<typename... Args>
T* emplaceBack(Args&&... args) {
return this->create(args...);
}
int32_t length() const {
return this->fCount;
}
T** getAlias() {
return this->fPool.getAlias();
}
/**
* Array item access (read-only).
* No index bounds check.
* @param i array index
* @return reference to the array item
*/
const T* operator[](ptrdiff_t i) const {
return this->fPool[i];
}
/**
* Array item access (writable).
* No index bounds check.
* @param i array index
* @return reference to the array item
*/
T* operator[](ptrdiff_t i) {
return this->fPool[i];
}
/**
* Append all the items from another MaybeStackVector to this one.
*/
void appendAll(const MaybeStackVector& other, UErrorCode& status) {
for (int32_t i = 0; i < other.fCount; i++) {
T* item = emplaceBack(*other[i]);
if (!item) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
}
};
U_NAMESPACE_END
#endif /* __cplusplus */
+2
View File
@@ -52,6 +52,8 @@
U_CAPI UBool U_EXPORT2
uprv_isASCIILetter(char c);
// NOTE: For u_asciiToUpper that takes a UChar, see ustr_imp.h
U_CAPI char U_EXPORT2
uprv_toupper(char c);
+16
View File
@@ -18,6 +18,7 @@
#include "unicode/uniset.h"
#include "unicode/chariter.h"
#include "unicode/ubrk.h"
#include "utracimp.h"
#include "uvectr32.h"
#include "uvector.h"
#include "uassert.h"
@@ -194,6 +195,8 @@ ThaiBreakEngine::ThaiBreakEngine(DictionaryMatcher *adoptDictionary, UErrorCode
: DictionaryBreakEngine(),
fDictionary(adoptDictionary)
{
UTRACE_ENTRY(UTRACE_UBRK_CREATE_BREAK_ENGINE);
UTRACE_DATA1(UTRACE_INFO, "dictbe=%s", "Thai");
fThaiWordSet.applyPattern(UNICODE_STRING_SIMPLE("[[:Thai:]&[:LineBreak=SA:]]"), status);
if (U_SUCCESS(status)) {
setCharacters(fThaiWordSet);
@@ -213,6 +216,7 @@ ThaiBreakEngine::ThaiBreakEngine(DictionaryMatcher *adoptDictionary, UErrorCode
fEndWordSet.compact();
fBeginWordSet.compact();
fSuffixSet.compact();
UTRACE_EXIT_STATUS(status);
}
ThaiBreakEngine::~ThaiBreakEngine() {
@@ -436,6 +440,8 @@ LaoBreakEngine::LaoBreakEngine(DictionaryMatcher *adoptDictionary, UErrorCode &s
: DictionaryBreakEngine(),
fDictionary(adoptDictionary)
{
UTRACE_ENTRY(UTRACE_UBRK_CREATE_BREAK_ENGINE);
UTRACE_DATA1(UTRACE_INFO, "dictbe=%s", "Laoo");
fLaoWordSet.applyPattern(UNICODE_STRING_SIMPLE("[[:Laoo:]&[:LineBreak=SA:]]"), status);
if (U_SUCCESS(status)) {
setCharacters(fLaoWordSet);
@@ -452,6 +458,7 @@ LaoBreakEngine::LaoBreakEngine(DictionaryMatcher *adoptDictionary, UErrorCode &s
fMarkSet.compact();
fEndWordSet.compact();
fBeginWordSet.compact();
UTRACE_EXIT_STATUS(status);
}
LaoBreakEngine::~LaoBreakEngine() {
@@ -632,6 +639,8 @@ BurmeseBreakEngine::BurmeseBreakEngine(DictionaryMatcher *adoptDictionary, UErro
: DictionaryBreakEngine(),
fDictionary(adoptDictionary)
{
UTRACE_ENTRY(UTRACE_UBRK_CREATE_BREAK_ENGINE);
UTRACE_DATA1(UTRACE_INFO, "dictbe=%s", "Mymr");
fBurmeseWordSet.applyPattern(UNICODE_STRING_SIMPLE("[[:Mymr:]&[:LineBreak=SA:]]"), status);
if (U_SUCCESS(status)) {
setCharacters(fBurmeseWordSet);
@@ -645,6 +654,7 @@ BurmeseBreakEngine::BurmeseBreakEngine(DictionaryMatcher *adoptDictionary, UErro
fMarkSet.compact();
fEndWordSet.compact();
fBeginWordSet.compact();
UTRACE_EXIT_STATUS(status);
}
BurmeseBreakEngine::~BurmeseBreakEngine() {
@@ -825,6 +835,8 @@ KhmerBreakEngine::KhmerBreakEngine(DictionaryMatcher *adoptDictionary, UErrorCod
: DictionaryBreakEngine(),
fDictionary(adoptDictionary)
{
UTRACE_ENTRY(UTRACE_UBRK_CREATE_BREAK_ENGINE);
UTRACE_DATA1(UTRACE_INFO, "dictbe=%s", "Khmr");
fKhmerWordSet.applyPattern(UNICODE_STRING_SIMPLE("[[:Khmr:]&[:LineBreak=SA:]]"), status);
if (U_SUCCESS(status)) {
setCharacters(fKhmerWordSet);
@@ -850,6 +862,7 @@ KhmerBreakEngine::KhmerBreakEngine(DictionaryMatcher *adoptDictionary, UErrorCod
fEndWordSet.compact();
fBeginWordSet.compact();
// fSuffixSet.compact();
UTRACE_EXIT_STATUS(status);
}
KhmerBreakEngine::~KhmerBreakEngine() {
@@ -1045,6 +1058,8 @@ foundBest:
static const uint32_t kuint32max = 0xFFFFFFFF;
CjkBreakEngine::CjkBreakEngine(DictionaryMatcher *adoptDictionary, LanguageType type, UErrorCode &status)
: DictionaryBreakEngine(), fDictionary(adoptDictionary) {
UTRACE_ENTRY(UTRACE_UBRK_CREATE_BREAK_ENGINE);
UTRACE_DATA1(UTRACE_INFO, "dictbe=%s", "Hani");
// Korean dictionary only includes Hangul syllables
fHangulWordSet.applyPattern(UNICODE_STRING_SIMPLE("[\\uac00-\\ud7a3]"), status);
fHanWordSet.applyPattern(UNICODE_STRING_SIMPLE("[:Han:]"), status);
@@ -1066,6 +1081,7 @@ CjkBreakEngine::CjkBreakEngine(DictionaryMatcher *adoptDictionary, LanguageType
setCharacters(cjSet);
}
}
UTRACE_EXIT_STATUS(status);
}
CjkBreakEngine::~CjkBreakEngine(){
+183 -109
View File
@@ -12,6 +12,7 @@
#include "unicode/localematcher.h"
#include "unicode/locid.h"
#include "unicode/stringpiece.h"
#include "unicode/uloc.h"
#include "unicode/uobject.h"
#include "cstring.h"
#include "localeprioritylist.h"
@@ -20,9 +21,10 @@
#include "lsr.h"
#include "uassert.h"
#include "uhash.h"
#include "ustr_imp.h"
#include "uvector.h"
#define UND_LSR LSR("und", "", "")
#define UND_LSR LSR("und", "", "", LSR::EXPLICIT_LSR)
/**
* Indicator for the lifetime of desired-locale objects passed into the LocaleMatcher.
@@ -129,7 +131,8 @@ LocaleMatcher::Builder::Builder(LocaleMatcher::Builder &&src) U_NOEXCEPT :
thresholdDistance_(src.thresholdDistance_),
demotion_(src.demotion_),
defaultLocale_(src.defaultLocale_),
favor_(src.favor_) {
favor_(src.favor_),
direction_(src.direction_) {
src.supportedLocales_ = nullptr;
src.defaultLocale_ = nullptr;
}
@@ -148,6 +151,7 @@ LocaleMatcher::Builder &LocaleMatcher::Builder::operator=(LocaleMatcher::Builder
demotion_ = src.demotion_;
defaultLocale_ = src.defaultLocale_;
favor_ = src.favor_;
direction_ = src.direction_;
src.supportedLocales_ = nullptr;
src.defaultLocale_ = nullptr;
@@ -308,38 +312,53 @@ UBool compareLSRs(const UHashTok t1, const UHashTok t2) {
return *lsr1 == *lsr2;
}
bool putIfAbsent(UHashtable *lsrToIndex, const LSR &lsr, int32_t i, UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) { return false; }
U_ASSERT(i > 0);
int32_t index = uhash_geti(lsrToIndex, &lsr);
if (index != 0) {
return false;
} else {
uhash_puti(lsrToIndex, const_cast<LSR *>(&lsr), i, &errorCode);
return U_SUCCESS(errorCode);
}
}
} // namespace
int32_t LocaleMatcher::putIfAbsent(const LSR &lsr, int32_t i, int32_t suppLength,
UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) { return suppLength; }
int32_t index = uhash_geti(supportedLsrToIndex, &lsr);
if (index == 0) {
uhash_puti(supportedLsrToIndex, const_cast<LSR *>(&lsr), i + 1, &errorCode);
if (U_SUCCESS(errorCode)) {
supportedLSRs[suppLength] = &lsr;
supportedIndexes[suppLength++] = i;
}
}
return suppLength;
}
LocaleMatcher::LocaleMatcher(const Builder &builder, UErrorCode &errorCode) :
likelySubtags(*XLikelySubtags::getSingleton(errorCode)),
localeDistance(*LocaleDistance::getSingleton(errorCode)),
thresholdDistance(builder.thresholdDistance_),
demotionPerDesiredLocale(0),
favorSubtag(builder.favor_),
direction(builder.direction_),
supportedLocales(nullptr), lsrs(nullptr), supportedLocalesLength(0),
supportedLsrToIndex(nullptr),
supportedLSRs(nullptr), supportedIndexes(nullptr), supportedLSRsLength(0),
ownedDefaultLocale(nullptr), defaultLocale(nullptr), defaultLocaleIndex(-1) {
ownedDefaultLocale(nullptr), defaultLocale(nullptr) {
if (U_FAILURE(errorCode)) { return; }
if (thresholdDistance < 0) {
thresholdDistance = localeDistance.getDefaultScriptDistance();
}
const Locale *def = builder.defaultLocale_;
LSR builderDefaultLSR;
const LSR *defLSR = nullptr;
if (def != nullptr) {
ownedDefaultLocale = def->clone();
if (ownedDefaultLocale == nullptr) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
def = ownedDefaultLocale;
builderDefaultLSR = getMaximalLsrOrUnd(likelySubtags, *def, errorCode);
if (U_FAILURE(errorCode)) { return; }
defLSR = &builderDefaultLSR;
}
supportedLocalesLength = builder.supportedLocales_ != nullptr ?
builder.supportedLocales_->size() : 0;
const Locale *def = builder.defaultLocale_;
int32_t idef = -1;
if (supportedLocalesLength > 0) {
// Store the supported locales in input order,
// so that when different types are used (e.g., language tag strings)
@@ -356,15 +375,6 @@ LocaleMatcher::LocaleMatcher(const Builder &builder, UErrorCode &errorCode) :
}
// If the constructor fails partway, we need null pointers for destructibility.
uprv_memset(supportedLocales, 0, supportedLocalesLength * sizeof(const Locale *));
// Also find the first supported locale whose LSR is
// the same as that for the default locale.
LSR builderDefaultLSR;
const LSR *defLSR = nullptr;
if (def != nullptr) {
builderDefaultLSR = getMaximalLsrOrUnd(likelySubtags, *def, errorCode);
if (U_FAILURE(errorCode)) { return; }
defLSR = &builderDefaultLSR;
}
for (int32_t i = 0; i < supportedLocalesLength; ++i) {
const Locale &locale = *static_cast<Locale *>(builder.supportedLocales_->elementAt(i));
supportedLocales[i] = locale.clone();
@@ -376,103 +386,74 @@ LocaleMatcher::LocaleMatcher(const Builder &builder, UErrorCode &errorCode) :
LSR &lsr = lsrs[i] = getMaximalLsrOrUnd(likelySubtags, supportedLocale, errorCode);
lsr.setHashCode();
if (U_FAILURE(errorCode)) { return; }
if (idef < 0 && defLSR != nullptr && lsr == *defLSR) {
idef = i;
defLSR = &lsr; // owned pointer to put into supportedLsrToIndex
if (*def == supportedLocale) {
def = &supportedLocale; // owned pointer to keep
}
}
}
// We need an unordered map from LSR to first supported locale with that LSR,
// and an ordered list of (LSR, supported index).
// We insert the supported locales in the following order:
// and an ordered list of (LSR, supported index) for
// the supported locales in the following order:
// 1. Default locale, if it is supported.
// 2. Priority locales (aka "paradigm locales") in builder order.
// 3. Remaining locales in builder order.
// In Java, we use a LinkedHashMap for both map & ordered lists.
// In C++, we use separate structures.
// We over-allocate arrays of LSRs and indexes for simplicity.
// We reserve slots at the array starts for the default and paradigm locales,
// plus enough for all supported locales.
// If there are few paradigm locales and few duplicate supported LSRs,
// then the amount of wasted space is small.
supportedLsrToIndex = uhash_openSize(hashLSR, compareLSRs, uhash_compareLong,
supportedLocalesLength, &errorCode);
if (U_FAILURE(errorCode)) { return; }
int32_t paradigmLimit = 1 + localeDistance.getParadigmLSRsLength();
int32_t suppLSRsCapacity = paradigmLimit + supportedLocalesLength;
supportedLSRs = static_cast<const LSR **>(
uprv_malloc(suppLSRsCapacity * sizeof(const LSR *)));
uprv_malloc(supportedLocalesLength * sizeof(const LSR *)));
supportedIndexes = static_cast<int32_t *>(
uprv_malloc(suppLSRsCapacity * sizeof(int32_t)));
uprv_malloc(supportedLocalesLength * sizeof(int32_t)));
if (supportedLSRs == nullptr || supportedIndexes == nullptr) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
int32_t paradigmIndex = 0;
int32_t otherIndex = paradigmLimit;
if (idef >= 0) {
uhash_puti(supportedLsrToIndex, const_cast<LSR *>(defLSR), idef + 1, &errorCode);
supportedLSRs[0] = defLSR;
supportedIndexes[0] = idef;
paradigmIndex = 1;
int32_t suppLength = 0;
// Determine insertion order.
// Add locales immediately that are equivalent to the default.
MaybeStackArray<int8_t, 100> order(supportedLocalesLength);
if (order.getAlias() == nullptr) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
int32_t numParadigms = 0;
for (int32_t i = 0; i < supportedLocalesLength; ++i) {
if (i == idef) { continue; }
const Locale &locale = *supportedLocales[i];
const LSR &lsr = lsrs[i];
if (defLSR == nullptr) {
U_ASSERT(i == 0);
def = &locale;
defLSR = &lsr;
idef = 0;
uhash_puti(supportedLsrToIndex, const_cast<LSR *>(&lsr), 0 + 1, &errorCode);
supportedLSRs[0] = &lsr;
supportedIndexes[0] = 0;
paradigmIndex = 1;
} else if (idef >= 0 && lsr == *defLSR) {
// lsr == *defLSR means that this supported locale is
// a duplicate of the default locale.
// Either an explicit default locale is supported, and we added it before the loop,
// or there is no explicit default locale, and this is
// a duplicate of the first supported locale.
// In both cases, idef >= 0 now, so otherwise we can skip the comparison.
// For a duplicate, putIfAbsent() is a no-op, so nothing to do.
order[i] = 1;
suppLength = putIfAbsent(lsr, 0, suppLength, errorCode);
} else if (lsr.isEquivalentTo(*defLSR)) {
order[i] = 1;
suppLength = putIfAbsent(lsr, i, suppLength, errorCode);
} else if (localeDistance.isParadigmLSR(lsr)) {
order[i] = 2;
++numParadigms;
} else {
if (putIfAbsent(supportedLsrToIndex, lsr, i + 1, errorCode)) {
if (localeDistance.isParadigmLSR(lsr)) {
supportedLSRs[paradigmIndex] = &lsr;
supportedIndexes[paradigmIndex++] = i;
} else {
supportedLSRs[otherIndex] = &lsr;
supportedIndexes[otherIndex++] = i;
}
}
order[i] = 3;
}
if (U_FAILURE(errorCode)) { return; }
}
// Squeeze out unused array slots.
if (paradigmIndex < paradigmLimit && paradigmLimit < otherIndex) {
uprv_memmove(supportedLSRs + paradigmIndex, supportedLSRs + paradigmLimit,
(otherIndex - paradigmLimit) * sizeof(const LSR *));
uprv_memmove(supportedIndexes + paradigmIndex, supportedIndexes + paradigmLimit,
(otherIndex - paradigmLimit) * sizeof(int32_t));
// Add supported paradigm locales.
int32_t paradigmLimit = suppLength + numParadigms;
for (int32_t i = 0; i < supportedLocalesLength && suppLength < paradigmLimit; ++i) {
if (order[i] == 2) {
suppLength = putIfAbsent(lsrs[i], i, suppLength, errorCode);
}
}
supportedLSRsLength = otherIndex - (paradigmLimit - paradigmIndex);
// Add remaining supported locales.
for (int32_t i = 0; i < supportedLocalesLength; ++i) {
if (order[i] == 3) {
suppLength = putIfAbsent(lsrs[i], i, suppLength, errorCode);
}
}
supportedLSRsLength = suppLength;
// If supportedLSRsLength < supportedLocalesLength then
// we waste as many array slots as there are duplicate supported LSRs,
// but the amount of wasted space is small as long as there are few duplicates.
}
if (def != nullptr && (idef < 0 || def != supportedLocales[idef])) {
ownedDefaultLocale = def->clone();
if (ownedDefaultLocale == nullptr) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
def = ownedDefaultLocale;
}
defaultLocale = def;
defaultLocaleIndex = idef;
if (builder.demotion_ == ULOCMATCH_DEMOTION_REGION) {
demotionPerDesiredLocale = localeDistance.getDefaultDemotionPerDesiredLocale();
@@ -485,14 +466,14 @@ LocaleMatcher::LocaleMatcher(LocaleMatcher &&src) U_NOEXCEPT :
thresholdDistance(src.thresholdDistance),
demotionPerDesiredLocale(src.demotionPerDesiredLocale),
favorSubtag(src.favorSubtag),
direction(src.direction),
supportedLocales(src.supportedLocales), lsrs(src.lsrs),
supportedLocalesLength(src.supportedLocalesLength),
supportedLsrToIndex(src.supportedLsrToIndex),
supportedLSRs(src.supportedLSRs),
supportedIndexes(src.supportedIndexes),
supportedLSRsLength(src.supportedLSRsLength),
ownedDefaultLocale(src.ownedDefaultLocale), defaultLocale(src.defaultLocale),
defaultLocaleIndex(src.defaultLocaleIndex) {
ownedDefaultLocale(src.ownedDefaultLocale), defaultLocale(src.defaultLocale) {
src.supportedLocales = nullptr;
src.lsrs = nullptr;
src.supportedLocalesLength = 0;
@@ -502,7 +483,6 @@ LocaleMatcher::LocaleMatcher(LocaleMatcher &&src) U_NOEXCEPT :
src.supportedLSRsLength = 0;
src.ownedDefaultLocale = nullptr;
src.defaultLocale = nullptr;
src.defaultLocaleIndex = -1;
}
LocaleMatcher::~LocaleMatcher() {
@@ -523,6 +503,7 @@ LocaleMatcher &LocaleMatcher::operator=(LocaleMatcher &&src) U_NOEXCEPT {
thresholdDistance = src.thresholdDistance;
demotionPerDesiredLocale = src.demotionPerDesiredLocale;
favorSubtag = src.favorSubtag;
direction = src.direction;
supportedLocales = src.supportedLocales;
lsrs = src.lsrs;
supportedLocalesLength = src.supportedLocalesLength;
@@ -532,7 +513,6 @@ LocaleMatcher &LocaleMatcher::operator=(LocaleMatcher &&src) U_NOEXCEPT {
supportedLSRsLength = src.supportedLSRsLength;
ownedDefaultLocale = src.ownedDefaultLocale;
defaultLocale = src.defaultLocale;
defaultLocaleIndex = src.defaultLocaleIndex;
src.supportedLocales = nullptr;
src.lsrs = nullptr;
@@ -543,7 +523,6 @@ LocaleMatcher &LocaleMatcher::operator=(LocaleMatcher &&src) U_NOEXCEPT {
src.supportedLSRsLength = 0;
src.ownedDefaultLocale = nullptr;
src.defaultLocale = nullptr;
src.defaultLocaleIndex = -1;
return *this;
}
@@ -630,13 +609,13 @@ const Locale *LocaleMatcher::getBestMatchForListString(
LocaleMatcher::Result LocaleMatcher::getBestMatchResult(
const Locale &desiredLocale, UErrorCode &errorCode) const {
if (U_FAILURE(errorCode)) {
return Result(nullptr, defaultLocale, -1, defaultLocaleIndex, FALSE);
return Result(nullptr, defaultLocale, -1, -1, FALSE);
}
int32_t suppIndex = getBestSuppIndex(
getMaximalLsrOrUnd(likelySubtags, desiredLocale, errorCode),
nullptr, errorCode);
if (U_FAILURE(errorCode) || suppIndex < 0) {
return Result(nullptr, defaultLocale, -1, defaultLocaleIndex, FALSE);
return Result(nullptr, defaultLocale, -1, -1, FALSE);
} else {
return Result(&desiredLocale, supportedLocales[suppIndex], 0, suppIndex, FALSE);
}
@@ -645,12 +624,12 @@ LocaleMatcher::Result LocaleMatcher::getBestMatchResult(
LocaleMatcher::Result LocaleMatcher::getBestMatchResult(
Locale::Iterator &desiredLocales, UErrorCode &errorCode) const {
if (U_FAILURE(errorCode) || !desiredLocales.hasNext()) {
return Result(nullptr, defaultLocale, -1, defaultLocaleIndex, FALSE);
return Result(nullptr, defaultLocale, -1, -1, FALSE);
}
LocaleLsrIterator lsrIter(likelySubtags, desiredLocales, ULOCMATCH_TEMPORARY_LOCALES);
int32_t suppIndex = getBestSuppIndex(lsrIter.next(errorCode), &lsrIter, errorCode);
if (U_FAILURE(errorCode) || suppIndex < 0) {
return Result(nullptr, defaultLocale, -1, defaultLocaleIndex, FALSE);
return Result(nullptr, defaultLocale, -1, -1, FALSE);
} else {
return Result(lsrIter.orphanRemembered(), supportedLocales[suppIndex],
lsrIter.getBestDesiredIndex(), suppIndex, TRUE);
@@ -662,7 +641,7 @@ int32_t LocaleMatcher::getBestSuppIndex(LSR desiredLSR, LocaleLsrIterator *remai
if (U_FAILURE(errorCode)) { return -1; }
int32_t desiredIndex = 0;
int32_t bestSupportedLsrIndex = -1;
for (int32_t bestDistance = thresholdDistance;;) {
for (int32_t bestShiftedDistance = LocaleDistance::shiftDistance(thresholdDistance);;) {
// Quick check for exact maximized LSR.
// Returns suppIndex+1 where 0 means not found.
if (supportedLsrToIndex != nullptr) {
@@ -677,16 +656,17 @@ int32_t LocaleMatcher::getBestSuppIndex(LSR desiredLSR, LocaleLsrIterator *remai
}
}
int32_t bestIndexAndDistance = localeDistance.getBestIndexAndDistance(
desiredLSR, supportedLSRs, supportedLSRsLength, bestDistance, favorSubtag);
desiredLSR, supportedLSRs, supportedLSRsLength,
bestShiftedDistance, favorSubtag, direction);
if (bestIndexAndDistance >= 0) {
bestDistance = bestIndexAndDistance & 0xff;
bestShiftedDistance = LocaleDistance::getShiftedDistance(bestIndexAndDistance);
if (remainingIter != nullptr) {
remainingIter->rememberCurrent(desiredIndex, errorCode);
if (U_FAILURE(errorCode)) { return -1; }
}
bestSupportedLsrIndex = bestIndexAndDistance >= 0 ? bestIndexAndDistance >> 8 : -1;
bestSupportedLsrIndex = LocaleDistance::getIndex(bestIndexAndDistance);
}
if ((bestDistance -= demotionPerDesiredLocale) <= 0) {
if ((bestShiftedDistance -= LocaleDistance::shiftDistance(demotionPerDesiredLocale)) <= 0) {
break;
}
if (remainingIter == nullptr || !remainingIter->hasNext()) {
@@ -708,13 +688,107 @@ double LocaleMatcher::internalMatch(const Locale &desired, const Locale &support
LSR suppLSR = getMaximalLsrOrUnd(likelySubtags, supported, errorCode);
if (U_FAILURE(errorCode)) { return 0; }
const LSR *pSuppLSR = &suppLSR;
int32_t distance = localeDistance.getBestIndexAndDistance(
int32_t indexAndDistance = localeDistance.getBestIndexAndDistance(
getMaximalLsrOrUnd(likelySubtags, desired, errorCode),
&pSuppLSR, 1,
thresholdDistance, favorSubtag) & 0xff;
return (100 - distance) / 100.0;
LocaleDistance::shiftDistance(thresholdDistance), favorSubtag, direction);
double distance = LocaleDistance::getDistanceDouble(indexAndDistance);
return (100.0 - distance) / 100.0;
}
U_NAMESPACE_END
// uloc_acceptLanguage() --------------------------------------------------- ***
U_NAMESPACE_USE
namespace {
class LocaleFromTag {
public:
LocaleFromTag() : locale(Locale::getRoot()) {}
const Locale &operator()(const char *tag) { return locale = Locale(tag); }
private:
// Store the locale in the converter, rather than return a reference to a temporary,
// or a value which could go out of scope with the caller's reference to it.
Locale locale;
};
int32_t acceptLanguage(UEnumeration &supportedLocales, Locale::Iterator &desiredLocales,
char *dest, int32_t capacity, UAcceptResult *acceptResult,
UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) { return 0; }
LocaleMatcher::Builder builder;
const char *locString;
while ((locString = uenum_next(&supportedLocales, nullptr, &errorCode)) != nullptr) {
Locale loc(locString);
if (loc.isBogus()) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
builder.addSupportedLocale(loc);
}
LocaleMatcher matcher = builder.build(errorCode);
LocaleMatcher::Result result = matcher.getBestMatchResult(desiredLocales, errorCode);
if (U_FAILURE(errorCode)) { return 0; }
if (result.getDesiredIndex() >= 0) {
if (acceptResult != nullptr) {
*acceptResult = *result.getDesiredLocale() == *result.getSupportedLocale() ?
ULOC_ACCEPT_VALID : ULOC_ACCEPT_FALLBACK;
}
const char *bestStr = result.getSupportedLocale()->getName();
int32_t bestLength = (int32_t)uprv_strlen(bestStr);
if (bestLength <= capacity) {
uprv_memcpy(dest, bestStr, bestLength);
}
return u_terminateChars(dest, capacity, bestLength, &errorCode);
} else {
if (acceptResult != nullptr) {
*acceptResult = ULOC_ACCEPT_FAILED;
}
return u_terminateChars(dest, capacity, 0, &errorCode);
}
}
} // namespace
U_CAPI int32_t U_EXPORT2
uloc_acceptLanguage(char *result, int32_t resultAvailable,
UAcceptResult *outResult,
const char **acceptList, int32_t acceptListCount,
UEnumeration *availableLocales,
UErrorCode *status) {
if (U_FAILURE(*status)) { return 0; }
if ((result == nullptr ? resultAvailable != 0 : resultAvailable < 0) ||
(acceptList == nullptr ? acceptListCount != 0 : acceptListCount < 0) ||
availableLocales == nullptr) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
LocaleFromTag converter;
Locale::ConvertingIterator<const char **, LocaleFromTag> desiredLocales(
acceptList, acceptList + acceptListCount, converter);
return acceptLanguage(*availableLocales, desiredLocales,
result, resultAvailable, outResult, *status);
}
U_CAPI int32_t U_EXPORT2
uloc_acceptLanguageFromHTTP(char *result, int32_t resultAvailable,
UAcceptResult *outResult,
const char *httpAcceptLanguage,
UEnumeration *availableLocales,
UErrorCode *status) {
if (U_FAILURE(*status)) { return 0; }
if ((result == nullptr ? resultAvailable != 0 : resultAvailable < 0) ||
httpAcceptLanguage == nullptr || availableLocales == nullptr) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
LocalePriorityList list(httpAcceptLanguage, *status);
LocalePriorityList::Iterator desiredLocales = list.iterator();
return acceptLanguage(*availableLocales, desiredLocales,
result, resultAvailable, outResult, *status);
}
#endif // __LOCMATCHER_H__
+1 -1
View File
@@ -133,7 +133,7 @@ LocalePriorityList::LocalePriorityList(StringPiece s, UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) { return; }
Locale locale = Locale(tag.data());
if (locale.isBogus()) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
int32_t weight = WEIGHT_ONE;
+73 -22
View File
@@ -69,7 +69,7 @@ void U_CALLCONV LocaleDistance::initLocaleDistance(UErrorCode &errorCode) {
errorCode = U_MISSING_RESOURCE_ERROR;
return;
}
gLocaleDistance = new LocaleDistance(data);
gLocaleDistance = new LocaleDistance(data, likely);
if (gLocaleDistance == nullptr) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
@@ -83,7 +83,8 @@ const LocaleDistance *LocaleDistance::getSingleton(UErrorCode &errorCode) {
return gLocaleDistance;
}
LocaleDistance::LocaleDistance(const LocaleDistanceData &data) :
LocaleDistance::LocaleDistance(const LocaleDistanceData &data, const XLikelySubtags &likely) :
likelySubtags(likely),
trie(data.distanceTrieBytes),
regionToPartitionsIndex(data.regionToPartitions), partitionArrays(data.partitions),
paradigmLSRs(data.paradigms), paradigmLSRsLength(data.paradigmsLength),
@@ -97,17 +98,19 @@ LocaleDistance::LocaleDistance(const LocaleDistanceData &data) :
// a mere region difference for one desired locale
// is as good as a perfect match for the next following desired locale.
// As of CLDR 36, we have <languageMatch desired="en_*_*" supported="en_*_*" distance="5"/>.
LSR en("en", "Latn", "US");
LSR enGB("en", "Latn", "GB");
LSR en("en", "Latn", "US", LSR::EXPLICIT_LSR);
LSR enGB("en", "Latn", "GB", LSR::EXPLICIT_LSR);
const LSR *p_enGB = &enGB;
defaultDemotionPerDesiredLocale = getBestIndexAndDistance(en, &p_enGB, 1,
50, ULOCMATCH_FAVOR_LANGUAGE) & 0xff;
int32_t indexAndDistance = getBestIndexAndDistance(en, &p_enGB, 1,
shiftDistance(50), ULOCMATCH_FAVOR_LANGUAGE, ULOCMATCH_DIRECTION_WITH_ONE_WAY);
defaultDemotionPerDesiredLocale = getDistanceFloor(indexAndDistance);
}
int32_t LocaleDistance::getBestIndexAndDistance(
const LSR &desired,
const LSR **supportedLSRs, int32_t supportedLSRsLength,
int32_t threshold, ULocMatchFavorSubtag favorSubtag) const {
int32_t shiftedThreshold,
ULocMatchFavorSubtag favorSubtag, ULocMatchDirection direction) const {
BytesTrie iter(trie);
// Look up the desired language only once for all supported LSRs.
// Its "distance" is either a match point value of 0, or a non-match negative value.
@@ -116,6 +119,8 @@ int32_t LocaleDistance::getBestIndexAndDistance(
uint64_t desLangState = desLangDistance >= 0 && supportedLSRsLength > 1 ? iter.getState64() : 0;
// Index of the supported LSR with the lowest distance.
int32_t bestIndex = -1;
// Cached lookup info from XLikelySubtags.compareLikely().
int32_t bestLikelyInfo = -1;
for (int32_t slIndex = 0; slIndex < supportedLSRsLength; ++slIndex) {
const LSR &supported = *supportedLSRs[slIndex];
bool star = false;
@@ -145,6 +150,11 @@ int32_t LocaleDistance::getBestIndexAndDistance(
star = true;
}
U_ASSERT(0 <= distance && distance <= 100);
// Round up the shifted threshold (if fraction bits are not 0)
// for comparison with un-shifted distances until we need fraction bits.
// (If we simply shifted non-zero fraction bits away, then we might ignore a language
// when it's really still a micro distance below the threshold.)
int32_t roundedThreshold = (shiftedThreshold + DISTANCE_FRACTION_MASK) >> DISTANCE_SHIFT;
// We implement "favor subtag" by reducing the language subtag distance
// (unscientifically reducing it to a quarter of the normal value),
// so that the script distance is relatively more important.
@@ -153,7 +163,9 @@ int32_t LocaleDistance::getBestIndexAndDistance(
if (favorSubtag == ULOCMATCH_FAVOR_SCRIPT) {
distance >>= 2;
}
if (distance >= threshold) {
// Let distance == roundedThreshold pass until the tie-breaker logic
// at the end of the loop.
if (distance > roundedThreshold) {
continue;
}
@@ -171,7 +183,7 @@ int32_t LocaleDistance::getBestIndexAndDistance(
scriptDistance &= ~DISTANCE_IS_FINAL;
}
distance += scriptDistance;
if (distance >= threshold) {
if (distance > roundedThreshold) {
continue;
}
@@ -180,8 +192,8 @@ int32_t LocaleDistance::getBestIndexAndDistance(
} else if (star || (flags & DISTANCE_IS_FINAL) != 0) {
distance += defaultRegionDistance;
} else {
int32_t remainingThreshold = threshold - distance;
if (minRegionDistance >= remainingThreshold) {
int32_t remainingThreshold = roundedThreshold - distance;
if (minRegionDistance > remainingThreshold) {
continue;
}
@@ -196,15 +208,51 @@ int32_t LocaleDistance::getBestIndexAndDistance(
partitionsForRegion(supported),
remainingThreshold);
}
if (distance < threshold) {
if (distance == 0) {
return slIndex << 8;
int32_t shiftedDistance = shiftDistance(distance);
if (shiftedDistance == 0) {
// Distinguish between equivalent but originally unequal locales via an
// additional micro distance.
shiftedDistance |= (desired.flags ^ supported.flags);
if (shiftedDistance < shiftedThreshold) {
if (direction != ULOCMATCH_DIRECTION_ONLY_TWO_WAY ||
// Is there also a match when we swap desired/supported?
isMatch(supported, desired, shiftedThreshold, favorSubtag)) {
if (shiftedDistance == 0) {
return slIndex << INDEX_SHIFT;
}
bestIndex = slIndex;
shiftedThreshold = shiftedDistance;
bestLikelyInfo = -1;
}
}
} else {
if (shiftedDistance < shiftedThreshold) {
if (direction != ULOCMATCH_DIRECTION_ONLY_TWO_WAY ||
// Is there also a match when we swap desired/supported?
isMatch(supported, desired, shiftedThreshold, favorSubtag)) {
bestIndex = slIndex;
shiftedThreshold = shiftedDistance;
bestLikelyInfo = -1;
}
} else if (shiftedDistance == shiftedThreshold && bestIndex >= 0) {
if (direction != ULOCMATCH_DIRECTION_ONLY_TWO_WAY ||
// Is there also a match when we swap desired/supported?
isMatch(supported, desired, shiftedThreshold, favorSubtag)) {
bestLikelyInfo = likelySubtags.compareLikely(
supported, *supportedLSRs[bestIndex], bestLikelyInfo);
if ((bestLikelyInfo & 1) != 0) {
// This supported locale matches as well as the previous best match,
// and neither matches perfectly,
// but this one is "more likely" (has more-default subtags).
bestIndex = slIndex;
}
}
}
bestIndex = slIndex;
threshold = distance;
}
}
return bestIndex >= 0 ? (bestIndex << 8) | threshold : 0xffffff00 | ABOVE_THRESHOLD;
return bestIndex >= 0 ?
(bestIndex << INDEX_SHIFT) | shiftedThreshold :
INDEX_NEG_1 | shiftDistance(ABOVE_THRESHOLD);
}
int32_t LocaleDistance::getDesSuppScriptDistance(
@@ -273,7 +321,7 @@ int32_t LocaleDistance::getRegionPartitionsDistance(
d = getFallbackRegionDistance(iter, startState);
star = true;
}
if (d >= threshold) {
if (d > threshold) {
return d;
} else if (regionDistance < d) {
regionDistance = d;
@@ -286,7 +334,7 @@ int32_t LocaleDistance::getRegionPartitionsDistance(
}
} else if (!star) {
int32_t d = getFallbackRegionDistance(iter, startState);
if (d >= threshold) {
if (d > threshold) {
return d;
} else if (regionDistance < d) {
regionDistance = d;
@@ -352,11 +400,14 @@ int32_t LocaleDistance::trieNext(BytesTrie &iter, const char *s, bool wantValue)
}
UBool LocaleDistance::isParadigmLSR(const LSR &lsr) const {
// Linear search for a very short list (length 6 as of 2019).
// If there are many paradigm LSRs we should use a hash set.
// Linear search for a very short list (length 6 as of 2019),
// because we look for equivalence not equality, and
// because it's easy.
// If there are many paradigm LSRs we should use a hash set
// with custom comparator and hasher.
U_ASSERT(paradigmLSRsLength <= 15);
for (int32_t i = 0; i < paradigmLSRsLength; ++i) {
if (lsr == paradigmLSRs[i]) { return true; }
if (lsr.isEquivalentTo(paradigmLSRs[i])) { return true; }
}
return false;
}
+48 -6
View File
@@ -26,19 +26,37 @@ class LocaleDistance final : public UMemory {
public:
static const LocaleDistance *getSingleton(UErrorCode &errorCode);
static int32_t shiftDistance(int32_t distance) {
return distance << DISTANCE_SHIFT;
}
static int32_t getShiftedDistance(int32_t indexAndDistance) {
return indexAndDistance & DISTANCE_MASK;
}
static double getDistanceDouble(int32_t indexAndDistance) {
double shiftedDistance = getShiftedDistance(indexAndDistance);
return shiftedDistance / (1 << DISTANCE_SHIFT);
}
static int32_t getIndex(int32_t indexAndDistance) {
// assert indexAndDistance >= 0;
return indexAndDistance >> INDEX_SHIFT;
}
/**
* Finds the supported LSR with the smallest distance from the desired one.
* Equivalent LSR subtags must be normalized into a canonical form.
*
* <p>Returns the index of the lowest-distance supported LSR in bits 31..8
* <p>Returns the index of the lowest-distance supported LSR in the high bits
* (negative if none has a distance below the threshold),
* and its distance (0..ABOVE_THRESHOLD) in bits 7..0.
* and its distance (0..ABOVE_THRESHOLD) in the low bits.
*/
int32_t getBestIndexAndDistance(const LSR &desired,
const LSR **supportedLSRs, int32_t supportedLSRsLength,
int32_t threshold, ULocMatchFavorSubtag favorSubtag) const;
int32_t getParadigmLSRsLength() const { return paradigmLSRsLength; }
int32_t shiftedThreshold,
ULocMatchFavorSubtag favorSubtag,
ULocMatchDirection direction) const;
UBool isParadigmLSR(const LSR &lsr) const;
@@ -51,12 +69,34 @@ public:
}
private:
LocaleDistance(const LocaleDistanceData &data);
// The distance is shifted left to gain some fraction bits.
static constexpr int32_t DISTANCE_SHIFT = 3;
static constexpr int32_t DISTANCE_FRACTION_MASK = 7;
// 7 bits for 0..100
static constexpr int32_t DISTANCE_INT_SHIFT = 7;
static constexpr int32_t INDEX_SHIFT = DISTANCE_INT_SHIFT + DISTANCE_SHIFT;
static constexpr int32_t DISTANCE_MASK = 0x3ff;
// tic constexpr int32_t MAX_INDEX = 0x1fffff; // avoids sign bit
static constexpr int32_t INDEX_NEG_1 = 0xfffffc00;
static int32_t getDistanceFloor(int32_t indexAndDistance) {
return (indexAndDistance & DISTANCE_MASK) >> DISTANCE_SHIFT;
}
LocaleDistance(const LocaleDistanceData &data, const XLikelySubtags &likely);
LocaleDistance(const LocaleDistance &other) = delete;
LocaleDistance &operator=(const LocaleDistance &other) = delete;
static void initLocaleDistance(UErrorCode &errorCode);
UBool isMatch(const LSR &desired, const LSR &supported,
int32_t shiftedThreshold, ULocMatchFavorSubtag favorSubtag) const {
const LSR *pSupp = &supported;
return getBestIndexAndDistance(
desired, &pSupp, 1,
shiftedThreshold, favorSubtag, ULOCMATCH_DIRECTION_WITH_ONE_WAY) >= 0;
}
static int32_t getDesSuppScriptDistance(BytesTrie &iter, uint64_t startState,
const char *desired, const char *supported);
@@ -79,6 +119,8 @@ private:
return defaultRegionDistance;
}
const XLikelySubtags &likelySubtags;
// The trie maps each dlang+slang+dscript+sscript+dregion+sregion
// (encoded in ASCII with bit 7 set on the last character of each subtag) to a distance.
// There is also a trie value for each subsequence of whole subtags.
+252 -15
View File
@@ -38,6 +38,7 @@
#include "unicode/strenum.h"
#include "unicode/stringpiece.h"
#include "unicode/uloc.h"
#include "unicode/ures.h"
#include "bytesinkutil.h"
#include "charstr.h"
@@ -104,7 +105,6 @@ typedef enum ELocalePos {
U_CFUNC int32_t locale_getKeywords(const char *localeID,
char prev,
char *keywords, int32_t keywordCapacity,
char *values, int32_t valuesCapacity, int32_t *valLen,
UBool valuesToo,
UErrorCode *status);
@@ -184,17 +184,16 @@ Locale *locale_set_default_internal(const char *id, UErrorCode& status) {
canonicalize = TRUE; // always canonicalize host ID
}
char localeNameBuf[512];
if (canonicalize) {
uloc_canonicalize(id, localeNameBuf, sizeof(localeNameBuf)-1, &status);
} else {
uloc_getName(id, localeNameBuf, sizeof(localeNameBuf)-1, &status);
CharString localeNameBuf;
{
CharStringByteSink sink(&localeNameBuf);
if (canonicalize) {
ulocimp_canonicalize(id, sink, &status);
} else {
ulocimp_getName(id, sink, &status);
}
}
localeNameBuf[sizeof(localeNameBuf)-1] = 0; // Force null termination in event of
// a long name filling the buffer.
// (long names are truncated.)
//
if (U_FAILURE(status)) {
return gDefaultLocale;
}
@@ -208,14 +207,14 @@ Locale *locale_set_default_internal(const char *id, UErrorCode& status) {
ucln_common_registerCleanup(UCLN_COMMON_LOCALE, locale_cleanup);
}
Locale *newDefault = (Locale *)uhash_get(gDefaultLocalesHashT, localeNameBuf);
Locale *newDefault = (Locale *)uhash_get(gDefaultLocalesHashT, localeNameBuf.data());
if (newDefault == NULL) {
newDefault = new Locale(Locale::eBOGUS);
if (newDefault == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
return gDefaultLocale;
}
newDefault->init(localeNameBuf, FALSE);
newDefault->init(localeNameBuf.data(), FALSE);
uhash_put(gDefaultLocalesHashT, (char*) newDefault->getName(), newDefault, &status);
if (U_FAILURE(status)) {
return gDefaultLocale;
@@ -509,6 +508,36 @@ Locale::operator==( const Locale& other) const
#define ISASCIIALPHA(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
namespace {
CharString& AppendLSCVE(CharString& out, const char* language, const char* script,
const char* country, const char* variants, const char* extension,
UErrorCode& status) {
out.append(language, status);
if (script && script[0] != '\0') {
out.append('_', status);
out.append(script, status);
}
if (country && country[0] != '\0') {
out.append('_', status);
out.append(country, status);
}
if (variants && variants[0] != '\0') {
if ((script == nullptr || script[0] == '\0') &&
(country == nullptr || country[0] == '\0')) {
out.append('_', status);
}
out.append('_', status);
out.append(variants, status);
}
if (extension && extension[0] != '\0') {
out.append(extension, status);
}
return out;
}
} // namespace
/*This function initializes a Locale from a C locale ID*/
Locale& Locale::init(const char* localeID, UBool canonicalize)
{
@@ -632,6 +661,195 @@ Locale& Locale::init(const char* localeID, UBool canonicalize)
break;
}
if (canonicalize) {
UErrorCode status = U_ZERO_ERROR;
// TODO: Try to use ResourceDataValue and ures_getValueWithFallback() etc.
LocalUResourceBundlePointer metadata(ures_openDirect(NULL, "metadata", &status));
LocalUResourceBundlePointer metadataAlias(ures_getByKey(metadata.getAlias(), "alias", NULL, &status));
// Look up the metadata:alias:language:$key:replacement entries
// key could be one of the following:
// language
// language_Script_REGION
// language_REGION
// language_variant
do {
// The resource structure looks like
// metadata {
// alias {
// language {
// art_lojban {
// replacement{"jbo"}
// }
// ...
// ks_Arab_IN {
// replacement{"ks_IN"}
// }
// ...
// no {
// replacement{"nb"}
// }
// ....
// zh_CN {
// replacement{"zh_Hans_CN"}
// }
// }
// ...
// }
// }
LocalUResourceBundlePointer languageAlias(ures_getByKey(metadataAlias.getAlias(), "language", NULL, &status));
if (U_FAILURE(status))
break;
CharString temp;
// Handle cases of key pattern "language _ variant"
// ex: Map "art_lojban" to "jbo"
const char* variants = getVariant();
if (variants != nullptr && variants[0] != '\0') {
const char* begin = variants;
const char* end = begin;
// We may have multiple variants, need to look at each of
// them.
do {
status = U_ZERO_ERROR;
end = uprv_strchr(begin, '_');
int32_t len = (end == nullptr) ? int32_t(uprv_strlen(begin)) : int32_t(end - begin);
temp.clear().append(getLanguage(), status).append("_", status).append(begin, len, status);
LocalUResourceBundlePointer languageVariantAlias(
ures_getByKey(languageAlias.getAlias(),
temp.data(),
NULL, &status));
temp.clear().appendInvariantChars(
UnicodeString(ures_getStringByKey(languageVariantAlias.getAlias(), "replacement", nullptr, &status)), status);
if (U_SUCCESS(status)) {
CharString newVar;
if (begin != variants) {
newVar.append(variants, static_cast<int32_t>(begin - variants - 1), status);
}
if (end != nullptr) {
if (begin != variants) {
newVar.append("_", status);
}
newVar.append(end + 1, status);
}
Locale l(temp.data());
init(AppendLSCVE(temp.clear(),
l.getLanguage(),
(getScript() != nullptr && getScript()[0] != '\0') ? getScript() : l.getScript(),
(getCountry() != nullptr && getCountry()[0] != '\0') ? getCountry() : l.getCountry(),
newVar.data(),
uprv_strchr(fullName, '@'), status).data(), false);
break;
}
begin = end + 1;
} while (end != nullptr);
} // End of handle language _ variant
// Handle cases of key pattern "language _ Script _ REGION"
// ex: Map "ks_Arab_IN" to "ks_IN"
if (getScript() != nullptr && getScript()[0] != '\0' &&
getCountry() != nullptr && getCountry()[0] != '\0') {
status = U_ZERO_ERROR;
LocalUResourceBundlePointer replacedAlias(
ures_getByKey(languageAlias.getAlias(),
AppendLSCVE(temp.clear(), getLanguage(), getScript(), getCountry(),
nullptr, nullptr, status).data(), NULL, &status));
temp.clear().appendInvariantChars(
UnicodeString(ures_getStringByKey(replacedAlias.getAlias(), "replacement", nullptr, &status)), status);
if (U_SUCCESS(status)) {
Locale l(temp.data());
init(AppendLSCVE(temp.clear(),
l.getLanguage(),
l.getScript(),
l.getCountry(),
getVariant(),
uprv_strchr(fullName, '@'), status).data(), false);
}
} // End of handle language _ Script _ REGION
// Handle cases of key pattern "language _ REGION"
// ex: Map "zh_CN" to "zh_Hans_CN"
if (getCountry() != nullptr && getCountry()[0] != '\0') {
status = U_ZERO_ERROR;
LocalUResourceBundlePointer replacedAlias(
ures_getByKey(languageAlias.getAlias(),
AppendLSCVE(temp.clear(), getLanguage(), nullptr, getCountry(),
nullptr, nullptr, status).data(), NULL, &status));
temp.clear().appendInvariantChars(
UnicodeString(ures_getStringByKey(replacedAlias.getAlias(), "replacement", nullptr, &status)), status);
if (U_SUCCESS(status)) {
Locale l(temp.data());
init(AppendLSCVE(temp.clear(),
l.getLanguage(),
(getScript() != nullptr && getScript()[0] != '\0') ? getScript() : l.getScript(),
l.getCountry(),
getVariant(),
uprv_strchr(fullName, '@'), status).data(), false);
}
} // End of handle "language _ REGION"
// Handle cases of key pattern "language"
// ex: Map "no" to "nb"
{
status = U_ZERO_ERROR;
LocalUResourceBundlePointer replaceLanguageAlias(ures_getByKey(languageAlias.getAlias(), getLanguage(), NULL, &status));
temp.clear().appendInvariantChars(
UnicodeString(ures_getStringByKey(replaceLanguageAlias.getAlias(), "replacement", nullptr, &status)), status);
if (U_SUCCESS(status)) {
Locale l(temp.data());
init(AppendLSCVE(temp.clear(),
l.getLanguage(),
(getScript() != nullptr && getScript()[0] != '\0') ? getScript() : l.getScript(),
(getCountry() != nullptr && getCountry()[0] != '\0') ? getCountry() : l.getCountry(),
getVariant(),
uprv_strchr(fullName, '@'), status).data(), false);
}
} // End of handle "language"
// Look up the metadata:alias:territory:$key:replacement entries
// key is region code.
if (getCountry() != nullptr) {
status = U_ZERO_ERROR;
// The resource structure looks like
// metadata {
// alias {
// ...
// territory: {
// 172 {
// replacement{"RU AM AZ BY GE KG KZ MD TJ TM UA UZ"}
// }
// ...
// 554 {
// replacement{"NZ"}
// }
// }
// }
// }
LocalUResourceBundlePointer territoryAlias(ures_getByKey(metadataAlias.getAlias(), "territory", NULL, &status));
LocalUResourceBundlePointer countryAlias(ures_getByKey(territoryAlias.getAlias(), getCountry(), NULL, &status));
UnicodeString replacements(
ures_getStringByKey(countryAlias.getAlias(), "replacement", nullptr, &status));
if (U_SUCCESS(status)) {
CharString replacedCountry;
int32_t delPos = replacements.indexOf(' ');
if (delPos == -1) {
replacedCountry.appendInvariantChars(replacements, status);
} else {
Locale l(AppendLSCVE(temp.clear(), getLanguage(), nullptr, getScript(),
nullptr, nullptr, status).data());
l.addLikelySubtags(status);
if (replacements.indexOf(UnicodeString(l.getCountry())) != -1) {
replacedCountry.append(l.getCountry(), status);
} else {
replacedCountry.appendInvariantChars(replacements.getBuffer(), delPos, status);
}
}
init(AppendLSCVE(temp.clear(),
getLanguage(),
getScript(),
replacedCountry.data(),
getVariant(),
uprv_strchr(fullName, '@'), status).data(), false);
}
} // End of handle REGION
} while (0);
} // if (canonicalize) {
// successful end of init()
return *this;
} while(0); /*loop doesn't iterate*/
@@ -778,6 +996,25 @@ Locale::minimizeSubtags(UErrorCode& status) {
}
}
void
Locale::canonicalize(UErrorCode& status) {
if (U_FAILURE(status)) {
return;
}
if (isBogus()) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
CharString uncanonicalized(fullName, status);
if (U_FAILURE(status)) {
return;
}
init(uncanonicalized.data(), /*canonicalize=*/TRUE);
if (isBogus()) {
status = U_ILLEGAL_ARGUMENT_ERROR;
}
}
Locale U_EXPORT2
Locale::forLanguageTag(StringPiece tag, UErrorCode& status)
{
@@ -1189,7 +1426,7 @@ Locale::createKeywords(UErrorCode &status) const
const char* assignment = uprv_strchr(fullName, '=');
if(variantStart) {
if(assignment > variantStart) {
int32_t keyLen = locale_getKeywords(variantStart+1, '@', keywords, keywordCapacity, NULL, 0, NULL, FALSE, &status);
int32_t keyLen = locale_getKeywords(variantStart+1, '@', keywords, keywordCapacity, FALSE, &status);
if(U_SUCCESS(status) && keyLen) {
result = new KeywordEnumeration(keywords, keyLen, 0, status);
if (!result) {
@@ -1218,7 +1455,7 @@ Locale::createUnicodeKeywords(UErrorCode &status) const
const char* assignment = uprv_strchr(fullName, '=');
if(variantStart) {
if(assignment > variantStart) {
int32_t keyLen = locale_getKeywords(variantStart+1, '@', keywords, keywordCapacity, NULL, 0, NULL, FALSE, &status);
int32_t keyLen = locale_getKeywords(variantStart+1, '@', keywords, keywordCapacity, FALSE, &status);
if(U_SUCCESS(status) && keyLen) {
result = new UnicodeKeywordEnumeration(keywords, keyLen, 0, status);
if (!result) {
+124 -16
View File
@@ -250,7 +250,8 @@ struct XLikelySubtagsData {
for (int32_t i = 0, j = 0; i < lsrSubtagsLength; i += 3, ++j) {
lsrs[j] = LSR(strings.get(lsrSubtagIndexes[i]),
strings.get(lsrSubtagIndexes[i + 1]),
strings.get(lsrSubtagIndexes[i + 2]));
strings.get(lsrSubtagIndexes[i + 2]),
LSR::IMPLICIT_LSR);
}
if (partitionsLength > 0) {
@@ -275,7 +276,8 @@ struct XLikelySubtagsData {
for (int32_t i = 0, j = 0; i < paradigmSubtagsLength; i += 3, ++j) {
paradigms[j] = LSR(strings.get(paradigmSubtagIndexes[i]),
strings.get(paradigmSubtagIndexes[i + 1]),
strings.get(paradigmSubtagIndexes[i + 2]));
strings.get(paradigmSubtagIndexes[i + 2]),
LSR::DONT_CARE_FLAGS);
}
distanceData.paradigms = paradigms;
}
@@ -383,7 +385,7 @@ LSR XLikelySubtags::makeMaximizedLsrFrom(const Locale &locale, UErrorCode &error
const char *name = locale.getName();
if (uprv_isAtSign(name[0]) && name[1] == 'x' && name[2] == '=') { // name.startsWith("@x=")
// Private use language tag x-subtag-subtag...
return LSR(name, "", "");
return LSR(name, "", "", LSR::EXPLICIT_LSR);
}
return makeMaximizedLsr(locale.getLanguage(), locale.getScript(), locale.getCountry(),
locale.getVariant(), errorCode);
@@ -407,26 +409,31 @@ LSR XLikelySubtags::makeMaximizedLsr(const char *language, const char *script, c
if (region[0] == 'X' && (c1 = region[1]) != 0 && region[2] == 0) {
switch (c1) {
case 'A':
return LSR(PSEUDO_ACCENTS_PREFIX, language, script, region, errorCode);
return LSR(PSEUDO_ACCENTS_PREFIX, language, script, region,
LSR::EXPLICIT_LSR, errorCode);
case 'B':
return LSR(PSEUDO_BIDI_PREFIX, language, script, region, errorCode);
return LSR(PSEUDO_BIDI_PREFIX, language, script, region,
LSR::EXPLICIT_LSR, errorCode);
case 'C':
return LSR(PSEUDO_CRACKED_PREFIX, language, script, region, errorCode);
return LSR(PSEUDO_CRACKED_PREFIX, language, script, region,
LSR::EXPLICIT_LSR, errorCode);
default: // normal locale
break;
}
}
if (variant[0] == 'P' && variant[1] == 'S') {
int32_t lsrFlags = *region == 0 ?
LSR::EXPLICIT_LANGUAGE | LSR::EXPLICIT_SCRIPT : LSR::EXPLICIT_LSR;
if (uprv_strcmp(variant, "PSACCENT") == 0) {
return LSR(PSEUDO_ACCENTS_PREFIX, language, script,
*region == 0 ? "XA" : region, errorCode);
*region == 0 ? "XA" : region, lsrFlags, errorCode);
} else if (uprv_strcmp(variant, "PSBIDI") == 0) {
return LSR(PSEUDO_BIDI_PREFIX, language, script,
*region == 0 ? "XB" : region, errorCode);
*region == 0 ? "XB" : region, lsrFlags, errorCode);
} else if (uprv_strcmp(variant, "PSCRACK") == 0) {
return LSR(PSEUDO_CRACKED_PREFIX, language, script,
*region == 0 ? "XC" : region, errorCode);
*region == 0 ? "XC" : region, lsrFlags, errorCode);
}
// else normal locale
}
@@ -448,7 +455,7 @@ LSR XLikelySubtags::maximize(const char *language, const char *script, const cha
region = "";
}
if (*script != 0 && *region != 0 && *language != 0) {
return LSR(language, script, region); // already maximized
return LSR(language, script, region, LSR::EXPLICIT_LSR); // already maximized
}
uint32_t retainOldMask = 0;
@@ -535,7 +542,7 @@ LSR XLikelySubtags::maximize(const char *language, const char *script, const cha
if (retainOldMask == 0) {
// Quickly return a copy of the lookup-result LSR
// without new allocation of the subtags.
return LSR(result.language, result.script, result.region);
return LSR(result.language, result.script, result.region, result.flags);
}
if ((retainOldMask & 4) == 0) {
language = result.language;
@@ -546,7 +553,108 @@ LSR XLikelySubtags::maximize(const char *language, const char *script, const cha
if ((retainOldMask & 1) == 0) {
region = result.region;
}
return LSR(language, script, region);
// retainOldMask flags = LSR explicit-subtag flags
return LSR(language, script, region, retainOldMask);
}
int32_t XLikelySubtags::compareLikely(const LSR &lsr, const LSR &other, int32_t likelyInfo) const {
// If likelyInfo >= 0:
// likelyInfo bit 1 is set if the previous comparison with lsr
// was for equal language and script.
// Otherwise the scripts differed.
if (uprv_strcmp(lsr.language, other.language) != 0) {
return 0xfffffffc; // negative, lsr not better than other
}
if (uprv_strcmp(lsr.script, other.script) != 0) {
int32_t index;
if (likelyInfo >= 0 && (likelyInfo & 2) == 0) {
index = likelyInfo >> 2;
} else {
index = getLikelyIndex(lsr.language, "");
likelyInfo = index << 2;
}
const LSR &likely = lsrs[index];
if (uprv_strcmp(lsr.script, likely.script) == 0) {
return likelyInfo | 1;
} else {
return likelyInfo & ~1;
}
}
if (uprv_strcmp(lsr.region, other.region) != 0) {
int32_t index;
if (likelyInfo >= 0 && (likelyInfo & 2) != 0) {
index = likelyInfo >> 2;
} else {
index = getLikelyIndex(lsr.language, lsr.region);
likelyInfo = (index << 2) | 2;
}
const LSR &likely = lsrs[index];
if (uprv_strcmp(lsr.region, likely.region) == 0) {
return likelyInfo | 1;
} else {
return likelyInfo & ~1;
}
}
return likelyInfo & ~1; // lsr not better than other
}
// Subset of maximize().
int32_t XLikelySubtags::getLikelyIndex(const char *language, const char *script) const {
if (uprv_strcmp(language, "und") == 0) {
language = "";
}
if (uprv_strcmp(script, "Zzzz") == 0) {
script = "";
}
BytesTrie iter(trie);
uint64_t state;
int32_t value;
// Small optimization: Array lookup for first language letter.
int32_t c0;
if (0 <= (c0 = uprv_lowerOrdinal(language[0])) && c0 <= 25 &&
language[1] != 0 && // language.length() >= 2
(state = trieFirstLetterStates[c0]) != 0) {
value = trieNext(iter.resetToState64(state), language, 1);
} else {
value = trieNext(iter, language, 0);
}
if (value >= 0) {
state = iter.getState64();
} else {
iter.resetToState64(trieUndState); // "und" ("*")
state = 0;
}
if (value > 0) {
// Intermediate or final value from just language.
if (value == SKIP_SCRIPT) {
value = 0;
}
} else {
value = trieNext(iter, script, 0);
if (value >= 0) {
state = iter.getState64();
} else {
if (state == 0) {
iter.resetToState64(trieUndZzzzState); // "und-Zzzz" ("**")
} else {
iter.resetToState64(state);
value = trieNext(iter, "", 0);
U_ASSERT(value >= 0);
state = iter.getState64();
}
}
}
if (value > 0) {
// Final value from just language or language+script.
} else {
value = trieNext(iter, "", 0);
U_ASSERT(value > 0);
}
U_ASSERT(value < lsrsLength);
return value;
}
int32_t XLikelySubtags::trieNext(BytesTrie &iter, const char *s, int32_t i) {
@@ -615,9 +723,9 @@ LSR XLikelySubtags::minimizeSubtags(const char *languageIn, const char *scriptIn
boolean favorRegionOk = false;
if (result.script.equals(value00.script)) { //script is default
if (result.region.equals(value00.region)) {
return new LSR(result.language, "", "");
return new LSR(result.language, "", "", LSR.DONT_CARE_FLAGS);
} else if (fieldToFavor == ULocale.Minimize.FAVOR_REGION) {
return new LSR(result.language, "", result.region);
return new LSR(result.language, "", result.region, LSR.DONT_CARE_FLAGS);
} else {
favorRegionOk = true;
}
@@ -627,9 +735,9 @@ LSR XLikelySubtags::minimizeSubtags(const char *languageIn, const char *scriptIn
// Maybe do later, but for now use the straightforward code.
LSR result2 = maximize(languageIn, scriptIn, "");
if (result2.equals(result)) {
return new LSR(result.language, result.script, "");
return new LSR(result.language, result.script, "", LSR.DONT_CARE_FLAGS);
} else if (favorRegionOk) {
return new LSR(result.language, "", result.region);
return new LSR(result.language, "", result.region, LSR.DONT_CARE_FLAGS);
}
return result;
}
+14
View File
@@ -85,6 +85,18 @@ public:
// VisibleForTesting
LSR makeMaximizedLsrFrom(const Locale &locale, UErrorCode &errorCode) const;
/**
* Tests whether lsr is "more likely" than other.
* For example, fr-Latn-FR is more likely than fr-Latn-CH because
* FR is the default region for fr-Latn.
*
* The likelyInfo caches lookup information between calls.
* The return value is an updated likelyInfo value,
* with bit 0 set if lsr is "more likely".
* The initial value of likelyInfo must be negative.
*/
int32_t compareLikely(const LSR &lsr, const LSR &other, int32_t likelyInfo) const;
// TODO(ICU-20777): Switch Locale/uloc_ likely-subtags API from the old code
// in loclikely.cpp to this new code, including activating this
// minimizeSubtags() function. The LocaleMatcher does not minimize.
@@ -111,6 +123,8 @@ private:
*/
LSR maximize(const char *language, const char *script, const char *region) const;
int32_t getLikelyIndex(const char *language, const char *script) const;
static int32_t trieNext(BytesTrie &iter, const char *s, int32_t i);
UResourceBundle *langInfoBundle;
+21 -8
View File
@@ -14,9 +14,10 @@
U_NAMESPACE_BEGIN
LSR::LSR(char prefix, const char *lang, const char *scr, const char *r, UErrorCode &errorCode) :
LSR::LSR(char prefix, const char *lang, const char *scr, const char *r, int32_t f,
UErrorCode &errorCode) :
language(nullptr), script(nullptr), region(r),
regionIndex(indexForRegion(region)) {
regionIndex(indexForRegion(region)), flags(f) {
if (U_SUCCESS(errorCode)) {
CharString langScript;
langScript.append(prefix, errorCode).append(lang, errorCode).append('\0', errorCode);
@@ -32,7 +33,8 @@ LSR::LSR(char prefix, const char *lang, const char *scr, const char *r, UErrorCo
LSR::LSR(LSR &&other) U_NOEXCEPT :
language(other.language), script(other.script), region(other.region), owned(other.owned),
regionIndex(other.regionIndex), hashCode(other.hashCode) {
regionIndex(other.regionIndex), flags(other.flags),
hashCode(other.hashCode) {
if (owned != nullptr) {
other.language = other.script = "";
other.owned = nullptr;
@@ -50,6 +52,7 @@ LSR &LSR::operator=(LSR &&other) U_NOEXCEPT {
script = other.script;
region = other.region;
regionIndex = other.regionIndex;
flags = other.flags;
owned = other.owned;
hashCode = other.hashCode;
if (owned != nullptr) {
@@ -60,7 +63,7 @@ LSR &LSR::operator=(LSR &&other) U_NOEXCEPT {
return *this;
}
UBool LSR::operator==(const LSR &other) const {
UBool LSR::isEquivalentTo(const LSR &other) const {
return
uprv_strcmp(language, other.language) == 0 &&
uprv_strcmp(script, other.script) == 0 &&
@@ -69,6 +72,16 @@ UBool LSR::operator==(const LSR &other) const {
(regionIndex > 0 || uprv_strcmp(region, other.region) == 0);
}
UBool LSR::operator==(const LSR &other) const {
return
uprv_strcmp(language, other.language) == 0 &&
uprv_strcmp(script, other.script) == 0 &&
regionIndex == other.regionIndex &&
// Compare regions if both are ill-formed (and their indexes are 0).
(regionIndex > 0 || uprv_strcmp(region, other.region) == 0) &&
flags == other.flags;
}
int32_t LSR::indexForRegion(const char *region) {
int32_t c = region[0];
int32_t a = c - '0';
@@ -90,10 +103,10 @@ int32_t LSR::indexForRegion(const char *region) {
LSR &LSR::setHashCode() {
if (hashCode == 0) {
hashCode =
(ustr_hashCharsN(language, static_cast<int32_t>(uprv_strlen(language))) * 37 +
ustr_hashCharsN(script, static_cast<int32_t>(uprv_strlen(script)))) * 37 +
regionIndex;
uint32_t h = ustr_hashCharsN(language, static_cast<int32_t>(uprv_strlen(language)));
h = h * 37 + ustr_hashCharsN(script, static_cast<int32_t>(uprv_strlen(script)));
h = h * 37 + regionIndex;
hashCode = h * 37 + flags;
}
return *this;
}
+13 -3
View File
@@ -16,26 +16,35 @@ U_NAMESPACE_BEGIN
struct LSR final : public UMemory {
static constexpr int32_t REGION_INDEX_LIMIT = 1001 + 26 * 26;
static constexpr int32_t EXPLICIT_LSR = 7;
static constexpr int32_t EXPLICIT_LANGUAGE = 4;
static constexpr int32_t EXPLICIT_SCRIPT = 2;
static constexpr int32_t EXPLICIT_REGION = 1;
static constexpr int32_t IMPLICIT_LSR = 0;
static constexpr int32_t DONT_CARE_FLAGS = 0;
const char *language;
const char *script;
const char *region;
char *owned = nullptr;
/** Index for region, 0 if ill-formed. @see indexForRegion */
int32_t regionIndex = 0;
int32_t flags = 0;
/** Only set for LSRs that will be used in a hash table. */
int32_t hashCode = 0;
LSR() : language("und"), script(""), region("") {}
/** Constructor which aliases all subtag pointers. */
LSR(const char *lang, const char *scr, const char *r) :
LSR(const char *lang, const char *scr, const char *r, int32_t f) :
language(lang), script(scr), region(r),
regionIndex(indexForRegion(region)) {}
regionIndex(indexForRegion(region)), flags(f) {}
/**
* Constructor which prepends the prefix to the language and script,
* copies those into owned memory, and aliases the region.
*/
LSR(char prefix, const char *lang, const char *scr, const char *r, UErrorCode &errorCode);
LSR(char prefix, const char *lang, const char *scr, const char *r, int32_t f,
UErrorCode &errorCode);
LSR(LSR &&other) U_NOEXCEPT;
LSR(const LSR &other) = delete;
inline ~LSR() {
@@ -55,6 +64,7 @@ struct LSR final : public UMemory {
*/
static int32_t indexForRegion(const char *region);
UBool isEquivalentTo(const LSR &other) const;
UBool operator==(const LSR &other) const;
inline UBool operator!=(const LSR &other) const {
+12
View File
@@ -1459,6 +1459,11 @@ static void U_CALLCONV TimeZoneDataDirInitFn(UErrorCode &status) {
const char *dir = "";
#if defined(ICU_TIMEZONE_FILES_DIR_PREFIX_ENV_VAR)
char timezonefilesdir_path_buffer[PATH_MAX];
const char *prefix = getenv(ICU_TIMEZONE_FILES_DIR_PREFIX_ENV_VAR);
#endif
#if U_PLATFORM_HAS_WINUWP_API == 1
// The UWP version does not support the environment variable setting.
@@ -1485,6 +1490,13 @@ static void U_CALLCONV TimeZoneDataDirInitFn(UErrorCode &status) {
dir = "";
}
#if defined(ICU_TIMEZONE_FILES_DIR_PREFIX_ENV_VAR)
if (prefix != NULL) {
snprintf(timezonefilesdir_path_buffer, PATH_MAX, "%s%s", prefix, dir);
dir = timezonefilesdir_path_buffer;
}
#endif
setTimeZoneFilesDir(dir, status);
}
+8 -2
View File
@@ -883,9 +883,15 @@ int32_t RuleBasedBreakIterator::handleNext() {
return lookaheadResult;
}
}
// If we are at the position of the '/' in a look-ahead (hard break) rule;
// record the current position, to be returned later, if the full rule matches.
// TODO: Move this check before the previous check of fAccepting.
// This would enable hard-break rules with no following context.
// But there are line break test failures when trying this. Investigate.
// Issue ICU-20837
int16_t rule = row->fLookAhead;
if (rule != 0) {
// At the position of a '/' in a look-ahead match. Record it.
int32_t pos = (int32_t)UTEXT_GETNATIVEINDEX(&fText);
lookAheadMatches.setPosition(rule, pos);
}
@@ -1111,7 +1117,7 @@ static icu::UInitOnce gRBBIInitOnce = U_INITONCE_INITIALIZER;
* Release all static memory held by breakiterator.
*/
U_CDECL_BEGIN
static UBool U_CALLCONV rbbi_cleanup(void) {
UBool U_CALLCONV rbbi_cleanup(void) {
delete gLanguageBreakFactories;
gLanguageBreakFactories = nullptr;
delete gEmptyString;
+2
View File
@@ -192,6 +192,8 @@ private:
U_NAMESPACE_END
U_CFUNC UBool rbbi_cleanup(void);
#endif /* C++ */
#endif
+13
View File
@@ -161,6 +161,19 @@ RBBIDataHeader *RBBIRuleBuilder::flattenData() {
+ reverseTableSize
+ statusTableSize + trieSize + rulesSize;
#ifdef RBBI_DEBUG
if (fDebugEnv && uprv_strstr(fDebugEnv, "size")) {
RBBIDebugPrintf("Header Size: %8d\n", headerSize);
RBBIDebugPrintf("Forward Table Size: %8d\n", forwardTableSize);
RBBIDebugPrintf("Reverse Table Size: %8d\n", reverseTableSize);
RBBIDebugPrintf("Trie Size: %8d\n", trieSize);
RBBIDebugPrintf("Status Table Size: %8d\n", statusTableSize);
RBBIDebugPrintf("Rules Size: %8d\n", rulesSize);
RBBIDebugPrintf("-----------------------------\n");
RBBIDebugPrintf("Total Size: %8d\n", totalSize);
}
#endif
RBBIDataHeader *data = (RBBIDataHeader *)uprv_malloc(totalSize);
if (data == NULL) {
*fStatus = U_MEMORY_ALLOCATION_ERROR;
+4
View File
@@ -1274,6 +1274,10 @@ void RBBIRuleScanner::scanSet() {
}
int32_t RBBIRuleScanner::numRules() {
return fRuleNum;
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_BREAK_ITERATION */
+2
View File
@@ -73,6 +73,8 @@ public:
// reverse rules,
// and a list of UnicodeSets encountered.
int32_t numRules(); // Return the number of rules that have been seen.
/**
* Return a rules string without unnecessary
* characters.
+105 -50
View File
@@ -18,6 +18,7 @@
#include "unicode/unistr.h"
#include "rbbitblb.h"
#include "rbbirb.h"
#include "rbbiscan.h"
#include "rbbisetb.h"
#include "rbbidata.h"
#include "cstring.h"
@@ -52,6 +53,7 @@ RBBITableBuilder::~RBBITableBuilder() {
}
delete fDStates;
delete fSafeTable;
delete fLookAheadRuleMap;
}
@@ -121,7 +123,7 @@ void RBBITableBuilder::buildForwardTable() {
}
cn->fLeftChild = fTree;
fTree->fParent = cn;
cn->fRightChild = new RBBINode(RBBINode::endMark);
RBBINode *endMarkerNode = cn->fRightChild = new RBBINode(RBBINode::endMark);
// Delete and exit if memory allocation failed.
if (cn->fRightChild == NULL) {
*fStatus = U_MEMORY_ALLOCATION_ERROR;
@@ -164,7 +166,7 @@ void RBBITableBuilder::buildForwardTable() {
// For "chained" rules, modify the followPos sets
//
if (fRB->fChainRules) {
calcChainedFollowPos(fTree);
calcChainedFollowPos(fTree, endMarkerNode);
}
//
@@ -178,6 +180,7 @@ void RBBITableBuilder::buildForwardTable() {
// Build the DFA state transition tables.
//
buildStateTable();
mapLookAheadRules();
flagAcceptingStates();
flagLookAheadStates();
flagTaggedStates();
@@ -401,19 +404,13 @@ void RBBITableBuilder::addRuleRootNodes(UVector *dest, RBBINode *node) {
// to implement rule chaining. NOT described by Aho
//
//-----------------------------------------------------------------------------
void RBBITableBuilder::calcChainedFollowPos(RBBINode *tree) {
void RBBITableBuilder::calcChainedFollowPos(RBBINode *tree, RBBINode *endMarkNode) {
UVector endMarkerNodes(*fStatus);
UVector leafNodes(*fStatus);
int32_t i;
if (U_FAILURE(*fStatus)) {
return;
}
// get a list of all endmarker nodes.
tree->findNodes(&endMarkerNodes, RBBINode::endMark, *fStatus);
// get a list all leaf nodes
tree->findNodes(&leafNodes, RBBINode::leafChar, *fStatus);
if (U_FAILURE(*fStatus)) {
@@ -442,28 +439,26 @@ void RBBITableBuilder::calcChainedFollowPos(RBBINode *tree) {
int32_t startNodeIx;
for (endNodeIx=0; endNodeIx<leafNodes.size(); endNodeIx++) {
RBBINode *tNode = (RBBINode *)leafNodes.elementAt(endNodeIx);
RBBINode *endNode = NULL;
RBBINode *endNode = (RBBINode *)leafNodes.elementAt(endNodeIx);
// Identify leaf nodes that correspond to overall rule match positions.
// These include an endMarkerNode in their followPos sets.
for (i=0; i<endMarkerNodes.size(); i++) {
if (tNode->fFollowPos->contains(endMarkerNodes.elementAt(i))) {
endNode = tNode;
break;
}
}
if (endNode == NULL) {
// node wasn't an end node. Try again with the next.
// These include the endMarkNode in their followPos sets.
//
// Note: do not consider other end marker nodes, those that are added to
// look-ahead rules. These can't chain; a match immediately stops
// further matching. This leaves exactly one end marker node, the one
// at the end of the complete tree.
if (!endNode->fFollowPos->contains(endMarkNode)) {
continue;
}
// We've got a node that can end a match.
// Line Break Specific hack: If this node's val correspond to the $CM char class,
// don't chain from it.
// TODO: Add rule syntax for this behavior, get specifics out of here and
// into the rule file.
// !!LBCMNoChain implementation: If this node's val correspond to
// the Line Break $CM char class, don't chain from it.
// TODO: Remove this. !!LBCMNoChain is deprecated, and is not used
// by any of the standard ICU rules.
if (fRB->fLBCMNoChain) {
UChar32 c = this->fRB->fSetBuilder->getFirstChar(endNode->fVal);
if (c != -1) {
@@ -475,7 +470,6 @@ void RBBITableBuilder::calcChainedFollowPos(RBBINode *tree) {
}
}
// Now iterate over the nodes that can start a match, looking for ones
// with the same char class as our ending node.
RBBINode *startNode;
@@ -705,6 +699,77 @@ ExitBuildSTdeleteall:
}
/**
* mapLookAheadRules
*
*/
void RBBITableBuilder::mapLookAheadRules() {
fLookAheadRuleMap = new UVector32(fRB->fScanner->numRules() + 1, *fStatus);
if (fLookAheadRuleMap == nullptr) {
*fStatus = U_MEMORY_ALLOCATION_ERROR;
}
if (U_FAILURE(*fStatus)) {
return;
}
fLookAheadRuleMap->setSize(fRB->fScanner->numRules() + 1);
int32_t laSlotsInUse = 0;
for (int32_t n=0; n<fDStates->size(); n++) {
RBBIStateDescriptor *sd = (RBBIStateDescriptor *)fDStates->elementAt(n);
int32_t laSlotForState = 0;
// Establish the look-ahead slot for this state, if the state covers
// any look-ahead nodes - corresponding to the '/' in look-ahead rules.
// If any of the look-ahead nodes already have a slot assigned, use it,
// otherwise assign a new one.
bool sawLookAheadNode = false;
for (int32_t ipos=0; ipos<sd->fPositions->size(); ++ipos) {
RBBINode *node = static_cast<RBBINode *>(sd->fPositions->elementAt(ipos));
if (node->fType != RBBINode::NodeType::lookAhead) {
continue;
}
sawLookAheadNode = true;
int32_t ruleNum = node->fVal; // Set when rule was originally parsed.
U_ASSERT(ruleNum < fLookAheadRuleMap->size());
U_ASSERT(ruleNum > 0);
int32_t laSlot = fLookAheadRuleMap->elementAti(ruleNum);
if (laSlot != 0) {
if (laSlotForState == 0) {
laSlotForState = laSlot;
} else {
// TODO: figure out if this can fail, change to setting an error code if so.
U_ASSERT(laSlot == laSlotForState);
}
}
}
if (!sawLookAheadNode) {
continue;
}
if (laSlotForState == 0) {
laSlotForState = ++laSlotsInUse;
}
// For each look ahead node covered by this state,
// set the mapping from the node's rule number to the look ahead slot.
// There can be multiple nodes/rule numbers going to the same la slot.
for (int32_t ipos=0; ipos<sd->fPositions->size(); ++ipos) {
RBBINode *node = static_cast<RBBINode *>(sd->fPositions->elementAt(ipos));
if (node->fType != RBBINode::NodeType::lookAhead) {
continue;
}
int32_t ruleNum = node->fVal; // Set when rule was originally parsed.
int32_t existingVal = fLookAheadRuleMap->elementAti(ruleNum);
(void)existingVal;
U_ASSERT(existingVal == 0 || existingVal == laSlotForState);
fLookAheadRuleMap->setElementAt(laSlotForState, ruleNum);
}
}
}
//-----------------------------------------------------------------------------
//
@@ -744,28 +809,19 @@ void RBBITableBuilder::flagAcceptingStates() {
if (sd->fAccepting==0) {
// State hasn't been marked as accepting yet. Do it now.
sd->fAccepting = endMarker->fVal;
sd->fAccepting = fLookAheadRuleMap->elementAti(endMarker->fVal);
if (sd->fAccepting == 0) {
sd->fAccepting = -1;
}
}
if (sd->fAccepting==-1 && endMarker->fVal != 0) {
// Both lookahead and non-lookahead accepting for this state.
// Favor the look-ahead. Expedient for line break.
// TODO: need a more elegant resolution for conflicting rules.
sd->fAccepting = endMarker->fVal;
// Favor the look-ahead, because a look-ahead match needs to
// immediately stop the run-time engine. First match, not longest.
sd->fAccepting = fLookAheadRuleMap->elementAti(endMarker->fVal);
}
// implicit else:
// if sd->fAccepting already had a value other than 0 or -1, leave it be.
// If the end marker node is from a look-ahead rule, set
// the fLookAhead field for this state also.
if (endMarker->fLookAheadEnd) {
// TODO: don't change value if already set?
// TODO: allow for more than one active look-ahead rule in engine.
// Make value here an index to a side array in engine?
sd->fLookAhead = sd->fAccepting;
}
}
}
}
@@ -792,11 +848,20 @@ void RBBITableBuilder::flagLookAheadStates() {
}
for (i=0; i<lookAheadNodes.size(); i++) {
lookAheadNode = (RBBINode *)lookAheadNodes.elementAt(i);
U_ASSERT(lookAheadNode->fType == RBBINode::NodeType::lookAhead);
for (n=0; n<fDStates->size(); n++) {
RBBIStateDescriptor *sd = (RBBIStateDescriptor *)fDStates->elementAt(n);
if (sd->fPositions->indexOf(lookAheadNode) >= 0) {
sd->fLookAhead = lookAheadNode->fVal;
int32_t positionsIdx = sd->fPositions->indexOf(lookAheadNode);
if (positionsIdx >= 0) {
U_ASSERT(lookAheadNode == sd->fPositions->elementAt(positionsIdx));
int32_t lookaheadSlot = fLookAheadRuleMap->elementAti(lookAheadNode->fVal);
U_ASSERT(sd->fLookAhead == 0 || sd->fLookAhead == lookaheadSlot);
// if (sd->fLookAhead != 0 && sd->fLookAhead != lookaheadSlot) {
// printf("%s:%d Bingo. sd->fLookAhead:%d lookaheadSlot:%d\n",
// __FILE__, __LINE__, sd->fLookAhead, lookaheadSlot);
// }
sd->fLookAhead = lookaheadSlot;
}
}
}
@@ -1204,16 +1269,6 @@ void RBBITableBuilder::removeState(IntPair duplStates) {
}
sd->fDtran->setElementAt(newVal, col);
}
if (sd->fAccepting == duplState) {
sd->fAccepting = keepState;
} else if (sd->fAccepting > duplState) {
sd->fAccepting--;
}
if (sd->fLookAhead == duplState) {
sd->fLookAhead = keepState;
} else if (sd->fLookAhead > duplState) {
sd->fLookAhead--;
}
}
}
+5 -1
View File
@@ -91,9 +91,10 @@ private:
void calcFirstPos(RBBINode *n);
void calcLastPos(RBBINode *n);
void calcFollowPos(RBBINode *n);
void calcChainedFollowPos(RBBINode *n);
void calcChainedFollowPos(RBBINode *n, RBBINode *endMarkNode);
void bofFixup();
void buildStateTable();
void mapLookAheadRules();
void flagAcceptingStates();
void flagLookAheadStates();
void flagTaggedStates();
@@ -175,6 +176,9 @@ private:
/** Synthesized safe table, UVector of UnicodeString, one string per table row. */
UVector *fSafeTable;
/** Map from rule number (fVal in look ahead nodes) to sequential lookahead index. */
UVector32 *fLookAheadRuleMap = nullptr;
RBBITableBuilder(const RBBITableBuilder &other); // forbid copying of this class
RBBITableBuilder &operator=(const RBBITableBuilder &other); // forbid copying of this class
+41
View File
@@ -51,6 +51,47 @@ void StringPiece::set(const char* str) {
length_ = 0;
}
int32_t StringPiece::find(StringPiece needle, int32_t offset) {
if (length() == 0 && needle.length() == 0) {
return 0;
}
// TODO: Improve to be better than O(N^2)?
for (int32_t i = offset; i < length(); i++) {
int32_t j = 0;
for (; j < needle.length(); i++, j++) {
if (data()[i] != needle.data()[j]) {
i -= j;
goto outer_end;
}
}
return i - j;
outer_end: void();
}
return -1;
}
int32_t StringPiece::compare(StringPiece other) {
int32_t i = 0;
for (; i < length(); i++) {
if (i == other.length()) {
// this is longer
return 1;
}
char a = data()[i];
char b = other.data()[i];
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
}
if (i < other.length()) {
// other is longer
return -1;
}
return 0;
}
U_EXPORT UBool U_EXPORT2
operator==(const StringPiece& x, const StringPiece& y) {
int32_t len = x.size();
+5 -3
View File
@@ -18,6 +18,8 @@
* Internal function for sorting arrays.
*/
#include <cstddef>
#include "unicode/utypes.h"
#include "cmemory.h"
#include "uarrsort.h"
@@ -35,7 +37,7 @@ enum {
};
static constexpr int32_t sizeInMaxAlignTs(int32_t sizeInBytes) {
return (sizeInBytes + sizeof(max_align_t) - 1) / sizeof(max_align_t);
return (sizeInBytes + sizeof(std::max_align_t) - 1) / sizeof(std::max_align_t);
}
/* UComparator convenience implementations ---------------------------------- */
@@ -139,7 +141,7 @@ static void
insertionSort(char *array, int32_t length, int32_t itemSize,
UComparator *cmp, const void *context, UErrorCode *pErrorCode) {
icu::MaybeStackArray<max_align_t, sizeInMaxAlignTs(STACK_ITEM_SIZE)> v;
icu::MaybeStackArray<std::max_align_t, sizeInMaxAlignTs(STACK_ITEM_SIZE)> v;
if (sizeInMaxAlignTs(itemSize) > v.getCapacity() &&
v.resize(sizeInMaxAlignTs(itemSize)) == nullptr) {
*pErrorCode = U_MEMORY_ALLOCATION_ERROR;
@@ -233,7 +235,7 @@ static void
quickSort(char *array, int32_t length, int32_t itemSize,
UComparator *cmp, const void *context, UErrorCode *pErrorCode) {
/* allocate two intermediate item variables (x and w) */
icu::MaybeStackArray<max_align_t, sizeInMaxAlignTs(STACK_ITEM_SIZE) * 2> xw;
icu::MaybeStackArray<std::max_align_t, sizeInMaxAlignTs(STACK_ITEM_SIZE) * 2> xw;
if(sizeInMaxAlignTs(itemSize)*2 > xw.getCapacity() &&
xw.resize(sizeInMaxAlignTs(itemSize) * 2) == nullptr) {
*pErrorCode=U_MEMORY_ALLOCATION_ERROR;
+2
View File
@@ -31,6 +31,8 @@
#if U_DEBUG
# include <assert.h>
# define U_ASSERT(exp) assert(exp)
#elif U_CPLUSPLUS_VERSION
# define U_ASSERT(exp) void()
#else
# define U_ASSERT(exp)
#endif
+3 -3
View File
@@ -687,13 +687,13 @@ void toUpper(uint32_t options,
if (change) {
ByteSinkUtil::appendTwoBytes(upper, sink);
if ((data & HAS_EITHER_DIALYTIKA) != 0) {
sink.Append(reinterpret_cast<const char*>(u8"\u0308"), 2); // restore or add a dialytika
sink.AppendU8(u8"\u0308", 2); // restore or add a dialytika
}
if (addTonos) {
sink.Append(reinterpret_cast<const char*>(u8"\u0301"), 2);
sink.AppendU8(u8"\u0301", 2);
}
while (numYpogegrammeni > 0) {
sink.Append(reinterpret_cast<const char*>(u8"\u0399"), 2);
sink.AppendU8(u8"\u0399", 2);
--numYpogegrammeni;
}
}
+2 -2
View File
@@ -478,7 +478,7 @@ setInitialStateFromUnicodeKR(UConverter* converter,UConverterDataISO2022 *myConv
static void U_CALLCONV
_ISO2022Open(UConverter *cnv, UConverterLoadArgs *pArgs, UErrorCode *errorCode){
char myLocale[6]={' ',' ',' ',' ',' ',' '};
char myLocale[7]={' ',' ',' ',' ',' ',' ', '\0'};
cnv->extraInfo = uprv_malloc (sizeof (UConverterDataISO2022));
if(cnv->extraInfo != NULL) {
@@ -493,7 +493,7 @@ _ISO2022Open(UConverter *cnv, UConverterLoadArgs *pArgs, UErrorCode *errorCode){
myConverterData->currentType = ASCII1;
cnv->fromUnicodeStatus =FALSE;
if(pArgs->locale){
uprv_strncpy(myLocale, pArgs->locale, sizeof(myLocale));
uprv_strncpy(myLocale, pArgs->locale, sizeof(myLocale)-1);
}
version = pArgs->options & UCNV_OPTIONS_VERSION_MASK;
myConverterData->version = version;
+2 -2
View File
@@ -866,7 +866,7 @@ getCurrencyNameCount(const char* loc, int32_t* total_currency_name_count, int32_
*total_currency_name_count = 0;
*total_currency_symbol_count = 0;
const UChar* s = NULL;
char locale[ULOC_FULLNAME_CAPACITY];
char locale[ULOC_FULLNAME_CAPACITY] = "";
uprv_strcpy(locale, loc);
const icu::Hashtable *currencySymbolsEquiv = getCurrSymbolsEquiv();
for (;;) {
@@ -941,7 +941,7 @@ collectCurrencyNames(const char* locale,
// Look up the Currencies resource for the given locale.
UErrorCode ec2 = U_ZERO_ERROR;
char loc[ULOC_FULLNAME_CAPACITY];
char loc[ULOC_FULLNAME_CAPACITY] = "";
uloc_getName(locale, loc, sizeof(loc), &ec2);
if (U_FAILURE(ec2) || ec2 == U_STRING_NOT_TERMINATED_WARNING) {
ec = U_ILLEGAL_ARGUMENT_ERROR;
+269 -549
View File
File diff suppressed because it is too large. Load diff
+24 -3
View File
@@ -1110,6 +1110,19 @@ _appendRegionToLanguageTag(const char* localeID, icu::ByteSink& sink, UBool stri
}
}
static void _sortVariants(VariantListEntry* first) {
for (VariantListEntry* var1 = first; var1 != NULL; var1 = var1->next) {
for (VariantListEntry* var2 = var1->next; var2 != NULL; var2 = var2->next) {
// Swap var1->variant and var2->variant.
if (uprv_compareInvCharsAsAscii(var1->variant, var2->variant) > 0) {
const char* temp = var1->variant;
var1->variant = var2->variant;
var2->variant = temp;
}
}
}
}
static void
_appendVariantsToLanguageTag(const char* localeID, icu::ByteSink& sink, UBool strict, UBool *hadPosix, UErrorCode* status) {
char buf[ULOC_FULLNAME_CAPACITY];
@@ -1199,6 +1212,9 @@ _appendVariantsToLanguageTag(const char* localeID, icu::ByteSink& sink, UBool st
if (varFirst != NULL) {
int32_t varLen;
/* per UTS35, we should sort the variants */
_sortVariants(varFirst);
/* write out validated/normalized variants to the target */
var = varFirst;
while (var != NULL) {
@@ -1492,8 +1508,11 @@ _appendKeywordsToLanguageTag(const char* localeID, icu::ByteSink& sink, UBool st
} else {
sink.Append("-", 1);
sink.Append(ext->key, static_cast<int32_t>(uprv_strlen(ext->key)));
sink.Append("-", 1);
sink.Append(ext->value, static_cast<int32_t>(uprv_strlen(ext->value)));
if (uprv_strcmp(ext->value, "true") != 0 &&
uprv_strcmp(ext->value, "yes") != 0) {
sink.Append("-", 1);
sink.Append(ext->value, static_cast<int32_t>(uprv_strlen(ext->value)));
}
}
}
}
@@ -1662,7 +1681,7 @@ _appendLDMLExtensionAsKeywords(const char* ldmlext, ExtensionListEntry** appendT
const char *pKey = NULL; /* LDML key */
const char *pType = NULL; /* LDML type */
char bcpKeyBuf[9]; /* BCP key length is always 2 for now */
char bcpKeyBuf[3]; /* BCP key length is always 2 for now */
U_ASSERT(pBcpKey != NULL);
@@ -1671,6 +1690,7 @@ _appendLDMLExtensionAsKeywords(const char* ldmlext, ExtensionListEntry** appendT
*status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
U_ASSERT(bcpKeyLen <= 2);
uprv_strncpy(bcpKeyBuf, pBcpKey, bcpKeyLen);
bcpKeyBuf[bcpKeyLen] = 0;
@@ -2822,6 +2842,7 @@ ulocimp_forLanguageTag(const char* langtag,
}
/* variants */
_sortVariants(lt.getAlias()->variants);
n = ultag_getVariantsSize(lt.getAlias());
if (n > 0) {
if (noRegion) {
+15
View File
@@ -62,6 +62,21 @@ ulocimp_getCountry(const char *localeID,
char *country, int32_t countryCapacity,
const char **pEnd);
U_STABLE void U_EXPORT2
ulocimp_getName(const char* localeID,
icu::ByteSink& sink,
UErrorCode* err);
U_STABLE void U_EXPORT2
ulocimp_getBaseName(const char* localeID,
icu::ByteSink& sink,
UErrorCode* err);
U_STABLE void U_EXPORT2
ulocimp_canonicalize(const char* localeID,
icu::ByteSink& sink,
UErrorCode* err);
/**
* Writes a well-formed language tag for this locale ID.
*
Vendored Executable → Regular
View File
File mode changed.
+2 -1
View File
@@ -1519,7 +1519,8 @@ U_CAPI UChar32 U_EXPORT2
u_charFromName(UCharNameChoice nameChoice,
const char *name,
UErrorCode *pErrorCode) {
char upper[120], lower[120];
char upper[120] = {0};
char lower[120] = {0};
FindName findName;
AlgorithmicRange *algRange;
uint32_t *p;
+34
View File
@@ -71,6 +71,40 @@ public:
*/
virtual void Append(const char* bytes, int32_t n) = 0;
#ifndef U_HIDE_DRAFT_API
/**
* Appends n bytes to this. Same as Append().
* Call AppendU8() with u8"string literals" which are const char * in C++11
* but const char8_t * in C++20.
* If the compiler does support char8_t as a distinct type,
* then an AppendU8() overload for that is defined and will be chosen.
*
* @param bytes the pointer to the bytes
* @param n the number of bytes; must be non-negative
* @draft ICU 67
*/
inline void AppendU8(const char* bytes, int32_t n) {
Append(bytes, n);
}
#if defined(__cpp_char8_t) || defined(U_IN_DOXYGEN)
/**
* Appends n bytes to this. Same as Append() but for a const char8_t * pointer.
* Call AppendU8() with u8"string literals" which are const char * in C++11
* but const char8_t * in C++20.
* If the compiler does support char8_t as a distinct type,
* then this AppendU8() overload for that is defined and will be chosen.
*
* @param bytes the pointer to the bytes
* @param n the number of bytes; must be non-negative
* @draft ICU 67
*/
inline void AppendU8(const char8_t* bytes, int32_t n) {
Append(reinterpret_cast<const char*>(bytes), n);
}
#endif
#endif // U_HIDE_DRAFT_API
/**
* Returns a writable buffer for appending and writes the buffer's capacity to
* *result_capacity. Guarantees *result_capacity>=min_capacity.
+16 -19
View File
@@ -12,7 +12,6 @@
#include "unicode/stringpiece.h"
#include "unicode/uobject.h"
#ifndef U_HIDE_DRAFT_API
/**
* \file
* \brief C++ API: Builder API for Locale
@@ -57,7 +56,7 @@ class CharString;
* UErrorCode, then track the error of the validation of the input parameter
* into the internal UErrorCode.
*
* @draft ICU 64
* @stable ICU 64
*/
class U_COMMON_API LocaleBuilder : public UObject {
public:
@@ -66,13 +65,13 @@ public:
* fields, extensions, and private use information is the
* empty string.
*
* @draft ICU 64
* @stable ICU 64
*/
LocaleBuilder();
/**
* Destructor
* @draft ICU 64
* @stable ICU 64
*/
virtual ~LocaleBuilder();
@@ -86,7 +85,7 @@ public:
* @param locale the locale
* @return This builder.
*
* @draft ICU 64
* @stable ICU 64
*/
LocaleBuilder& setLocale(const Locale& locale);
@@ -104,7 +103,7 @@ public:
* @param tag the language tag, defined as
* [unicode_locale_id](http://www.unicode.org/reports/tr35/tr35.html#unicode_locale_id).
* @return This builder.
* @draft ICU 64
* @stable ICU 64
*/
LocaleBuilder& setLanguageTag(StringPiece tag);
@@ -119,7 +118,7 @@ public:
*
* @param language the language
* @return This builder.
* @draft ICU 64
* @stable ICU 64
*/
LocaleBuilder& setLanguage(StringPiece language);
@@ -135,7 +134,7 @@ public:
*
* @param script the script
* @return This builder.
* @draft ICU 64
* @stable ICU 64
*/
LocaleBuilder& setScript(StringPiece script);
@@ -154,7 +153,7 @@ public:
*
* @param region the region
* @return This builder.
* @draft ICU 64
* @stable ICU 64
*/
LocaleBuilder& setRegion(StringPiece region);
@@ -175,7 +174,7 @@ public:
*
* @param variant the variant
* @return This builder.
* @draft ICU 64
* @stable ICU 64
*/
LocaleBuilder& setVariant(StringPiece variant);
@@ -196,7 +195,7 @@ public:
* @param key the extension key
* @param value the extension value
* @return This builder.
* @draft ICU 64
* @stable ICU 64
*/
LocaleBuilder& setExtension(char key, StringPiece value);
@@ -216,7 +215,7 @@ public:
* @param key the Unicode locale key
* @param type the Unicode locale type
* @return This builder.
* @draft ICU 64
* @stable ICU 64
*/
LocaleBuilder& setUnicodeLocaleKeyword(
StringPiece key, StringPiece type);
@@ -229,7 +228,7 @@ public:
*
* @param attribute the attribute
* @return This builder.
* @draft ICU 64
* @stable ICU 64
*/
LocaleBuilder& addUnicodeLocaleAttribute(StringPiece attribute);
@@ -242,7 +241,7 @@ public:
*
* @param attribute the attribute
* @return This builder.
* @draft ICU 64
* @stable ICU 64
*/
LocaleBuilder& removeUnicodeLocaleAttribute(StringPiece attribute);
@@ -251,7 +250,7 @@ public:
* <p>This method clears the internal UErrorCode.
*
* @return this builder
* @draft ICU 64
* @stable ICU 64
*/
LocaleBuilder& clear();
@@ -260,7 +259,7 @@ public:
* Language, script, region and variant are unchanged.
*
* @return this builder
* @draft ICU 64
* @stable ICU 64
*/
LocaleBuilder& clearExtensions();
@@ -275,7 +274,7 @@ public:
* the same builder to build more locales.
*
* @return a new Locale
* @draft ICU 64
* @stable ICU 64
*/
Locale build(UErrorCode& status);
@@ -308,8 +307,6 @@ private:
U_NAMESPACE_END
#endif // U_HIDE_DRAFT_API
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __LOCALEBUILDER_H__
+65 -5
View File
@@ -20,12 +20,12 @@
* \brief C++ API: Locale matcher: User's desired locales vs. application's supported locales.
*/
#ifndef U_HIDE_DRAFT_API
#ifndef U_FORCE_HIDE_DRAFT_API
/**
* Builder option for whether the language subtag or the script subtag is most important.
*
* @see Builder#setFavorSubtag(FavorSubtag)
* @see Builder#setFavorSubtag(ULocMatchFavorSubtag)
* @draft ICU 65
*/
enum ULocMatchFavorSubtag {
@@ -51,7 +51,7 @@ typedef enum ULocMatchFavorSubtag ULocMatchFavorSubtag;
* Builder option for whether all desired locales are treated equally or
* earlier ones are preferred.
*
* @see Builder#setDemotionPerDesiredLocale(Demotion)
* @see Builder#setDemotionPerDesiredLocale(ULocMatchDemotion)
* @draft ICU 65
*/
enum ULocMatchDemotion {
@@ -93,6 +93,42 @@ enum ULocMatchDemotion {
typedef enum ULocMatchDemotion ULocMatchDemotion;
#endif
/**
* Builder option for whether to include or ignore one-way (fallback) match data.
* The LocaleMatcher uses CLDR languageMatch data which includes fallback (oneway=true) entries.
* Sometimes it is desirable to ignore those.
*
* <p>For example, consider a web application with the UI in a given language,
* with a link to another, related web app.
* The link should include the UI language, and the target server may also use
* the client’s Accept-Language header data.
* The target server has its own list of supported languages.
* One may want to favor UI language consistency, that is,
* if there is a decent match for the original UI language, we want to use it,
* but not if it is merely a fallback.
*
* @see Builder#setDirection(ULocMatchDirection)
* @draft ICU 67
*/
enum ULocMatchDirection {
/**
* Locale matching includes one-way matches such as Breton→French. (default)
*
* @draft ICU 67
*/
ULOCMATCH_DIRECTION_WITH_ONE_WAY,
/**
* Locale matching limited to two-way matches including e.g. Danish↔Norwegian
* but ignoring one-way matches.
*
* @draft ICU 67
*/
ULOCMATCH_DIRECTION_ONLY_TWO_WAY
};
#ifndef U_IN_DOXYGEN
typedef enum ULocMatchDirection ULocMatchDirection;
#endif
struct UHashtable;
U_NAMESPACE_BEGIN
@@ -182,6 +218,7 @@ public:
*/
Result &operator=(Result &&src) U_NOEXCEPT;
#ifndef U_HIDE_DRAFT_API
/**
* Returns the best-matching desired locale.
* nullptr if the list of desired locales is empty or if none matched well enough.
@@ -236,6 +273,7 @@ public:
* @draft ICU 65
*/
Locale makeResolvedLocale(UErrorCode &errorCode) const;
#endif // U_HIDE_DRAFT_API
private:
Result(const Locale *desired, const Locale *supported,
@@ -298,6 +336,7 @@ public:
*/
Builder &operator=(Builder &&src) U_NOEXCEPT;
#ifndef U_HIDE_DRAFT_API
/**
* Parses an Accept-Language string
* (<a href="https://tools.ietf.org/html/rfc2616#section-14.4">RFC 2616 Section 14.4</a>),
@@ -412,6 +451,21 @@ public:
*/
Builder &setDemotionPerDesiredLocale(ULocMatchDemotion demotion);
/**
* Option for whether to include or ignore one-way (fallback) match data.
* By default, they are included.
*
* @param direction the match direction to set.
* @return this Builder object
* @draft ICU 67
*/
Builder &setDirection(ULocMatchDirection direction) {
if (U_SUCCESS(errorCode_)) {
direction_ = direction;
}
return *this;
}
/**
* Sets the UErrorCode if an error occurred while setting parameters.
* Preserves older error codes in the outErrorCode.
@@ -435,6 +489,7 @@ public:
* @draft ICU 65
*/
LocaleMatcher build(UErrorCode &errorCode) const;
#endif // U_HIDE_DRAFT_API
private:
friend class LocaleMatcher;
@@ -451,6 +506,7 @@ public:
ULocMatchDemotion demotion_ = ULOCMATCH_DEMOTION_REGION;
Locale *defaultLocale_ = nullptr;
ULocMatchFavorSubtag favor_ = ULOCMATCH_FAVOR_LANGUAGE;
ULocMatchDirection direction_ = ULOCMATCH_DIRECTION_WITH_ONE_WAY;
};
// FYI No public LocaleMatcher constructors in C++; use the Builder.
@@ -479,6 +535,7 @@ public:
*/
LocaleMatcher &operator=(LocaleMatcher &&src) U_NOEXCEPT;
#ifndef U_HIDE_DRAFT_API
/**
* Returns the supported locale which best matches the desired locale.
*
@@ -546,6 +603,7 @@ public:
* @draft ICU 65
*/
Result getBestMatchResult(Locale::Iterator &desiredLocales, UErrorCode &errorCode) const;
#endif // U_HIDE_DRAFT_API
#ifndef U_HIDE_INTERNAL_API
/**
@@ -574,6 +632,8 @@ private:
LocaleMatcher(const LocaleMatcher &other) = delete;
LocaleMatcher &operator=(const LocaleMatcher &other) = delete;
int32_t putIfAbsent(const LSR &lsr, int32_t i, int32_t suppLength, UErrorCode &errorCode);
int32_t getBestSuppIndex(LSR desiredLSR, LocaleLsrIterator *remainingIter, UErrorCode &errorCode) const;
const XLikelySubtags &likelySubtags;
@@ -581,6 +641,7 @@ private:
int32_t thresholdDistance;
int32_t demotionPerDesiredLocale;
ULocMatchFavorSubtag favorSubtag;
ULocMatchDirection direction;
// These are in input order.
const Locale ** supportedLocales;
@@ -595,11 +656,10 @@ private:
int32_t supportedLSRsLength;
Locale *ownedDefaultLocale;
const Locale *defaultLocale;
int32_t defaultLocaleIndex;
};
U_NAMESPACE_END
#endif // U_HIDE_DRAFT_API
#endif // U_FORCE_HIDE_DRAFT_API
#endif // U_SHOW_CPLUSPLUS_API
#endif // __LOCALEMATCHER_H__
+6 -18
View File
@@ -225,7 +225,6 @@ public:
src.ptr=NULL;
}
#ifndef U_HIDE_DRAFT_API
/**
* Constructs a LocalPointer from a C++11 std::unique_ptr.
* The LocalPointer steals the object owned by the std::unique_ptr.
@@ -234,11 +233,10 @@ public:
* in a local variable, you must use std::move.
*
* @param p The std::unique_ptr from which the pointer will be stolen.
* @draft ICU 64
* @stable ICU 64
*/
explicit LocalPointer(std::unique_ptr<T> &&p)
: LocalPointerBase<T>(p.release()) {}
#endif /* U_HIDE_DRAFT_API */
/**
* Destructor deletes the object it owns.
@@ -261,20 +259,18 @@ public:
return *this;
}
#ifndef U_HIDE_DRAFT_API
/**
* Move-assign from an std::unique_ptr to this LocalPointer.
* Steals the pointer from the std::unique_ptr.
*
* @param p The std::unique_ptr from which the pointer will be stolen.
* @return *this
* @draft ICU 64
* @stable ICU 64
*/
LocalPointer<T> &operator=(std::unique_ptr<T> &&p) U_NOEXCEPT {
adoptInstead(p.release());
return *this;
}
#endif /* U_HIDE_DRAFT_API */
/**
* Swap pointers.
@@ -332,7 +328,6 @@ public:
}
}
#ifndef U_HIDE_DRAFT_API
/**
* Conversion operator to a C++11 std::unique_ptr.
* Disowns the object and gives it to the returned std::unique_ptr.
@@ -342,12 +337,11 @@ public:
*
* @return An std::unique_ptr owning the pointer previously owned by this
* icu::LocalPointer.
* @draft ICU 64
* @stable ICU 64
*/
operator std::unique_ptr<T> () && {
return std::unique_ptr<T>(LocalPointerBase<T>::orphan());
}
#endif /* U_HIDE_DRAFT_API */
};
/**
@@ -406,7 +400,6 @@ public:
src.ptr=NULL;
}
#ifndef U_HIDE_DRAFT_API
/**
* Constructs a LocalArray from a C++11 std::unique_ptr of an array type.
* The LocalPointer steals the array owned by the std::unique_ptr.
@@ -415,11 +408,10 @@ public:
* in a local variable, you must use std::move.
*
* @param p The std::unique_ptr from which the array will be stolen.
* @draft ICU 64
* @stable ICU 64
*/
explicit LocalArray(std::unique_ptr<T[]> &&p)
: LocalPointerBase<T>(p.release()) {}
#endif /* U_HIDE_DRAFT_API */
/**
* Destructor deletes the array it owns.
@@ -442,20 +434,18 @@ public:
return *this;
}
#ifndef U_HIDE_DRAFT_API
/**
* Move-assign from an std::unique_ptr to this LocalPointer.
* Steals the array from the std::unique_ptr.
*
* @param p The std::unique_ptr from which the array will be stolen.
* @return *this
* @draft ICU 64
* @stable ICU 64
*/
LocalArray<T> &operator=(std::unique_ptr<T[]> &&p) U_NOEXCEPT {
adoptInstead(p.release());
return *this;
}
#endif /* U_HIDE_DRAFT_API */
/**
* Swap pointers.
@@ -521,7 +511,6 @@ public:
*/
T &operator[](ptrdiff_t i) const { return LocalPointerBase<T>::ptr[i]; }
#ifndef U_HIDE_DRAFT_API
/**
* Conversion operator to a C++11 std::unique_ptr.
* Disowns the object and gives it to the returned std::unique_ptr.
@@ -531,12 +520,11 @@ public:
*
* @return An std::unique_ptr owning the pointer previously owned by this
* icu::LocalPointer.
* @draft ICU 64
* @stable ICU 64
*/
operator std::unique_ptr<T[]> () && {
return std::unique_ptr<T[]>(LocalPointerBase<T>::orphan());
}
#endif /* U_HIDE_DRAFT_API */
};
/**
+11 -1
View File
@@ -448,7 +448,7 @@ public:
/**
* Creates a locale from the given string after canonicalizing
* the string by calling uloc_canonicalize().
* the string according to CLDR by calling uloc_canonicalize().
* @param name the locale ID to create from. Must not be NULL.
* @return a new locale object corresponding to the given name
* @stable ICU 3.0
@@ -567,6 +567,16 @@ public:
*/
void minimizeSubtags(UErrorCode& status);
#ifndef U_HIDE_DRAFT_API
/**
* Canonicalize the locale ID of this object according to CLDR.
* @param status the status code
* @draft ICU 67
* @see createCanonical
*/
void canonicalize(UErrorCode& status);
#endif // U_HIDE_DRAFT_API
/**
* Gets the list of keywords for the specified locale.
*
+1 -1
View File
@@ -828,7 +828,7 @@ namespace std {
# define U_EXPORT
#endif
/* U_CALLCONV is releated to U_EXPORT2 */
/* U_CALLCONV is related to U_EXPORT2 */
#ifdef U_EXPORT2
/* Use the predefined value. */
#elif defined(_MSC_VER)
+102 -6
View File
@@ -67,19 +67,50 @@ class U_COMMON_API StringPiece : public UMemory {
* Default constructor, creates an empty StringPiece.
* @stable ICU 4.2
*/
StringPiece() : ptr_(NULL), length_(0) { }
StringPiece() : ptr_(nullptr), length_(0) { }
/**
* Constructs from a NUL-terminated const char * pointer.
* @param str a NUL-terminated const char * pointer
* @stable ICU 4.2
*/
StringPiece(const char* str);
#ifndef U_HIDE_DRAFT_API
#if defined(__cpp_char8_t) || defined(U_IN_DOXYGEN)
/**
* Constructs from a NUL-terminated const char8_t * pointer.
* @param str a NUL-terminated const char8_t * pointer
* @draft ICU 67
*/
StringPiece(const char8_t* str) : StringPiece(reinterpret_cast<const char*>(str)) {}
#endif
/**
* Constructs an empty StringPiece.
* Needed for type disambiguation from multiple other overloads.
* @param p nullptr
* @draft ICU 67
*/
StringPiece(std::nullptr_t p) : ptr_(p), length_(0) {}
#endif // U_HIDE_DRAFT_API
/**
* Constructs from a std::string.
* @stable ICU 4.2
*/
StringPiece(const std::string& str)
: ptr_(str.data()), length_(static_cast<int32_t>(str.size())) { }
#ifndef U_HIDE_DRAFT_API
#if defined(__cpp_lib_char8_t) || defined(U_IN_DOXYGEN)
/**
* Constructs from a std::u8string.
* @draft ICU 67
*/
StringPiece(const std::u8string& str)
: ptr_(reinterpret_cast<const char*>(str.data())),
length_(static_cast<int32_t>(str.size())) { }
#endif
#endif // U_HIDE_DRAFT_API
#ifndef U_HIDE_DRAFT_API
/**
* Constructs from some other implementation of a string piece class, from any
@@ -88,7 +119,7 @@ class U_COMMON_API StringPiece : public UMemory {
* \code{.cpp}
*
* struct OtherStringPieceClass {
* const char* data();
* const char* data(); // or const char8_t*
* size_t size();
* };
*
@@ -97,16 +128,25 @@ class U_COMMON_API StringPiece : public UMemory {
* The other string piece class will typically be std::string_view from C++17
* or absl::string_view from Abseil.
*
* Starting with C++20, data() may also return a const char8_t* pointer,
* as from std::u8string_view.
*
* @param str the other string piece
* @draft ICU 65
*/
template <typename T,
typename = typename std::enable_if<
std::is_same<decltype(T().data()), const char*>::value &&
(std::is_same<decltype(T().data()), const char*>::value
#if defined(__cpp_char8_t)
|| std::is_same<decltype(T().data()), const char8_t*>::value
#endif
) &&
std::is_same<decltype(T().size()), size_t>::value>::type>
StringPiece(T str)
: ptr_(str.data()), length_(static_cast<int32_t>(str.size())) {}
: ptr_(reinterpret_cast<const char*>(str.data())),
length_(static_cast<int32_t>(str.size())) {}
#endif // U_HIDE_DRAFT_API
/**
* Constructs from a const char * pointer and a specified length.
* @param offset a const char * pointer (need not be terminated)
@@ -114,6 +154,19 @@ class U_COMMON_API StringPiece : public UMemory {
* @stable ICU 4.2
*/
StringPiece(const char* offset, int32_t len) : ptr_(offset), length_(len) { }
#ifndef U_HIDE_DRAFT_API
#if defined(__cpp_char8_t) || defined(U_IN_DOXYGEN)
/**
* Constructs from a const char8_t * pointer and a specified length.
* @param str a const char8_t * pointer (need not be terminated)
* @param len the length of the string; must be non-negative
* @draft ICU 67
*/
StringPiece(const char8_t* str, int32_t len) :
StringPiece(reinterpret_cast<const char*>(str), len) {}
#endif
#endif // U_HIDE_DRAFT_API
/**
* Substring of another StringPiece.
* @param x the other StringPiece
@@ -132,7 +185,7 @@ class U_COMMON_API StringPiece : public UMemory {
StringPiece(const StringPiece& x, int32_t pos, int32_t len);
/**
* Returns the string pointer. May be NULL if it is empty.
* Returns the string pointer. May be nullptr if it is empty.
*
* data() may return a pointer to a buffer with embedded NULs, and the
* returned buffer may or may not be null terminated. Therefore it is
@@ -165,7 +218,7 @@ class U_COMMON_API StringPiece : public UMemory {
* Sets to an empty string.
* @stable ICU 4.2
*/
void clear() { ptr_ = NULL; length_ = 0; }
void clear() { ptr_ = nullptr; length_ = 0; }
/**
* Reset the stringpiece to refer to new data.
@@ -182,6 +235,29 @@ class U_COMMON_API StringPiece : public UMemory {
*/
void set(const char* str);
#ifndef U_HIDE_DRAFT_API
#if defined(__cpp_char8_t) || defined(U_IN_DOXYGEN)
/**
* Resets the stringpiece to refer to new data.
* @param xdata pointer the new string data. Need not be NUL-terminated.
* @param len the length of the new data
* @draft ICU 67
*/
inline void set(const char8_t* xdata, int32_t len) {
set(reinterpret_cast<const char*>(xdata), len);
}
/**
* Resets the stringpiece to refer to new data.
* @param str a pointer to a NUL-terminated string.
* @draft ICU 67
*/
inline void set(const char8_t* str) {
set(reinterpret_cast<const char*>(str));
}
#endif
#endif // U_HIDE_DRAFT_API
/**
* Removes the first n string units.
* @param n prefix length, must be non-negative and <=length()
@@ -212,6 +288,26 @@ class U_COMMON_API StringPiece : public UMemory {
}
}
#ifndef U_HIDE_DRAFT_API
/**
* Searches the StringPiece for the given search string (needle);
* @param needle The string for which to search.
* @param offset Where to start searching within this string (haystack).
* @return The offset of needle in haystack, or -1 if not found.
* @draft ICU 67
*/
int32_t find(StringPiece needle, int32_t offset);
/**
* Compares this StringPiece with the other StringPiece, with semantics
* similar to std::string::compare().
* @param other The string to compare to.
* @return below zero if this < other; above zero if this > other; 0 if this == other.
* @draft ICU 67
*/
int32_t compare(StringPiece other);
#endif // U_HIDE_DRAFT_API
/**
* Maximum integer, used as a default value for substring methods.
* @stable ICU 4.2
+30 -9
View File
@@ -1034,29 +1034,45 @@ uloc_getLineOrientation(const char* localeId,
UErrorCode *status);
/**
* enums for the 'outResult' parameter return value
* Output values which uloc_acceptLanguage() writes to the 'outResult' parameter.
*
* @see uloc_acceptLanguageFromHTTP
* @see uloc_acceptLanguage
* @stable ICU 3.2
*/
typedef enum {
ULOC_ACCEPT_FAILED = 0, /* No exact match was found. */
ULOC_ACCEPT_VALID = 1, /* An exact match was found. */
ULOC_ACCEPT_FALLBACK = 2 /* A fallback was found, for example,
Accept list contained 'ja_JP'
which matched available locale 'ja'. */
/**
* No exact match was found.
* @stable ICU 3.2
*/
ULOC_ACCEPT_FAILED = 0,
/**
* An exact match was found.
* @stable ICU 3.2
*/
ULOC_ACCEPT_VALID = 1,
/**
* A fallback was found. For example, the Accept-Language list includes 'ja_JP'
* and is matched with available locale 'ja'.
* @stable ICU 3.2
*/
ULOC_ACCEPT_FALLBACK = 2 /* */
} UAcceptResult;
/**
* Based on a HTTP header from a web browser and a list of available locales,
* determine an acceptable locale for the user.
*
* This is a thin wrapper over C++ class LocaleMatcher.
*
* @param result - buffer to accept the result locale
* @param resultAvailable the size of the result buffer.
* @param outResult - An out parameter that contains the fallback status
* @param httpAcceptLanguage - "Accept-Language:" header as per HTTP.
* @param availableLocales - list of available locales to match
* @param status Error status, may be BUFFER_OVERFLOW_ERROR
* @param status ICU error code. Its input value must pass the U_SUCCESS() test,
* or else the function returns immediately. Check for U_FAILURE()
* on output or use with function chaining. (See User Guide for details.)
* @return length needed for the locale.
* @stable ICU 3.2
*/
@@ -1070,13 +1086,18 @@ uloc_acceptLanguageFromHTTP(char *result, int32_t resultAvailable,
/**
* Based on a list of available locales,
* determine an acceptable locale for the user.
*
* This is a thin wrapper over C++ class LocaleMatcher.
*
* @param result - buffer to accept the result locale
* @param resultAvailable the size of the result buffer.
* @param outResult - An out parameter that contains the fallback status
* @param acceptList - list of acceptable languages
* @param acceptListCount - count of acceptList items
* @param availableLocales - list of available locales to match
* @param status Error status, may be BUFFER_OVERFLOW_ERROR
* @param status ICU error code. Its input value must pass the U_SUCCESS() test,
* or else the function returns immediately. Check for U_FAILURE()
* on output or use with function chaining. (See User Guide for details.)
* @return length needed for the locale.
* @stable ICU 3.2
*/
+1 -1
View File
@@ -372,7 +372,7 @@ typedef int8_t UBool;
typedef char16_t UChar;
#elif defined(UCHAR_TYPE)
typedef UCHAR_TYPE UChar;
#elif defined(__cplusplus)
#elif (U_CPLUSPLUS_VERSION >= 11)
typedef char16_t UChar;
#else
typedef uint16_t UChar;
+19 -19
View File
@@ -83,25 +83,6 @@ umutablecptrie_clone(const UMutableCPTrie *other, UErrorCode *pErrorCode);
U_CAPI void U_EXPORT2
umutablecptrie_close(UMutableCPTrie *trie);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUMutableCPTriePointer
* "Smart pointer" class, closes a UMutableCPTrie via umutablecptrie_close().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 63
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUMutableCPTriePointer, UMutableCPTrie, umutablecptrie_close);
U_NAMESPACE_END
#endif
/**
* Creates a mutable trie with the same contents as the UCPMap.
* You must umutablecptrie_close() the mutable trie once you are done using it.
@@ -235,4 +216,23 @@ umutablecptrie_buildImmutable(UMutableCPTrie *trie, UCPTrieType type, UCPTrieVal
U_CDECL_END
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUMutableCPTriePointer
* "Smart pointer" class, closes a UMutableCPTrie via umutablecptrie_close().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 63
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUMutableCPTriePointer, UMutableCPTrie, umutablecptrie_close);
U_NAMESPACE_END
#endif
#endif
+8 -1
View File
@@ -135,6 +135,7 @@
#define locale_get_default U_ICU_ENTRY_POINT_RENAME(locale_get_default)
#define locale_set_default U_ICU_ENTRY_POINT_RENAME(locale_set_default)
#define numSysCleanup U_ICU_ENTRY_POINT_RENAME(numSysCleanup)
#define rbbi_cleanup U_ICU_ENTRY_POINT_RENAME(rbbi_cleanup)
#define pl_addFontRun U_ICU_ENTRY_POINT_RENAME(pl_addFontRun)
#define pl_addLocaleRun U_ICU_ENTRY_POINT_RENAME(pl_addLocaleRun)
#define pl_addValueRun U_ICU_ENTRY_POINT_RENAME(pl_addValueRun)
@@ -203,6 +204,7 @@
#define res_read U_ICU_ENTRY_POINT_RENAME(res_read)
#define res_unload U_ICU_ENTRY_POINT_RENAME(res_unload)
#define u_UCharsToChars U_ICU_ENTRY_POINT_RENAME(u_UCharsToChars)
#define u_asciiToUpper U_ICU_ENTRY_POINT_RENAME(u_asciiToUpper)
#define u_austrcpy U_ICU_ENTRY_POINT_RENAME(u_austrcpy)
#define u_austrncpy U_ICU_ENTRY_POINT_RENAME(u_austrncpy)
#define u_caseInsensitivePrefixMatch U_ICU_ENTRY_POINT_RENAME(u_caseInsensitivePrefixMatch)
@@ -896,6 +898,7 @@
#define udatpg_getBestPatternWithOptions U_ICU_ENTRY_POINT_RENAME(udatpg_getBestPatternWithOptions)
#define udatpg_getDateTimeFormat U_ICU_ENTRY_POINT_RENAME(udatpg_getDateTimeFormat)
#define udatpg_getDecimal U_ICU_ENTRY_POINT_RENAME(udatpg_getDecimal)
#define udatpg_getDefaultHourCycle U_ICU_ENTRY_POINT_RENAME(udatpg_getDefaultHourCycle)
#define udatpg_getFieldDisplayName U_ICU_ENTRY_POINT_RENAME(udatpg_getFieldDisplayName)
#define udatpg_getPatternForSkeleton U_ICU_ENTRY_POINT_RENAME(udatpg_getPatternForSkeleton)
#define udatpg_getSkeleton U_ICU_ENTRY_POINT_RENAME(udatpg_getSkeleton)
@@ -913,6 +916,7 @@
#define udtitvfmt_close U_ICU_ENTRY_POINT_RENAME(udtitvfmt_close)
#define udtitvfmt_closeResult U_ICU_ENTRY_POINT_RENAME(udtitvfmt_closeResult)
#define udtitvfmt_format U_ICU_ENTRY_POINT_RENAME(udtitvfmt_format)
#define udtitvfmt_formatCalendarToResult U_ICU_ENTRY_POINT_RENAME(udtitvfmt_formatCalendarToResult)
#define udtitvfmt_formatToResult U_ICU_ENTRY_POINT_RENAME(udtitvfmt_formatToResult)
#define udtitvfmt_open U_ICU_ENTRY_POINT_RENAME(udtitvfmt_open)
#define udtitvfmt_openResult U_ICU_ENTRY_POINT_RENAME(udtitvfmt_openResult)
@@ -1053,6 +1057,7 @@
#define ulistfmt_format U_ICU_ENTRY_POINT_RENAME(ulistfmt_format)
#define ulistfmt_formatStringsToResult U_ICU_ENTRY_POINT_RENAME(ulistfmt_formatStringsToResult)
#define ulistfmt_open U_ICU_ENTRY_POINT_RENAME(ulistfmt_open)
#define ulistfmt_openForType U_ICU_ENTRY_POINT_RENAME(ulistfmt_openForType)
#define ulistfmt_openResult U_ICU_ENTRY_POINT_RENAME(ulistfmt_openResult)
#define ulistfmt_resultAsValue U_ICU_ENTRY_POINT_RENAME(ulistfmt_resultAsValue)
#define uloc_acceptLanguage U_ICU_ENTRY_POINT_RENAME(uloc_acceptLanguage)
@@ -1114,9 +1119,12 @@
#define ulocdata_open U_ICU_ENTRY_POINT_RENAME(ulocdata_open)
#define ulocdata_setNoSubstitute U_ICU_ENTRY_POINT_RENAME(ulocdata_setNoSubstitute)
#define ulocimp_addLikelySubtags U_ICU_ENTRY_POINT_RENAME(ulocimp_addLikelySubtags)
#define ulocimp_canonicalize U_ICU_ENTRY_POINT_RENAME(ulocimp_canonicalize)
#define ulocimp_forLanguageTag U_ICU_ENTRY_POINT_RENAME(ulocimp_forLanguageTag)
#define ulocimp_getBaseName U_ICU_ENTRY_POINT_RENAME(ulocimp_getBaseName)
#define ulocimp_getCountry U_ICU_ENTRY_POINT_RENAME(ulocimp_getCountry)
#define ulocimp_getLanguage U_ICU_ENTRY_POINT_RENAME(ulocimp_getLanguage)
#define ulocimp_getName U_ICU_ENTRY_POINT_RENAME(ulocimp_getName)
#define ulocimp_getRegionForSupplementalData U_ICU_ENTRY_POINT_RENAME(ulocimp_getRegionForSupplementalData)
#define ulocimp_getScript U_ICU_ENTRY_POINT_RENAME(ulocimp_getScript)
#define ulocimp_minimizeSubtags U_ICU_ENTRY_POINT_RENAME(ulocimp_minimizeSubtags)
@@ -1295,7 +1303,6 @@
#define uprv_convertToPosix U_ICU_ENTRY_POINT_RENAME(uprv_convertToPosix)
#define uprv_copyAscii U_ICU_ENTRY_POINT_RENAME(uprv_copyAscii)
#define uprv_copyEbcdic U_ICU_ENTRY_POINT_RENAME(uprv_copyEbcdic)
#define uprv_currencyLeads U_ICU_ENTRY_POINT_RENAME(uprv_currencyLeads)
#define uprv_decContextClearStatus U_ICU_ENTRY_POINT_RENAME(uprv_decContextClearStatus)
#define uprv_decContextDefault U_ICU_ENTRY_POINT_RENAME(uprv_decContextDefault)
#define uprv_decContextGetRounding U_ICU_ENTRY_POINT_RENAME(uprv_decContextGetRounding)
+19 -19
View File
@@ -183,25 +183,6 @@ typedef struct UText UText; /**< C typedef for struct UText. @stable ICU 3.6 */
U_STABLE UText * U_EXPORT2
utext_close(UText *ut);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUTextPointer
* "Smart pointer" class, closes a UText via utext_close().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 4.4
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUTextPointer, UText, utext_close);
U_NAMESPACE_END
#endif
/**
* Open a read-only UText implementation for UTF-8 strings.
*
@@ -1599,5 +1580,24 @@ enum {
U_CDECL_END
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUTextPointer
* "Smart pointer" class, closes a UText via utext_close().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 4.4
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUTextPointer, UText, utext_close);
U_NAMESPACE_END
#endif
#endif
+65
View File
@@ -177,6 +177,71 @@ typedef enum UTraceFunctionNumber {
UTRACE_RES_DATA_LIMIT,
#endif // U_HIDE_INTERNAL_API
#ifndef U_HIDE_DRAFT_API
/**
* The lowest break iterator location.
* @draft ICU 67
*/
UTRACE_UBRK_START=0x4000,
/**
* Indicates that a character instance of break iterator was created.
*
* @draft ICU 67
*/
UTRACE_UBRK_CREATE_CHARACTER = UTRACE_UBRK_START,
/**
* Indicates that a word instance of break iterator was created.
*
* @draft ICU 67
*/
UTRACE_UBRK_CREATE_WORD,
/**
* Indicates that a line instance of break iterator was created.
*
* Provides one C-style string to UTraceData: the lb value ("",
* "loose", "strict", or "normal").
*
* @draft ICU 67
*/
UTRACE_UBRK_CREATE_LINE,
/**
* Indicates that a sentence instance of break iterator was created.
*
* @draft ICU 67
*/
UTRACE_UBRK_CREATE_SENTENCE,
/**
* Indicates that a title instance of break iterator was created.
*
* @draft ICU 67
*/
UTRACE_UBRK_CREATE_TITLE,
/**
* Indicates that an internal dictionary break engine was created.
*
* Provides one C-style string to UTraceData: the script code of what
* the break engine cover ("Hani", "Khmr", "Laoo", "Mymr", or "Thai").
*
* @draft ICU 67
*/
UTRACE_UBRK_CREATE_BREAK_ENGINE,
#endif // U_HIDE_DRAFT_API
#ifndef U_HIDE_INTERNAL_API
/**
* One more than the highest normal break iterator trace location.
* @internal The numeric value may change over time, see ICU ticket #12420.
*/
UTRACE_UBRK_LIMIT,
#endif // U_HIDE_INTERNAL_API
} UTraceFunctionNumber;
/**
+5 -5
View File
@@ -60,7 +60,7 @@
* This value will change in the subsequent releases of ICU
* @stable ICU 2.4
*/
#define U_ICU_VERSION_MAJOR_NUM 66
#define U_ICU_VERSION_MAJOR_NUM 67
/** The current ICU minor version as an integer.
* This value will change in the subsequent releases of ICU
@@ -86,7 +86,7 @@
* This value will change in the subsequent releases of ICU
* @stable ICU 2.6
*/
#define U_ICU_VERSION_SUFFIX _66
#define U_ICU_VERSION_SUFFIX _67
/**
* \def U_DEF2_ICU_ENTRY_POINT_RENAME
@@ -139,7 +139,7 @@
* This value will change in the subsequent releases of ICU
* @stable ICU 2.4
*/
#define U_ICU_VERSION "66.1"
#define U_ICU_VERSION "67.1"
/**
* The current ICU library major version number as a string, for library name suffixes.
@@ -152,13 +152,13 @@
*
* @stable ICU 2.6
*/
#define U_ICU_VERSION_SHORT "66"
#define U_ICU_VERSION_SHORT "67"
#ifndef U_HIDE_INTERNAL_API
/** Data version in ICU4C.
* @internal ICU 4.4 Internal Use Only
**/
#define U_ICU_DATA_VERSION "66.1"
#define U_ICU_DATA_VERSION "67.1"
#endif /* U_HIDE_INTERNAL_API */
/*===========================================================================
+5 -1
View File
@@ -1563,7 +1563,11 @@ UnicodeString::doAppend(const UChar *srcChars, int32_t srcStart, int32_t srcLeng
}
int32_t oldLength = length();
int32_t newLength = oldLength + srcLength;
int32_t newLength;
if (uprv_add32_overflow(oldLength, srcLength, &newLength)) {
setToBogus();
return *this;
}
// Check for append onto ourself
const UChar* oldArray = getArrayStart();
+6
View File
@@ -68,4 +68,10 @@
# define _STDC_C99
#endif
#if !defined _POSIX_C_SOURCE && \
defined(__APPLE__) && defined(__MACH__) && !defined(__clang__)
// Needed to prevent EOWNERDEAD issues with GCC on Mac
#define _POSIX_C_SOURCE 200809L
#endif
#endif /* __UPOSIXDEFS_H__ */
+2 -2
View File
@@ -2611,8 +2611,8 @@ ures_getFunctionalEquivalent(char *result, int32_t resultCapacity,
char defVal[1024] = ""; /* default value for given locale */
char defLoc[1024] = ""; /* default value for given locale */
char base[1024] = ""; /* base locale */
char found[1024];
char parent[1024];
char found[1024] = "";
char parent[1024] = "";
char full[1024] = "";
UResourceBundle bund1, bund2;
UResourceBundle *res = NULL;
+2 -2
View File
@@ -58,8 +58,8 @@ static int32_t
getCodesFromLocale(const char *locale,
UScriptCode *scripts, int32_t capacity, UErrorCode *err) {
UErrorCode internalErrorCode = U_ZERO_ERROR;
char lang[8];
char script[8];
char lang[8] = {0};
char script[8] = {0};
int32_t scriptLength;
if(U_FAILURE(*err)) { return 0; }
// Multi-script languages, equivalent to the LocaleScript data
+19 -7
View File
@@ -37,15 +37,27 @@ uprv_strCompare(const UChar *s1, int32_t length1,
const UChar *s2, int32_t length2,
UBool strncmpStyle, UBool codePointOrder);
U_CAPI int32_t U_EXPORT2
U_INTERNAL int32_t U_EXPORT2
ustr_hashUCharsN(const UChar *str, int32_t length);
U_CAPI int32_t U_EXPORT2
U_INTERNAL int32_t U_EXPORT2
ustr_hashCharsN(const char *str, int32_t length);
U_CAPI int32_t U_EXPORT2
U_INTERNAL int32_t U_EXPORT2
ustr_hashICharsN(const char *str, int32_t length);
/**
* Convert an ASCII-range lowercase character to uppercase.
*
* @param c A UChar.
* @return If UChar is a lowercase ASCII character, returns the uppercase version.
* Otherwise, returns the input character.
*/
U_INTERNAL UChar U_EXPORT2
u_asciiToUpper(UChar c);
// TODO: Add u_asciiToLower if/when there is a need for it.
/**
* NUL-terminate a UChar * string if possible.
* If length < destCapacity then NUL-terminate.
@@ -58,28 +70,28 @@ ustr_hashICharsN(const char *str, int32_t length);
* @param pErrorCode ICU error code.
* @return length
*/
U_CAPI int32_t U_EXPORT2
U_INTERNAL int32_t U_EXPORT2
u_terminateUChars(UChar *dest, int32_t destCapacity, int32_t length, UErrorCode *pErrorCode);
/**
* NUL-terminate a char * string if possible.
* Same as u_terminateUChars() but for a different string type.
*/
U_CAPI int32_t U_EXPORT2
U_INTERNAL int32_t U_EXPORT2
u_terminateChars(char *dest, int32_t destCapacity, int32_t length, UErrorCode *pErrorCode);
/**
* NUL-terminate a UChar32 * string if possible.
* Same as u_terminateUChars() but for a different string type.
*/
U_CAPI int32_t U_EXPORT2
U_INTERNAL int32_t U_EXPORT2
u_terminateUChar32s(UChar32 *dest, int32_t destCapacity, int32_t length, UErrorCode *pErrorCode);
/**
* NUL-terminate a wchar_t * string if possible.
* Same as u_terminateUChars() but for a different string type.
*/
U_CAPI int32_t U_EXPORT2
U_INTERNAL int32_t U_EXPORT2
u_terminateWChars(wchar_t *dest, int32_t destCapacity, int32_t length, UErrorCode *pErrorCode);
/**
+8
View File
@@ -1451,6 +1451,14 @@ u_unescape(const char *src, UChar *dest, int32_t destCapacity) {
} \
} UPRV_BLOCK_MACRO_END
U_CAPI UChar U_EXPORT2
u_asciiToUpper(UChar c) {
if (u'a' <= c && c <= u'z') {
c = c + u'A' - u'a';
}
return c;
}
U_CAPI int32_t U_EXPORT2
u_terminateUChars(UChar *dest, int32_t destCapacity, int32_t length, UErrorCode *pErrorCode) {
__TERMINATE_STRING(dest, destCapacity, length, pErrorCode);
+5 -3
View File
@@ -16,6 +16,8 @@
* created by: Markus W. Scherer
*/
#include <cstddef>
#include "unicode/utypes.h"
#include "unicode/ustring.h"
#include "unicode/unistr.h"
@@ -566,8 +568,8 @@ enum {
// when a provider asks for a UText to be allocated with extra storage.
struct ExtendedUText {
UText ut;
max_align_t extension;
UText ut;
std::max_align_t extension;
};
static const UText emptyText = UTEXT_INITIALIZER;
@@ -582,7 +584,7 @@ utext_setup(UText *ut, int32_t extraSpace, UErrorCode *status) {
// We need to heap-allocate storage for the new UText
int32_t spaceRequired = sizeof(UText);
if (extraSpace > 0) {
spaceRequired = sizeof(ExtendedUText) + extraSpace - sizeof(max_align_t);
spaceRequired = sizeof(ExtendedUText) + extraSpace - sizeof(std::max_align_t);
}
ut = (UText *)uprv_malloc(spaceRequired);
if (ut == NULL) {
+1 -1
View File
@@ -958,7 +958,7 @@ Calendar::makeInstance(const Locale& aLocale, UErrorCode& success) {
#endif
c->setWeekData(aLocale, c->getType(), success); // set the correct locale (this was an indirected calendar)
char keyword[ULOC_FULLNAME_CAPACITY];
char keyword[ULOC_FULLNAME_CAPACITY] = "";
UErrorCode tmpStatus = U_ZERO_ERROR;
l.getKeywordValue("calendar", keyword, ULOC_FULLNAME_CAPACITY, tmpStatus);
if (U_SUCCESS(tmpStatus) && uprv_strcmp(keyword, "iso8601") == 0) {
+1 -1
View File
@@ -92,7 +92,7 @@ private:
CollationTailoring(const CollationTailoring &other);
};
struct CollationCacheEntry : public SharedObject {
struct U_I18N_API CollationCacheEntry : public SharedObject {
CollationCacheEntry(const Locale &loc, const CollationTailoring *t)
: validLocale(loc), tailoring(t) {
if(t != NULL) {
+18 -15
View File
@@ -16,12 +16,12 @@
#include "unicode/currunit.h"
#include "unicode/ustring.h"
#include "unicode/uchar.h"
#include "cstring.h"
#include "uinvchar.h"
#include "charstr.h"
static constexpr char16_t kDefaultCurrency[] = u"XXX";
static constexpr char kDefaultCurrency8[] = "XXX";
#include "ustr_imp.h"
#include "measunit_impl.h"
U_NAMESPACE_BEGIN
@@ -31,22 +31,25 @@ CurrencyUnit::CurrencyUnit(ConstChar16Ptr _isoCode, UErrorCode& ec) {
// non-NUL-terminated string to be passed as an argument, so it is not possible to check length.
// However, we allow a NUL-terminated empty string, which should have the same behavior as nullptr.
// Consider NUL-terminated strings of length 1 or 2 as invalid.
const char16_t* isoCodeToUse;
bool useDefault = false;
if (U_FAILURE(ec) || _isoCode == nullptr || _isoCode[0] == 0) {
isoCodeToUse = kDefaultCurrency;
useDefault = true;
} else if (_isoCode[1] == 0 || _isoCode[2] == 0) {
isoCodeToUse = kDefaultCurrency;
useDefault = true;
ec = U_ILLEGAL_ARGUMENT_ERROR;
} else if (!uprv_isInvariantUString(_isoCode, 3)) {
// TODO: Perform a more strict ASCII check like in ICU4J isAlpha3Code?
isoCodeToUse = kDefaultCurrency;
useDefault = true;
ec = U_INVARIANT_CONVERSION_ERROR;
} else {
isoCodeToUse = _isoCode;
for (int32_t i=0; i<3; i++) {
isoCode[i] = u_asciiToUpper(_isoCode[i]);
}
isoCode[3] = 0;
}
if (useDefault) {
uprv_memcpy(isoCode, kDefaultCurrency, sizeof(UChar) * 4);
}
// TODO: Perform uppercasing here like in ICU4J Currency.getInstance()?
uprv_memcpy(isoCode, isoCodeToUse, sizeof(UChar) * 3);
isoCode[3] = 0;
char simpleIsoCode[4];
u_UCharsToChars(isoCode, simpleIsoCode, 4);
initCurrency(simpleIsoCode);
@@ -66,13 +69,13 @@ CurrencyUnit::CurrencyUnit(StringPiece _isoCode, UErrorCode& ec) {
ec = U_INVARIANT_CONVERSION_ERROR;
} else {
// Have to use isoCodeBuffer to ensure the string is NUL-terminated
uprv_strncpy(isoCodeBuffer, _isoCode.data(), 3);
for (int32_t i=0; i<3; i++) {
isoCodeBuffer[i] = uprv_toupper(_isoCode.data()[i]);
}
isoCodeBuffer[3] = 0;
isoCodeToUse = isoCodeBuffer;
}
// TODO: Perform uppercasing here like in ICU4J Currency.getInstance()?
u_charsToUChars(isoCodeToUse, isoCode, 3);
isoCode[3] = 0;
u_charsToUChars(isoCodeToUse, isoCode, 4);
initCurrency(isoCodeToUse);
}
+50 -46
View File
@@ -167,6 +167,7 @@ DecimalFormatSymbols::operator=(const DecimalFormatSymbols& rhs)
fIsCustomCurrencySymbol = rhs.fIsCustomCurrencySymbol;
fIsCustomIntlCurrencySymbol = rhs.fIsCustomIntlCurrencySymbol;
fCodePointZero = rhs.fCodePointZero;
currPattern = rhs.currPattern;
}
return *this;
}
@@ -453,58 +454,16 @@ DecimalFormatSymbols::initialize(const Locale& loc, UErrorCode& status,
}
fCodePointZero = tempCodePointZero;
// Obtain currency data from the currency API. This is strictly
// for backward compatibility; we don't use DecimalFormatSymbols
// for currency data anymore.
// Get the default currency from the currency API.
UErrorCode internalStatus = U_ZERO_ERROR; // don't propagate failures out
UChar curriso[4];
UnicodeString tempStr;
int32_t currisoLength = ucurr_forLocale(locStr, curriso, UPRV_LENGTHOF(curriso), &internalStatus);
if (U_SUCCESS(internalStatus) && currisoLength == 3) {
uprv_getStaticCurrencyName(curriso, locStr, tempStr, internalStatus);
if (U_SUCCESS(internalStatus)) {
fSymbols[kIntlCurrencySymbol].setTo(curriso, currisoLength);
fSymbols[kCurrencySymbol] = tempStr;
}
setCurrency(curriso, status);
} else {
setCurrency(nullptr, status);
}
/* else use the default values. */
//load the currency data
UChar ucc[4]={0}; //Currency Codes are always 3 chars long
int32_t uccLen = 4;
const char* locName = loc.getName();
UErrorCode localStatus = U_ZERO_ERROR;
uccLen = ucurr_forLocale(locName, ucc, uccLen, &localStatus);
// TODO: Currency pattern data loading is duplicated in number_formatimpl.cpp
if(U_SUCCESS(localStatus) && uccLen > 0) {
char cc[4]={0};
u_UCharsToChars(ucc, cc, uccLen);
/* An explicit currency was requested */
LocalUResourceBundlePointer currencyResource(ures_open(U_ICUDATA_CURR, locStr, &localStatus));
LocalUResourceBundlePointer currency(
ures_getByKeyWithFallback(currencyResource.getAlias(), "Currencies", NULL, &localStatus));
ures_getByKeyWithFallback(currency.getAlias(), cc, currency.getAlias(), &localStatus);
if(U_SUCCESS(localStatus) && ures_getSize(currency.getAlias())>2) { // the length is 3 if more data is present
ures_getByIndex(currency.getAlias(), 2, currency.getAlias(), &localStatus);
int32_t currPatternLen = 0;
currPattern =
ures_getStringByIndex(currency.getAlias(), (int32_t)0, &currPatternLen, &localStatus);
UnicodeString decimalSep =
ures_getUnicodeStringByIndex(currency.getAlias(), (int32_t)1, &localStatus);
UnicodeString groupingSep =
ures_getUnicodeStringByIndex(currency.getAlias(), (int32_t)2, &localStatus);
if(U_SUCCESS(localStatus)){
fSymbols[kMonetaryGroupingSeparatorSymbol] = groupingSep;
fSymbols[kMonetarySeparatorSymbol] = decimalSep;
//pattern.setTo(TRUE, currPattern, currPatternLen);
status = localStatus;
}
}
/* else An explicit currency was requested and is unknown or locale data is malformed. */
/* ucurr_* API will get the correct value later on. */
}
// else ignore the error if no currency
// Currency Spacing.
LocalUResourceBundlePointer currencyResource(ures_open(U_ICUDATA_CURR, locStr, &status));
@@ -553,9 +512,54 @@ DecimalFormatSymbols::initialize() {
fIsCustomIntlCurrencySymbol = FALSE;
fCodePointZero = 0x30;
U_ASSERT(fCodePointZero == fSymbols[kZeroDigitSymbol].char32At(0));
currPattern = nullptr;
}
void DecimalFormatSymbols::setCurrency(const UChar* currency, UErrorCode& status) {
// TODO: If this method is made public:
// - Adopt ICU4J behavior of not allowing currency to be null.
// - Also verify that the length of currency is 3.
if (!currency) {
return;
}
UnicodeString tempStr;
uprv_getStaticCurrencyName(currency, locale.getName(), tempStr, status);
if (U_SUCCESS(status)) {
fSymbols[kIntlCurrencySymbol].setTo(currency, 3);
fSymbols[kCurrencySymbol] = tempStr;
}
char cc[4]={0};
u_UCharsToChars(currency, cc, 3);
/* An explicit currency was requested */
// TODO(ICU-13297): Move this data loading logic into a centralized place
UErrorCode localStatus = U_ZERO_ERROR;
LocalUResourceBundlePointer rbTop(ures_open(U_ICUDATA_CURR, locale.getName(), &localStatus));
LocalUResourceBundlePointer rb(
ures_getByKeyWithFallback(rbTop.getAlias(), "Currencies", NULL, &localStatus));
ures_getByKeyWithFallback(rb.getAlias(), cc, rb.getAlias(), &localStatus);
if(U_SUCCESS(localStatus) && ures_getSize(rb.getAlias())>2) { // the length is 3 if more data is present
ures_getByIndex(rb.getAlias(), 2, rb.getAlias(), &localStatus);
int32_t currPatternLen = 0;
currPattern =
ures_getStringByIndex(rb.getAlias(), (int32_t)0, &currPatternLen, &localStatus);
UnicodeString decimalSep =
ures_getUnicodeStringByIndex(rb.getAlias(), (int32_t)1, &localStatus);
UnicodeString groupingSep =
ures_getUnicodeStringByIndex(rb.getAlias(), (int32_t)2, &localStatus);
if(U_SUCCESS(localStatus)){
fSymbols[kMonetaryGroupingSeparatorSymbol] = groupingSep;
fSymbols[kMonetarySeparatorSymbol] = decimalSep;
//pattern.setTo(TRUE, currPattern, currPatternLen);
}
}
/* else An explicit currency was requested and is unknown or locale data is malformed. */
/* ucurr_* API will get the correct value later on. */
}
Locale
DecimalFormatSymbols::getLocale(ULocDataLocaleType type, UErrorCode& status) const {
U_LOCALE_BASED(locBased, *this);
+46 -18
View File
@@ -519,7 +519,9 @@ UnicodeString& DecimalFormat::format(double number, UnicodeString& appendTo, Fie
return appendTo;
}
UErrorCode localStatus = U_ZERO_ERROR;
FormattedNumber output = fields->formatter.formatDouble(number, localStatus);
UFormattedNumberData output;
output.quantity.setToDouble(number);
fields->formatter.formatImpl(&output, localStatus);
fieldPositionHelper(output, pos, appendTo.length(), localStatus);
auto appendable = UnicodeStringAppendable(appendTo);
output.appendTo(appendable, localStatus);
@@ -540,7 +542,9 @@ UnicodeString& DecimalFormat::format(double number, UnicodeString& appendTo, Fie
if (pos.getField() == FieldPosition::DONT_CARE && fastFormatDouble(number, appendTo)) {
return appendTo;
}
FormattedNumber output = fields->formatter.formatDouble(number, status);
UFormattedNumberData output;
output.quantity.setToDouble(number);
fields->formatter.formatImpl(&output, status);
fieldPositionHelper(output, pos, appendTo.length(), status);
auto appendable = UnicodeStringAppendable(appendTo);
output.appendTo(appendable, status);
@@ -562,7 +566,9 @@ DecimalFormat::format(double number, UnicodeString& appendTo, FieldPositionItera
if (posIter == nullptr && fastFormatDouble(number, appendTo)) {
return appendTo;
}
FormattedNumber output = fields->formatter.formatDouble(number, status);
UFormattedNumberData output;
output.quantity.setToDouble(number);
fields->formatter.formatImpl(&output, status);
fieldPositionIteratorHelper(output, posIter, appendTo.length(), status);
auto appendable = UnicodeStringAppendable(appendTo);
output.appendTo(appendable, status);
@@ -593,7 +599,9 @@ UnicodeString& DecimalFormat::format(int64_t number, UnicodeString& appendTo, Fi
return appendTo;
}
UErrorCode localStatus = U_ZERO_ERROR;
FormattedNumber output = fields->formatter.formatInt(number, localStatus);
UFormattedNumberData output;
output.quantity.setToLong(number);
fields->formatter.formatImpl(&output, localStatus);
fieldPositionHelper(output, pos, appendTo.length(), localStatus);
auto appendable = UnicodeStringAppendable(appendTo);
output.appendTo(appendable, localStatus);
@@ -614,7 +622,9 @@ UnicodeString& DecimalFormat::format(int64_t number, UnicodeString& appendTo, Fi
if (pos.getField() == FieldPosition::DONT_CARE && fastFormatInt64(number, appendTo)) {
return appendTo;
}
FormattedNumber output = fields->formatter.formatInt(number, status);
UFormattedNumberData output;
output.quantity.setToLong(number);
fields->formatter.formatImpl(&output, status);
fieldPositionHelper(output, pos, appendTo.length(), status);
auto appendable = UnicodeStringAppendable(appendTo);
output.appendTo(appendable, status);
@@ -636,7 +646,9 @@ DecimalFormat::format(int64_t number, UnicodeString& appendTo, FieldPositionIter
if (posIter == nullptr && fastFormatInt64(number, appendTo)) {
return appendTo;
}
FormattedNumber output = fields->formatter.formatInt(number, status);
UFormattedNumberData output;
output.quantity.setToLong(number);
fields->formatter.formatImpl(&output, status);
fieldPositionIteratorHelper(output, posIter, appendTo.length(), status);
auto appendable = UnicodeStringAppendable(appendTo);
output.appendTo(appendable, status);
@@ -655,7 +667,9 @@ DecimalFormat::format(StringPiece number, UnicodeString& appendTo, FieldPosition
appendTo.setToBogus();
return appendTo;
}
FormattedNumber output = fields->formatter.formatDecimal(number, status);
UFormattedNumberData output;
output.quantity.setToDecNumber(number, status);
fields->formatter.formatImpl(&output, status);
fieldPositionIteratorHelper(output, posIter, appendTo.length(), status);
auto appendable = UnicodeStringAppendable(appendTo);
output.appendTo(appendable, status);
@@ -673,7 +687,9 @@ UnicodeString& DecimalFormat::format(const DecimalQuantity& number, UnicodeStrin
appendTo.setToBogus();
return appendTo;
}
FormattedNumber output = fields->formatter.formatDecimalQuantity(number, status);
UFormattedNumberData output;
output.quantity = number;
fields->formatter.formatImpl(&output, status);
fieldPositionIteratorHelper(output, posIter, appendTo.length(), status);
auto appendable = UnicodeStringAppendable(appendTo);
output.appendTo(appendable, status);
@@ -692,7 +708,9 @@ DecimalFormat::format(const DecimalQuantity& number, UnicodeString& appendTo, Fi
appendTo.setToBogus();
return appendTo;
}
FormattedNumber output = fields->formatter.formatDecimalQuantity(number, status);
UFormattedNumberData output;
output.quantity = number;
fields->formatter.formatImpl(&output, status);
fieldPositionHelper(output, pos, appendTo.length(), status);
auto appendable = UnicodeStringAppendable(appendTo);
output.appendTo(appendable, status);
@@ -1502,8 +1520,11 @@ void DecimalFormat::setCurrency(const char16_t* theCurrency, UErrorCode& ec) {
}
NumberFormat::setCurrency(theCurrency, ec); // to set field for compatibility
fields->properties.currency = currencyUnit;
// TODO: Set values in fields->symbols, too?
touchNoError();
// In Java, the DecimalFormatSymbols is mutable. Why not in C++?
LocalPointer<DecimalFormatSymbols> newSymbols(new DecimalFormatSymbols(*fields->symbols), ec);
newSymbols->setCurrency(currencyUnit.getISOCurrency(), ec);
fields->symbols.adoptInsteadAndCheckErrorCode(newSymbols.orphan(), ec);
touch(ec);
}
void DecimalFormat::setCurrency(const char16_t* theCurrency) {
@@ -1700,8 +1721,11 @@ const numparse::impl::NumberParserImpl* DecimalFormat::getCurrencyParser(UErrorC
}
void
DecimalFormat::fieldPositionHelper(const number::FormattedNumber& formatted, FieldPosition& fieldPosition,
int32_t offset, UErrorCode& status) {
DecimalFormat::fieldPositionHelper(
const UFormattedNumberData& formatted,
FieldPosition& fieldPosition,
int32_t offset,
UErrorCode& status) {
if (U_FAILURE(status)) { return; }
// always return first occurrence:
fieldPosition.setBeginIndex(0);
@@ -1714,12 +1738,15 @@ DecimalFormat::fieldPositionHelper(const number::FormattedNumber& formatted, Fie
}
void
DecimalFormat::fieldPositionIteratorHelper(const number::FormattedNumber& formatted, FieldPositionIterator* fpi,
int32_t offset, UErrorCode& status) {
DecimalFormat::fieldPositionIteratorHelper(
const UFormattedNumberData& formatted,
FieldPositionIterator* fpi,
int32_t offset,
UErrorCode& status) {
if (U_SUCCESS(status) && (fpi != nullptr)) {
FieldPositionIteratorHandler fpih(fpi, status);
fpih.setShift(offset);
formatted.getAllFieldPositionsImpl(fpih, status);
formatted.getAllFieldPositions(fpih, status);
}
}
@@ -1801,7 +1828,7 @@ bool DecimalFormat::fastFormatDouble(double input, UnicodeString& output) const
return false;
}
if (std::isnan(input)
|| std::trunc(input) != input
|| uprv_trunc(input) != input
|| input <= INT32_MIN
|| input > INT32_MAX) {
return false;
@@ -1834,7 +1861,8 @@ void DecimalFormat::doFastFormatInt32(int32_t input, bool isNegative, UnicodeStr
char16_t localBuffer[localCapacity];
char16_t* ptr = localBuffer + localCapacity;
int8_t group = 0;
for (int8_t i = 0; i < fields->fastData.maxInt && (input != 0 || i < fields->fastData.minInt); i++) {
int8_t minInt = (fields->fastData.minInt < 1)? 1: fields->fastData.minInt;
for (int8_t i = 0; i < fields->fastData.maxInt && (input != 0 || i < minInt); i++) {
if (group++ == 3 && fields->fastData.cpGroupingSeparator != 0) {
*(--ptr) = fields->fastData.cpGroupingSeparator;
group = 1;
+20
View File
@@ -59,6 +59,7 @@ class Double {
static const uint64_t kExponentMask = DOUBLE_CONVERSION_UINT64_2PART_C(0x7FF00000, 00000000);
static const uint64_t kSignificandMask = DOUBLE_CONVERSION_UINT64_2PART_C(0x000FFFFF, FFFFFFFF);
static const uint64_t kHiddenBit = DOUBLE_CONVERSION_UINT64_2PART_C(0x00100000, 00000000);
static const uint64_t kQuietNanBit = DOUBLE_CONVERSION_UINT64_2PART_C(0x00080000, 00000000);
static const int kPhysicalSignificandSize = 52; // Excludes the hidden bit.
static const int kSignificandSize = 53;
static const int kExponentBias = 0x3FF + kPhysicalSignificandSize;
@@ -162,6 +163,15 @@ class Double {
((d64 & kSignificandMask) != 0);
}
bool IsQuietNan() const {
return IsNan() && ((AsUint64() & kQuietNanBit) != 0);
}
bool IsSignalingNan() const {
return IsNan() && ((AsUint64() & kQuietNanBit) == 0);
}
bool IsInfinite() const {
uint64_t d64 = AsUint64();
return ((d64 & kExponentMask) == kExponentMask) &&
@@ -280,6 +290,7 @@ class Single {
static const uint32_t kExponentMask = 0x7F800000;
static const uint32_t kSignificandMask = 0x007FFFFF;
static const uint32_t kHiddenBit = 0x00800000;
static const uint32_t kQuietNanBit = 0x00400000;
static const int kPhysicalSignificandSize = 23; // Excludes the hidden bit.
static const int kSignificandSize = 24;
@@ -338,6 +349,15 @@ class Single {
((d32 & kSignificandMask) != 0);
}
bool IsQuietNan() const {
return IsNan() && ((AsUint32() & kQuietNanBit) != 0);
}
bool IsSignalingNan() const {
return IsNan() && ((AsUint32() & kQuietNanBit) == 0);
}
bool IsInfinite() const {
uint32_t d32 = AsUint32();
return ((d32 & kExponentMask) == kExponentMask) &&
@@ -462,11 +462,6 @@ double StringToDoubleConverter::StringToIeee(
}
}
// The longest form of simplified number is: "-<significant digits>.1eXXX\0".
const int kBufferSize = kMaxSignificantDigits + 10;
char buffer[kBufferSize]; // NOLINT: size is known at compile time.
int buffer_pos = 0;
// Exponent will be adjusted if insignificant digits of the integer part
// or insignificant leading zeros of the fractional part are dropped.
int exponent = 0;
@@ -501,7 +496,6 @@ double StringToDoubleConverter::StringToIeee(
return junk_string_value_;
}
DOUBLE_CONVERSION_ASSERT(buffer_pos == 0);
*processed_characters_count = static_cast<int>(current - input);
return sign ? -Double::Infinity() : Double::Infinity();
}
@@ -520,7 +514,6 @@ double StringToDoubleConverter::StringToIeee(
return junk_string_value_;
}
DOUBLE_CONVERSION_ASSERT(buffer_pos == 0);
*processed_characters_count = static_cast<int>(current - input);
return sign ? -Double::NaN() : Double::NaN();
}
@@ -577,6 +570,12 @@ double StringToDoubleConverter::StringToIeee(
bool octal = leading_zero && (flags_ & ALLOW_OCTALS) != 0;
// The longest form of simplified number is: "-<significant digits>.1eXXX\0".
const int kBufferSize = kMaxSignificantDigits + 10;
DOUBLE_CONVERSION_STACK_UNINITIALIZED char
buffer[kBufferSize]; // NOLINT: size is known at compile time.
int buffer_pos = 0;
// Copy significant digits of the integer part (if any) to the buffer.
while (*current >= '0' && *current <= '9') {
if (significant_digits < kMaxSignificantDigits) {
@@ -49,10 +49,12 @@ U_NAMESPACE_BEGIN
namespace double_conversion {
#if defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
// 2^53 = 9007199254740992.
// Any integer with at most 15 decimal digits will hence fit into a double
// (which has a 53bit significand) without loss of precision.
static const int kMaxExactDoubleIntegerDecimalDigits = 15;
#endif // #if defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
// 2^64 = 18446744073709551616 > 10^19
static const int kMaxUint64DecimalDigits = 19;
@@ -69,6 +71,7 @@ static const int kMinDecimalPower = -324;
static const uint64_t kMaxUint64 = DOUBLE_CONVERSION_UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF);
#if defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
static const double exact_powers_of_ten[] = {
1.0, // 10^0
10.0,
@@ -96,6 +99,7 @@ static const double exact_powers_of_ten[] = {
10000000000000000000000.0
};
static const int kExactPowersOfTenSize = DOUBLE_CONVERSION_ARRAY_SIZE(exact_powers_of_ten);
#endif // #if defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
// Maximum number of significant digits in the decimal representation.
// In fact the value is 772 (see conversions.cc), but to give us some margin
+18 -2
View File
@@ -66,14 +66,28 @@ inline void abort_noreturn() { abort(); }
#endif
#endif
// Not all compilers support __has_attribute and combining a check for both
// ifdef and __has_attribute on the same preprocessor line isn't portable.
#ifdef __has_attribute
# define DOUBLE_CONVERSION_HAS_ATTRIBUTE(x) __has_attribute(x)
#else
# define DOUBLE_CONVERSION_HAS_ATTRIBUTE(x) 0
#endif
#ifndef DOUBLE_CONVERSION_UNUSED
#ifdef __GNUC__
#if DOUBLE_CONVERSION_HAS_ATTRIBUTE(unused)
#define DOUBLE_CONVERSION_UNUSED __attribute__((unused))
#else
#define DOUBLE_CONVERSION_UNUSED
#endif
#endif
#if DOUBLE_CONVERSION_HAS_ATTRIBUTE(uninitialized)
#define DOUBLE_CONVERSION_STACK_UNINITIALIZED __attribute__((uninitialized))
#else
#define DOUBLE_CONVERSION_STACK_UNINITIALIZED
#endif
// Double operations detection based on target architecture.
// Linux uses a 80bit wide floating point stack on x86. This induces double
// rounding, which in turn leads to wrong results.
@@ -104,6 +118,7 @@ int main(int argc, char** argv) {
defined(__ARMEL__) || defined(__avr32__) || defined(_M_ARM) || defined(_M_ARM64) || \
defined(__hppa__) || defined(__ia64__) || \
defined(__mips__) || \
defined(__nios2__) || \
defined(__powerpc__) || defined(__ppc__) || defined(__ppc64__) || \
defined(_POWER) || defined(_ARCH_PPC) || defined(_ARCH_PPC64) || \
defined(__sparc__) || defined(__sparc) || defined(__s390__) || \
@@ -112,7 +127,8 @@ int main(int argc, char** argv) {
defined(__AARCH64EL__) || defined(__aarch64__) || defined(__AARCH64EB__) || \
defined(__riscv) || defined(__e2k__) || \
defined(__or1k__) || defined(__arc__) || \
defined(__EMSCRIPTEN__)
defined(__microblaze__) || defined(__XTENSA__) || \
defined(__EMSCRIPTEN__) || defined(__wasm32__)
#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1
#elif defined(__mc68000__) || \
defined(__pnacl__) || defined(__native_client__)
+80 -56
View File
@@ -108,6 +108,10 @@ DateIntervalFormat::createInstance(const UnicodeString& skeleton,
#endif
DateIntervalInfo* dtitvinf = new DateIntervalInfo(locale, status);
if (dtitvinf == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return nullptr;
}
return create(locale, dtitvinf, &skeleton, status);
}
@@ -132,27 +136,27 @@ DateIntervalFormat::createInstance(const UnicodeString& skeleton,
DateIntervalFormat::DateIntervalFormat()
: fInfo(NULL),
fDateFormat(NULL),
fFromCalendar(NULL),
fToCalendar(NULL),
: fInfo(nullptr),
fDateFormat(nullptr),
fFromCalendar(nullptr),
fToCalendar(nullptr),
fLocale(Locale::getRoot()),
fDatePattern(NULL),
fTimePattern(NULL),
fDateTimeFormat(NULL)
fDatePattern(nullptr),
fTimePattern(nullptr),
fDateTimeFormat(nullptr)
{}
DateIntervalFormat::DateIntervalFormat(const DateIntervalFormat& itvfmt)
: Format(itvfmt),
fInfo(NULL),
fDateFormat(NULL),
fFromCalendar(NULL),
fToCalendar(NULL),
fInfo(nullptr),
fDateFormat(nullptr),
fFromCalendar(nullptr),
fToCalendar(nullptr),
fLocale(itvfmt.fLocale),
fDatePattern(NULL),
fTimePattern(NULL),
fDateTimeFormat(NULL) {
fDatePattern(nullptr),
fTimePattern(nullptr),
fDateTimeFormat(nullptr) {
*this = itvfmt;
}
@@ -172,23 +176,23 @@ DateIntervalFormat::operator=(const DateIntervalFormat& itvfmt) {
if ( itvfmt.fDateFormat ) {
fDateFormat = itvfmt.fDateFormat->clone();
} else {
fDateFormat = NULL;
fDateFormat = nullptr;
}
if ( itvfmt.fFromCalendar ) {
fFromCalendar = itvfmt.fFromCalendar->clone();
} else {
fFromCalendar = NULL;
fFromCalendar = nullptr;
}
if ( itvfmt.fToCalendar ) {
fToCalendar = itvfmt.fToCalendar->clone();
} else {
fToCalendar = NULL;
fToCalendar = nullptr;
}
}
if ( itvfmt.fInfo ) {
fInfo = itvfmt.fInfo->clone();
} else {
fInfo = NULL;
fInfo = nullptr;
}
fSkeleton = itvfmt.fSkeleton;
int8_t i;
@@ -196,9 +200,9 @@ DateIntervalFormat::operator=(const DateIntervalFormat& itvfmt) {
fIntervalPatterns[i] = itvfmt.fIntervalPatterns[i];
}
fLocale = itvfmt.fLocale;
fDatePattern = (itvfmt.fDatePattern)? itvfmt.fDatePattern->clone(): NULL;
fTimePattern = (itvfmt.fTimePattern)? itvfmt.fTimePattern->clone(): NULL;
fDateTimeFormat = (itvfmt.fDateTimeFormat)? itvfmt.fDateTimeFormat->clone(): NULL;
fDatePattern = (itvfmt.fDatePattern)? itvfmt.fDatePattern->clone(): nullptr;
fTimePattern = (itvfmt.fTimePattern)? itvfmt.fTimePattern->clone(): nullptr;
fDateTimeFormat = (itvfmt.fDateTimeFormat)? itvfmt.fDateTimeFormat->clone(): nullptr;
}
return *this;
}
@@ -227,21 +231,21 @@ DateIntervalFormat::operator==(const Format& other) const {
const DateIntervalFormat* fmt = (DateIntervalFormat*)&other;
if (this == fmt) {return TRUE;}
if (!Format::operator==(other)) {return FALSE;}
if ((fInfo != fmt->fInfo) && (fInfo == NULL || fmt->fInfo == NULL)) {return FALSE;}
if ((fInfo != fmt->fInfo) && (fInfo == nullptr || fmt->fInfo == nullptr)) {return FALSE;}
if (fInfo && fmt->fInfo && (*fInfo != *fmt->fInfo )) {return FALSE;}
{
Mutex lock(&gFormatterMutex);
if (fDateFormat != fmt->fDateFormat && (fDateFormat == NULL || fmt->fDateFormat == NULL)) {return FALSE;}
if (fDateFormat != fmt->fDateFormat && (fDateFormat == nullptr || fmt->fDateFormat == nullptr)) {return FALSE;}
if (fDateFormat && fmt->fDateFormat && (*fDateFormat != *fmt->fDateFormat)) {return FALSE;}
}
// note: fFromCalendar and fToCalendar hold no persistent state, and therefore do not participate in operator ==.
// fDateFormat has the master calendar for the DateIntervalFormat.
if (fSkeleton != fmt->fSkeleton) {return FALSE;}
if (fDatePattern != fmt->fDatePattern && (fDatePattern == NULL || fmt->fDatePattern == NULL)) {return FALSE;}
if (fDatePattern != fmt->fDatePattern && (fDatePattern == nullptr || fmt->fDatePattern == nullptr)) {return FALSE;}
if (fDatePattern && fmt->fDatePattern && (*fDatePattern != *fmt->fDatePattern)) {return FALSE;}
if (fTimePattern != fmt->fTimePattern && (fTimePattern == NULL || fmt->fTimePattern == NULL)) {return FALSE;}
if (fTimePattern != fmt->fTimePattern && (fTimePattern == nullptr || fmt->fTimePattern == nullptr)) {return FALSE;}
if (fTimePattern && fmt->fTimePattern && (*fTimePattern != *fmt->fTimePattern)) {return FALSE;}
if (fDateTimeFormat != fmt->fDateTimeFormat && (fDateTimeFormat == NULL || fmt->fDateTimeFormat == NULL)) {return FALSE;}
if (fDateTimeFormat != fmt->fDateTimeFormat && (fDateTimeFormat == nullptr || fmt->fDateTimeFormat == nullptr)) {return FALSE;}
if (fDateTimeFormat && fmt->fDateTimeFormat && (*fDateTimeFormat != *fmt->fDateTimeFormat)) {return FALSE;}
if (fLocale != fmt->fLocale) {return FALSE;}
@@ -266,7 +270,7 @@ DateIntervalFormat::format(const Formattable& obj,
if ( obj.getType() == Formattable::kObject ) {
const UObject* formatObj = obj.getObject();
const DateInterval* interval = dynamic_cast<const DateInterval*>(formatObj);
if (interval != NULL) {
if (interval != nullptr) {
return format(interval, appendTo, fieldPosition, status);
}
}
@@ -283,7 +287,7 @@ DateIntervalFormat::format(const DateInterval* dtInterval,
if ( U_FAILURE(status) ) {
return appendTo;
}
if (fDateFormat == NULL || fInfo == NULL) {
if (fDateFormat == nullptr || fInfo == nullptr) {
status = U_INVALID_STATE_ERROR;
return appendTo;
}
@@ -300,6 +304,10 @@ DateIntervalFormat::format(const DateInterval* dtInterval,
FormattedDateInterval DateIntervalFormat::formatToValue(
const DateInterval& dtInterval,
UErrorCode& status) const {
if (U_FAILURE(status)) {
return FormattedDateInterval(status);
}
// LocalPointer only sets OOM status if U_SUCCESS is true.
LocalPointer<FormattedDateIntervalData> result(new FormattedDateIntervalData(status), status);
if (U_FAILURE(status)) {
return FormattedDateInterval(status);
@@ -350,6 +358,10 @@ FormattedDateInterval DateIntervalFormat::formatToValue(
Calendar& fromCalendar,
Calendar& toCalendar,
UErrorCode& status) const {
if (U_FAILURE(status)) {
return FormattedDateInterval(status);
}
// LocalPointer only sets OOM status if U_SUCCESS is true.
LocalPointer<FormattedDateIntervalData> result(new FormattedDateIntervalData(status), status);
if (U_FAILURE(status)) {
return FormattedDateInterval(status);
@@ -444,6 +456,9 @@ DateIntervalFormat::formatImpl(Calendar& fromCalendar,
} else if ( fromCalendar.get(UCAL_SECOND, status) !=
toCalendar.get(UCAL_SECOND, status) ) {
field = UCAL_SECOND;
} else if ( fromCalendar.get(UCAL_MILLISECOND, status) !=
toCalendar.get(UCAL_MILLISECOND, status) ) {
field = UCAL_MILLISECOND;
}
if ( U_FAILURE(status) ) {
@@ -455,7 +470,7 @@ DateIntervalFormat::formatImpl(Calendar& fromCalendar,
*/
return fDateFormat->_format(fromCalendar, appendTo, fphandler, status);
}
UBool fromToOnSameDay = (field==UCAL_AM_PM || field==UCAL_HOUR || field==UCAL_MINUTE || field==UCAL_SECOND);
UBool fromToOnSameDay = (field==UCAL_AM_PM || field==UCAL_HOUR || field==UCAL_MINUTE || field==UCAL_SECOND || field==UCAL_MILLISECOND);
// following call should not set wrong status,
// all the pass-in fields are valid till here
@@ -537,14 +552,17 @@ DateIntervalFormat::setDateIntervalInfo(const DateIntervalInfo& newItvPattern,
UErrorCode& status) {
delete fInfo;
fInfo = new DateIntervalInfo(newItvPattern);
if (fInfo == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
}
// Delete patterns that get reset by initializePattern
delete fDatePattern;
fDatePattern = NULL;
fDatePattern = nullptr;
delete fTimePattern;
fTimePattern = NULL;
fTimePattern = nullptr;
delete fDateTimeFormat;
fDateTimeFormat = NULL;
fDateTimeFormat = nullptr;
if (fDateFormat) {
initializePattern(status);
@@ -562,7 +580,7 @@ DateIntervalFormat::getDateFormat() const {
void
DateIntervalFormat::adoptTimeZone(TimeZone* zone)
{
if (fDateFormat != NULL) {
if (fDateFormat != nullptr) {
fDateFormat->adoptTimeZone(zone);
}
// The fDateFormat has the master calendar for the DateIntervalFormat and has
@@ -580,7 +598,7 @@ DateIntervalFormat::adoptTimeZone(TimeZone* zone)
void
DateIntervalFormat::setTimeZone(const TimeZone& zone)
{
if (fDateFormat != NULL) {
if (fDateFormat != nullptr) {
fDateFormat->setTimeZone(zone);
}
// The fDateFormat has the master calendar for the DateIntervalFormat;
@@ -596,11 +614,11 @@ DateIntervalFormat::setTimeZone(const TimeZone& zone)
const TimeZone&
DateIntervalFormat::getTimeZone() const
{
if (fDateFormat != NULL) {
if (fDateFormat != nullptr) {
Mutex lock(&gFormatterMutex);
return fDateFormat->getTimeZone();
}
// If fDateFormat is NULL (unexpected), create default timezone.
// If fDateFormat is nullptr (unexpected), create default timezone.
return *(TimeZone::createDefault());
}
@@ -608,14 +626,14 @@ DateIntervalFormat::DateIntervalFormat(const Locale& locale,
DateIntervalInfo* dtItvInfo,
const UnicodeString* skeleton,
UErrorCode& status)
: fInfo(NULL),
fDateFormat(NULL),
fFromCalendar(NULL),
fToCalendar(NULL),
: fInfo(nullptr),
fDateFormat(nullptr),
fFromCalendar(nullptr),
fToCalendar(nullptr),
fLocale(locale),
fDatePattern(NULL),
fTimePattern(NULL),
fDateTimeFormat(NULL)
fDatePattern(nullptr),
fTimePattern(nullptr),
fDateTimeFormat(nullptr)
{
LocalPointer<DateIntervalInfo> info(dtItvInfo, status);
LocalPointer<SimpleDateFormat> dtfmt(static_cast<SimpleDateFormat *>(
@@ -643,7 +661,7 @@ DateIntervalFormat::create(const Locale& locale,
UErrorCode& status) {
DateIntervalFormat* f = new DateIntervalFormat(locale, dtitvinf,
skeleton, status);
if ( f == NULL ) {
if ( f == nullptr ) {
status = U_MEMORY_ALLOCATION_ERROR;
delete dtitvinf;
} else if ( U_FAILURE(status) ) {
@@ -760,7 +778,7 @@ DateIntervalFormat::initializePattern(UErrorCode& status) {
// with the time interval.
// The date/time pattern ( such as {0} {1} ) is saved in
// calendar, that is why need to get the CalendarData here.
LocalUResourceBundlePointer dateTimePatternsRes(ures_open(NULL, locale.getBaseName(), &status));
LocalUResourceBundlePointer dateTimePatternsRes(ures_open(nullptr, locale.getBaseName(), &status));
ures_getByKey(dateTimePatternsRes.getAlias(), gCalendarTag,
dateTimePatternsRes.getAlias(), &status);
ures_getByKeyWithFallback(dateTimePatternsRes.getAlias(), gGregorianTag,
@@ -775,6 +793,10 @@ DateIntervalFormat::initializePattern(UErrorCode& status) {
&dateTimeFormatLength, &status);
if ( U_SUCCESS(status) && dateTimeFormatLength >= 3 ) {
fDateTimeFormat = new UnicodeString(dateTimeFormat, dateTimeFormatLength);
if (fDateTimeFormat == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
}
@@ -798,9 +820,9 @@ DateIntervalFormat::initializePattern(UErrorCode& status) {
// the first part of the pattern is empty,
// the second part of the pattern is the full-pattern
// should be used in fall-back.
setPatternInfo(UCAL_DATE, NULL, &pattern, fInfo->getDefaultOrder());
setPatternInfo(UCAL_MONTH, NULL, &pattern, fInfo->getDefaultOrder());
setPatternInfo(UCAL_YEAR, NULL, &pattern, fInfo->getDefaultOrder());
setPatternInfo(UCAL_DATE, nullptr, &pattern, fInfo->getDefaultOrder());
setPatternInfo(UCAL_MONTH, nullptr, &pattern, fInfo->getDefaultOrder());
setPatternInfo(UCAL_YEAR, nullptr, &pattern, fInfo->getDefaultOrder());
} else {
// TODO: fall back
}
@@ -824,9 +846,9 @@ DateIntervalFormat::initializePattern(UErrorCode& status) {
// the first part of the pattern is empty,
// the second part of the pattern is the full-pattern
// should be used in fall-back.
setPatternInfo(UCAL_DATE, NULL, &pattern, fInfo->getDefaultOrder());
setPatternInfo(UCAL_MONTH, NULL, &pattern, fInfo->getDefaultOrder());
setPatternInfo(UCAL_YEAR, NULL, &pattern, fInfo->getDefaultOrder());
setPatternInfo(UCAL_DATE, nullptr, &pattern, fInfo->getDefaultOrder());
setPatternInfo(UCAL_MONTH, nullptr, &pattern, fInfo->getDefaultOrder());
setPatternInfo(UCAL_YEAR, nullptr, &pattern, fInfo->getDefaultOrder());
} else {
/* if both present,
* 1) when the year, month, or day differs,
@@ -861,7 +883,7 @@ DateIntervalFormat::initializePattern(UErrorCode& status) {
* range expression for the time.
*/
if ( fDateTimeFormat == NULL ) {
if ( fDateTimeFormat == nullptr ) {
// earlier failure getting dateTimeFormat
return;
}
@@ -1071,16 +1093,16 @@ DateIntervalFormat::setSeparateDateTimePtn(
int8_t differenceInfo = 0;
const UnicodeString* bestSkeleton = fInfo->getBestSkeleton(*skeleton,
differenceInfo);
/* best skeleton could be NULL.
/* best skeleton could be nullptr.
For example: in "ca" resource file,
interval format is defined as following
intervalFormats{
fallback{"{0} - {1}"}
}
there is no skeletons/interval patterns defined,
and the best skeleton match could be NULL
and the best skeleton match could be nullptr
*/
if ( bestSkeleton == NULL ) {
if ( bestSkeleton == nullptr ) {
return false;
}
@@ -1091,11 +1113,13 @@ DateIntervalFormat::setSeparateDateTimePtn(
status = U_ZERO_ERROR;
fDatePattern = new UnicodeString(DateFormat::getBestPattern(
fLocale, dateSkeleton, status));
// no way to report OOM. :(
}
if ( timeSkeleton.length() != 0) {
status = U_ZERO_ERROR;
fTimePattern = new UnicodeString(DateFormat::getBestPattern(
fLocale, timeSkeleton, status));
// no way to report OOM. :(
}
// difference:
@@ -1151,7 +1175,7 @@ DateIntervalFormat::setFallbackPattern(UCalendarDateFields field,
if ( U_FAILURE(status) ) {
return;
}
setPatternInfo(field, NULL, &pattern, fInfo->getDefaultOrder());
setPatternInfo(field, nullptr, &pattern, fInfo->getDefaultOrder());
}
+38 -27
View File
@@ -66,7 +66,7 @@ static const UChar gDefaultFallbackPattern[] = {LEFT_CURLY_BRACKET, DIGIT_ZERO,
DateIntervalInfo::DateIntervalInfo(UErrorCode& status)
: fFallbackIntervalPattern(gDefaultFallbackPattern),
fFirstDateInPtnIsLaterDate(false),
fIntervalPatterns(NULL)
fIntervalPatterns(nullptr)
{
fIntervalPatterns = initHash(status);
}
@@ -76,7 +76,7 @@ DateIntervalInfo::DateIntervalInfo(UErrorCode& status)
DateIntervalInfo::DateIntervalInfo(const Locale& locale, UErrorCode& status)
: fFallbackIntervalPattern(gDefaultFallbackPattern),
fFirstDateInPtnIsLaterDate(false),
fIntervalPatterns(NULL)
fIntervalPatterns(nullptr)
{
initializeData(locale, status);
}
@@ -126,7 +126,7 @@ DateIntervalInfo::setFallbackIntervalPattern(
DateIntervalInfo::DateIntervalInfo(const DateIntervalInfo& dtitvinf)
: UObject(dtitvinf),
fIntervalPatterns(NULL)
fIntervalPatterns(nullptr)
{
*this = dtitvinf;
}
@@ -161,7 +161,7 @@ DateIntervalInfo::clone() const {
DateIntervalInfo::~DateIntervalInfo() {
deleteHash(fIntervalPatterns);
fIntervalPatterns = NULL;
fIntervalPatterns = nullptr;
}
@@ -189,7 +189,7 @@ DateIntervalInfo::getIntervalPattern(const UnicodeString& skeleton,
}
const UnicodeString* patternsOfOneSkeleton = (UnicodeString*) fIntervalPatterns->get(skeleton);
if ( patternsOfOneSkeleton != NULL ) {
if ( patternsOfOneSkeleton != nullptr ) {
IntervalPatternIndex index = calendarFieldToIntervalIndex(field, status);
if ( U_FAILURE(status) ) {
return result;
@@ -363,7 +363,7 @@ struct DateIntervalInfo::DateIntervalSink : public ResourceSink {
UnicodeString* patternsOfOneSkeleton =
(UnicodeString*)(dateIntervalInfo.fIntervalPatterns->get(skeleton));
if (patternsOfOneSkeleton == NULL || patternsOfOneSkeleton[index].isEmpty()) {
if (patternsOfOneSkeleton == nullptr || patternsOfOneSkeleton[index].isEmpty()) {
UnicodeString pattern = value.getUnicodeString(errorCode);
dateIntervalInfo.setIntervalPatternInternally(skeleton, lrgDiffCalUnit,
pattern, errorCode);
@@ -398,8 +398,8 @@ DateIntervalInfo::initializeData(const Locale& locale, UErrorCode& status)
char calendarType[ULOC_KEYWORDS_CAPACITY]; // to be filled in with the type to use, if all goes well
char localeWithCalendarKey[ULOC_LOCALE_IDENTIFIER_CAPACITY];
// obtain a locale that always has the calendar key value that should be used
(void)ures_getFunctionalEquivalent(localeWithCalendarKey, ULOC_LOCALE_IDENTIFIER_CAPACITY, NULL,
"calendar", "calendar", locName, NULL, FALSE, &status);
(void)ures_getFunctionalEquivalent(localeWithCalendarKey, ULOC_LOCALE_IDENTIFIER_CAPACITY, nullptr,
"calendar", "calendar", locName, nullptr, FALSE, &status);
localeWithCalendarKey[ULOC_LOCALE_IDENTIFIER_CAPACITY-1] = 0; // ensure null termination
// now get the calendar key value from that locale
int32_t calendarTypeLen = uloc_getKeywordValue(localeWithCalendarKey, "calendar", calendarType,
@@ -411,11 +411,11 @@ DateIntervalInfo::initializeData(const Locale& locale, UErrorCode& status)
// Instantiate the resource bundles
UResourceBundle *rb, *calBundle;
rb = ures_open(NULL, locName, &status);
rb = ures_open(nullptr, locName, &status);
if (U_FAILURE(status)) {
return;
}
calBundle = ures_getByKeyWithFallback(rb, gCalendarTag, NULL, &status);
calBundle = ures_getByKeyWithFallback(rb, gCalendarTag, nullptr, &status);
if (U_SUCCESS(status)) {
@@ -424,9 +424,9 @@ DateIntervalInfo::initializeData(const Locale& locale, UErrorCode& status)
// Get the fallback pattern
const UChar* resStr = nullptr;
int32_t resStrLen = 0;
calTypeBundle = ures_getByKeyWithFallback(calBundle, calendarTypeToUse, NULL, &status);
calTypeBundle = ures_getByKeyWithFallback(calBundle, calendarTypeToUse, nullptr, &status);
itvDtPtnResource = ures_getByKeyWithFallback(calTypeBundle,
gIntervalDateTimePatternTag, NULL, &status);
gIntervalDateTimePatternTag, nullptr, &status);
// TODO(ICU-20400): After the fixing, we should find the "fallback" from
// the rb directly by the path "calendar/${calendar}/intervalFormats/fallback".
if ( U_SUCCESS(status) ) {
@@ -437,10 +437,10 @@ DateIntervalInfo::initializeData(const Locale& locale, UErrorCode& status)
// ures_getByKeyWithFallback
UErrorCode localStatus = U_ZERO_ERROR;
UResourceBundle *genericCalBundle =
ures_getByKeyWithFallback(calBundle, gGenericTag, NULL, &localStatus);
ures_getByKeyWithFallback(calBundle, gGenericTag, nullptr, &localStatus);
UResourceBundle *genericItvDtPtnResource =
ures_getByKeyWithFallback(
genericCalBundle, gIntervalDateTimePatternTag, NULL, &localStatus);
genericCalBundle, gIntervalDateTimePatternTag, nullptr, &localStatus);
resStr = ures_getStringByKeyWithFallback(
genericItvDtPtnResource, gFallbackPatternTag, &resStrLen, &localStatus);
ures_close(genericItvDtPtnResource);
@@ -509,8 +509,12 @@ DateIntervalInfo::setIntervalPatternInternally(const UnicodeString& skeleton,
}
UnicodeString* patternsOfOneSkeleton = (UnicodeString*)(fIntervalPatterns->get(skeleton));
UBool emptyHash = false;
if ( patternsOfOneSkeleton == NULL ) {
if ( patternsOfOneSkeleton == nullptr ) {
patternsOfOneSkeleton = new UnicodeString[kIPI_MAX_INDEX];
if (patternsOfOneSkeleton == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
emptyHash = true;
}
@@ -608,7 +612,7 @@ DateIntervalInfo::getBestSkeleton(const UnicodeString& skeleton,
parseSkeleton(*inputSkeleton, inputSkeletonFieldWidth);
int32_t bestDistance = MAX_POSITIVE_INT;
const UnicodeString* bestSkeleton = NULL;
const UnicodeString* bestSkeleton = nullptr;
// 0 means exact the same skeletons;
// 1 means having the same field, but with different length,
@@ -618,8 +622,8 @@ DateIntervalInfo::getBestSkeleton(const UnicodeString& skeleton,
int8_t fieldLength = UPRV_LENGTHOF(skeletonFieldWidth);
int32_t pos = UHASH_FIRST;
const UHashElement* elem = NULL;
while ( (elem = fIntervalPatterns->nextElement(pos)) != NULL ) {
const UHashElement* elem = nullptr;
while ( (elem = fIntervalPatterns->nextElement(pos)) != nullptr ) {
const UHashTok keyTok = elem->key;
UnicodeString* newSkeleton = (UnicodeString*)keyTok.pointer;
#ifdef DTITVINF_DEBUG
@@ -711,6 +715,9 @@ DateIntervalInfo::calendarFieldToIntervalIndex(UCalendarDateFields field,
case UCAL_SECOND:
index = kIPI_SECOND;
break;
case UCAL_MILLISECOND:
index = kIPI_MILLISECOND;
break;
default:
status = U_ILLEGAL_ARGUMENT_ERROR;
}
@@ -722,12 +729,12 @@ DateIntervalInfo::calendarFieldToIntervalIndex(UCalendarDateFields field,
void
DateIntervalInfo::deleteHash(Hashtable* hTable)
{
if ( hTable == NULL ) {
if ( hTable == nullptr ) {
return;
}
int32_t pos = UHASH_FIRST;
const UHashElement* element = NULL;
while ( (element = hTable->nextElement(pos)) != NULL ) {
const UHashElement* element = nullptr;
while ( (element = hTable->nextElement(pos)) != nullptr ) {
const UHashTok valueTok = element->value;
const UnicodeString* value = (UnicodeString*)valueTok.pointer;
delete[] value;
@@ -765,16 +772,16 @@ U_CDECL_END
Hashtable*
DateIntervalInfo::initHash(UErrorCode& status) {
if ( U_FAILURE(status) ) {
return NULL;
return nullptr;
}
Hashtable* hTable;
if ( (hTable = new Hashtable(FALSE, status)) == NULL ) {
if ( (hTable = new Hashtable(FALSE, status)) == nullptr ) {
status = U_MEMORY_ALLOCATION_ERROR;
return NULL;
return nullptr;
}
if ( U_FAILURE(status) ) {
delete hTable;
return NULL;
return nullptr;
}
hTable->setValueComparator(dtitvinfHashTableValueComparator);
return hTable;
@@ -789,14 +796,18 @@ DateIntervalInfo::copyHash(const Hashtable* source,
return;
}
int32_t pos = UHASH_FIRST;
const UHashElement* element = NULL;
const UHashElement* element = nullptr;
if ( source ) {
while ( (element = source->nextElement(pos)) != NULL ) {
while ( (element = source->nextElement(pos)) != nullptr ) {
const UHashTok keyTok = element->key;
const UnicodeString* key = (UnicodeString*)keyTok.pointer;
const UHashTok valueTok = element->value;
const UnicodeString* value = (UnicodeString*)valueTok.pointer;
UnicodeString* copy = new UnicodeString[kIPI_MAX_INDEX];
if (copy == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
int8_t i;
for ( i = 0; i < kIPI_MAX_INDEX; ++i ) {
copy[i] = value[i];
+125 -14
View File
@@ -324,6 +324,7 @@ DateTimePatternGenerator::createEmptyInstance(UErrorCode& status) {
DateTimePatternGenerator::DateTimePatternGenerator(UErrorCode &status) :
skipMatcher(nullptr),
fAvailableFormatKeyHash(nullptr),
fDefaultHourFormatChar(0),
internalErrorCode(U_ZERO_ERROR)
{
fp = new FormatParser();
@@ -338,6 +339,7 @@ DateTimePatternGenerator::DateTimePatternGenerator(UErrorCode &status) :
DateTimePatternGenerator::DateTimePatternGenerator(const Locale& locale, UErrorCode &status) :
skipMatcher(nullptr),
fAvailableFormatKeyHash(nullptr),
fDefaultHourFormatChar(0),
internalErrorCode(U_ZERO_ERROR)
{
fp = new FormatParser();
@@ -356,6 +358,7 @@ DateTimePatternGenerator::DateTimePatternGenerator(const DateTimePatternGenerato
UObject(),
skipMatcher(nullptr),
fAvailableFormatKeyHash(nullptr),
fDefaultHourFormatChar(0),
internalErrorCode(U_ZERO_ERROR)
{
fp = new FormatParser();
@@ -654,6 +657,23 @@ void DateTimePatternGenerator::getAllowedHourFormats(const Locale &locale, UErro
int32_t* allowedFormats = getAllowedHourFormatsLangCountry(language, country, status);
// We need to check if there is an hour cycle on locale
char buffer[8];
int32_t count = locale.getKeywordValue("hours", buffer, sizeof(buffer), status);
fDefaultHourFormatChar = 0;
if (U_SUCCESS(status) && count > 0) {
if(uprv_strcmp(buffer, "h24") == 0) {
fDefaultHourFormatChar = LOW_K;
} else if(uprv_strcmp(buffer, "h23") == 0) {
fDefaultHourFormatChar = CAP_H;
} else if(uprv_strcmp(buffer, "h12") == 0) {
fDefaultHourFormatChar = LOW_H;
} else if(uprv_strcmp(buffer, "h11") == 0) {
fDefaultHourFormatChar = CAP_K;
}
}
// Check if the region has an alias
if (allowedFormats == nullptr) {
UErrorCode localStatus = U_ZERO_ERROR;
@@ -667,13 +687,16 @@ void DateTimePatternGenerator::getAllowedHourFormats(const Locale &locale, UErro
if (allowedFormats != nullptr) { // Lookup is successful
// Here allowedFormats points to a list consisting of key for preferredFormat,
// followed by one or more keys for allowedFormats, then followed by ALLOWED_HOUR_FORMAT_UNKNOWN.
switch (allowedFormats[0]) {
case ALLOWED_HOUR_FORMAT_h: fDefaultHourFormatChar = LOW_H; break;
case ALLOWED_HOUR_FORMAT_H: fDefaultHourFormatChar = CAP_H; break;
case ALLOWED_HOUR_FORMAT_K: fDefaultHourFormatChar = CAP_K; break;
case ALLOWED_HOUR_FORMAT_k: fDefaultHourFormatChar = LOW_K; break;
default: fDefaultHourFormatChar = CAP_H; break;
if (!fDefaultHourFormatChar) {
switch (allowedFormats[0]) {
case ALLOWED_HOUR_FORMAT_h: fDefaultHourFormatChar = LOW_H; break;
case ALLOWED_HOUR_FORMAT_H: fDefaultHourFormatChar = CAP_H; break;
case ALLOWED_HOUR_FORMAT_K: fDefaultHourFormatChar = CAP_K; break;
case ALLOWED_HOUR_FORMAT_k: fDefaultHourFormatChar = LOW_K; break;
default: fDefaultHourFormatChar = CAP_H; break;
}
}
for (int32_t i = 0; i < UPRV_LENGTHOF(fAllowedHourFormats); ++i) {
fAllowedHourFormats[i] = allowedFormats[i + 1];
if (fAllowedHourFormats[i] == ALLOWED_HOUR_FORMAT_UNKNOWN) {
@@ -681,12 +704,39 @@ void DateTimePatternGenerator::getAllowedHourFormats(const Locale &locale, UErro
}
}
} else { // Lookup failed, twice
fDefaultHourFormatChar = CAP_H;
if (!fDefaultHourFormatChar) {
fDefaultHourFormatChar = CAP_H;
}
fAllowedHourFormats[0] = ALLOWED_HOUR_FORMAT_H;
fAllowedHourFormats[1] = ALLOWED_HOUR_FORMAT_UNKNOWN;
}
}
UDateFormatHourCycle
DateTimePatternGenerator::getDefaultHourCycle(UErrorCode& status) const {
if (U_FAILURE(status)) {
return UDAT_HOUR_CYCLE_23;
}
if (fDefaultHourFormatChar == 0) {
// We need to return something, but the caller should ignore it
// anyways since the returned status is a failure.
status = U_UNSUPPORTED_ERROR;
return UDAT_HOUR_CYCLE_23;
}
switch (fDefaultHourFormatChar) {
case CAP_K:
return UDAT_HOUR_CYCLE_11;
case LOW_H:
return UDAT_HOUR_CYCLE_12;
case CAP_H:
return UDAT_HOUR_CYCLE_23;
case LOW_K:
return UDAT_HOUR_CYCLE_24;
default:
UPRV_UNREACHABLE;
}
}
UnicodeString
DateTimePatternGenerator::getSkeleton(const UnicodeString& pattern, UErrorCode&
/*status*/) {
@@ -1479,6 +1529,7 @@ DateTimePatternGenerator::getBestRaw(DateTimeMatcher& source,
UErrorCode &status,
const PtnSkeleton** specifiedSkeletonPtr) {
int32_t bestDistance = 0x7fffffff;
int32_t bestMissingFieldMask = -1;
DistanceInfo tempInfo;
const UnicodeString *bestPattern=nullptr;
const PtnSkeleton* specifiedSkeleton=nullptr;
@@ -1492,8 +1543,15 @@ DateTimePatternGenerator::getBestRaw(DateTimeMatcher& source,
continue;
}
int32_t distance=source.getDistance(trial, includeMask, tempInfo);
if (distance<bestDistance) {
// Because we iterate over a map the order is undefined. Can change between implementations,
// versions, and will very likely be different between Java and C/C++.
// So if we have patterns with the same distance we also look at the missingFieldMask,
// and we favour the smallest one. Because the field is a bitmask this technically means we
// favour differences in the "least significant fields". For example we prefer the one with differences
// in seconds field vs one with difference in the hours field.
if (distance<bestDistance || (distance==bestDistance && bestMissingFieldMask<tempInfo.missingFieldMask)) {
bestDistance=distance;
bestMissingFieldMask=tempInfo.missingFieldMask;
bestPattern=patternMap->getPatternFromSkeleton(*trial.getSkeletonPtr(), &specifiedSkeleton);
missingFields->setTo(tempInfo);
if (distance==0) {
@@ -1546,14 +1604,16 @@ DateTimePatternGenerator::adjustFieldTypes(const UnicodeString& pattern,
dtMatcher->skeleton.original.appendFieldTo(UDATPG_FRACTIONAL_SECOND_FIELD, field);
} else if (dtMatcher->skeleton.type[typeValue]!=0) {
// Here:
// - "reqField" is the field from the originally requested skeleton, with length
// "reqFieldLen".
// - "reqField" is the field from the originally requested skeleton after replacement
// of metacharacters 'j', 'C' and 'J', with length "reqFieldLen".
// - "field" is the field from the found pattern.
//
// The adjusted field should consist of characters from the originally requested
// skeleton, except in the case of UDATPG_HOUR_FIELD or UDATPG_MONTH_FIELD or
// skeleton, except in the case of UDATPG_MONTH_FIELD or
// UDATPG_WEEKDAY_FIELD or UDATPG_YEAR_FIELD, in which case it should consist
// of characters from the found pattern.
// of characters from the found pattern. In some cases of UDATPG_HOUR_FIELD,
// there is adjustment following the "defaultHourFormatChar". There is explanation
// how it is done below.
//
// The length of the adjusted field (adjFieldLen) should match that in the originally
// requested skeleton, except that in the following cases the length of the adjusted field
@@ -1591,9 +1651,28 @@ DateTimePatternGenerator::adjustFieldTypes(const UnicodeString& pattern,
&& (typeValue!= UDATPG_YEAR_FIELD || reqFieldChar==CAP_Y))
? reqFieldChar
: field.charAt(0);
if (typeValue == UDATPG_HOUR_FIELD && (flags & kDTPGSkeletonUsesCapJ) != 0) {
c = fDefaultHourFormatChar;
if (typeValue == UDATPG_HOUR_FIELD && fDefaultHourFormatChar != 0) {
// The adjustment here is required to match spec (https://www.unicode.org/reports/tr35/tr35-dates.html#dfst-hour).
// It is necessary to match the hour-cycle preferred by the Locale.
// Given that, we need to do the following adjustments:
// 1. When hour-cycle is h11 it should replace 'h' by 'K'.
// 2. When hour-cycle is h23 it should replace 'H' by 'k'.
// 3. When hour-cycle is h24 it should replace 'k' by 'H'.
// 4. When hour-cycle is h12 it should replace 'K' by 'h'.
if ((flags & kDTPGSkeletonUsesCapJ) != 0 || reqFieldChar == fDefaultHourFormatChar) {
c = fDefaultHourFormatChar;
} else if (reqFieldChar == LOW_H && fDefaultHourFormatChar == CAP_K) {
c = CAP_K;
} else if (reqFieldChar == CAP_H && fDefaultHourFormatChar == LOW_K) {
c = LOW_K;
} else if (reqFieldChar == LOW_K && fDefaultHourFormatChar == CAP_H) {
c = CAP_H;
} else if (reqFieldChar == CAP_K && fDefaultHourFormatChar == LOW_H) {
c = LOW_H;
}
}
field.remove();
for (int32_t j=adjFieldLen; j>0; --j) {
field += c;
@@ -2118,6 +2197,11 @@ DateTimeMatcher::DateTimeMatcher(const DateTimeMatcher& other) {
copyFrom(other.skeleton);
}
DateTimeMatcher& DateTimeMatcher::operator=(const DateTimeMatcher& other) {
copyFrom(other.skeleton);
return *this;
}
void
DateTimeMatcher::set(const UnicodeString& pattern, FormatParser* fp) {
@@ -2162,6 +2246,33 @@ DateTimeMatcher::set(const UnicodeString& pattern, FormatParser* fp, PtnSkeleton
}
skeletonResult.type[field] = subField;
}
// #20739, we have a skeleton with minutes and milliseconds, but no seconds
//
// Theoretically we would need to check and fix all fields with "gaps":
// for example year-day (no month), month-hour (no day), and so on, All the possible field combinations.
// Plus some smartness: year + hour => should we add month, or add day-of-year?
// What about month + day-of-week, or month + am/pm indicator.
// I think beyond a certain point we should not try to fix bad developer input and try guessing what they mean.
// Garbage in, garbage out.
if (!skeletonResult.original.isFieldEmpty(UDATPG_MINUTE_FIELD)
&& !skeletonResult.original.isFieldEmpty(UDATPG_FRACTIONAL_SECOND_FIELD)
&& skeletonResult.original.isFieldEmpty(UDATPG_SECOND_FIELD)) {
// Force the use of seconds
for (i = 0; dtTypes[i].patternChar != 0; i++) {
if (dtTypes[i].field == UDATPG_SECOND_FIELD) {
// first entry for UDATPG_SECOND_FIELD
skeletonResult.original.populate(UDATPG_SECOND_FIELD, dtTypes[i].patternChar, dtTypes[i].minLen);
skeletonResult.baseOriginal.populate(UDATPG_SECOND_FIELD, dtTypes[i].patternChar, dtTypes[i].minLen);
// We add value.length, same as above, when type is first initialized.
// The value we want to "fake" here is "s", and 1 means "s".length()
int16_t subField = dtTypes[i].type;
skeletonResult.type[UDATPG_SECOND_FIELD] = (subField > 0) ? subField + 1 : subField;
break;
}
}
}
// #13183, handle special behavior for day period characters (a, b, B)
if (!skeletonResult.original.isFieldEmpty(UDATPG_HOUR_FIELD)) {
if (skeletonResult.original.getFieldChar(UDATPG_HOUR_FIELD)==LOW_H || skeletonResult.original.getFieldChar(UDATPG_HOUR_FIELD)==CAP_K) {
+1
View File
@@ -238,6 +238,7 @@ public:
int32_t getDistance(const DateTimeMatcher& other, int32_t includeMask, DistanceInfo& distanceInfo) const;
DateTimeMatcher();
DateTimeMatcher(const DateTimeMatcher& other);
DateTimeMatcher& operator=(const DateTimeMatcher& other);
virtual ~DateTimeMatcher();
int32_t getFieldMask() const;
};
+8 -5
View File
@@ -8,6 +8,7 @@
#include "formatted_string_builder.h"
#include "unicode/ustring.h"
#include "unicode/utf16.h"
#include "unicode/unum.h" // for UNumberFormatFields literals
namespace {
@@ -246,7 +247,7 @@ void FormattedStringBuilder::writeTerminator(UErrorCode& status) {
return;
}
getCharPtr()[position] = 0;
getFieldPtr()[position] = UNUM_FIELD_COUNT;
getFieldPtr()[position] = kUndefinedField;
fLength--;
}
@@ -360,11 +361,11 @@ UnicodeString FormattedStringBuilder::toDebugString() const {
sb.append(toUnicodeString());
sb.append(u"] [", -1);
for (int i = 0; i < fLength; i++) {
if (fieldAt(i) == UNUM_FIELD_COUNT) {
if (fieldAt(i) == kUndefinedField) {
sb.append(u'n');
} else {
} else if (fieldAt(i).getCategory() == UFIELD_CATEGORY_NUMBER) {
char16_t c;
switch (fieldAt(i)) {
switch (fieldAt(i).getField()) {
case UNUM_SIGN_FIELD:
c = u'-';
break;
@@ -399,10 +400,12 @@ UnicodeString FormattedStringBuilder::toDebugString() const {
c = u'$';
break;
default:
c = u'?';
c = u'0' + fieldAt(i).getField();
break;
}
sb.append(c);
} else {
sb.append(u'0' + fieldAt(i).getCategory());
}
}
sb.append(u"]>", -1);
+55 -37
View File
@@ -9,7 +9,8 @@
#include <cstdint>
#include "unicode/unum.h" // for UNUM_FIELD_COUNT
#include <type_traits>
#include "cstring.h"
#include "uassert.h"
#include "fphdlimp.h"
@@ -55,7 +56,20 @@ class U_I18N_API FormattedStringBuilder : public UMemory {
// Field category 0 implies the number category so that the number field
// literals can be directly passed as a Field type.
// See the helper functions in "StringBuilderFieldUtils" below.
typedef uint8_t Field;
// Exported as U_I18N_API so it can be used by other exports on Windows.
struct U_I18N_API Field {
uint8_t bits;
Field() = default;
constexpr Field(uint8_t category, uint8_t field);
inline UFieldCategory getCategory() const;
inline int32_t getField() const;
inline bool isNumeric() const;
inline bool isUndefined() const;
inline bool operator==(const Field& other) const;
inline bool operator!=(const Field& other) const;
};
FormattedStringBuilder &operator=(const FormattedStringBuilder &other);
@@ -204,46 +218,50 @@ class U_I18N_API FormattedStringBuilder : public UMemory {
friend class FormattedValueStringBuilderImpl;
};
static_assert(
std::is_pod<FormattedStringBuilder::Field>::value,
"Field should be a POD type for efficient initialization");
constexpr FormattedStringBuilder::Field::Field(uint8_t category, uint8_t field)
: bits((
U_ASSERT(category <= 0xf),
U_ASSERT(field <= 0xf),
static_cast<uint8_t>((category << 4) | field)
)) {}
/**
* Helper functions for dealing with the Field typedef, which stores fields
* in a compressed format.
* Internal constant for the undefined field for use in FormattedStringBuilder.
*/
class StringBuilderFieldUtils {
public:
struct CategoryFieldPair {
int32_t category;
int32_t field;
};
constexpr FormattedStringBuilder::Field kUndefinedField = {UFIELD_CATEGORY_UNDEFINED, 0};
/** Compile-time function to construct a Field from a category and a field */
template <int32_t category, int32_t field>
static constexpr FormattedStringBuilder::Field compress() {
static_assert(category != 0, "cannot use Undefined category in FieldUtils");
static_assert(category <= 0xf, "only 4 bits for category");
static_assert(field <= 0xf, "only 4 bits for field");
return static_cast<int8_t>((category << 4) | field);
}
/**
* Internal field to signal "numeric" when fields are not supported in NumberFormat.
*/
constexpr FormattedStringBuilder::Field kGeneralNumericField = {UFIELD_CATEGORY_UNDEFINED, 1};
/** Runtime inline function to unpack the category and field from the Field */
static inline CategoryFieldPair expand(FormattedStringBuilder::Field field) {
if (field == UNUM_FIELD_COUNT) {
return {UFIELD_CATEGORY_UNDEFINED, 0};
}
CategoryFieldPair ret = {
(field >> 4),
(field & 0xf)
};
if (ret.category == 0) {
ret.category = UFIELD_CATEGORY_NUMBER;
}
return ret;
}
inline UFieldCategory FormattedStringBuilder::Field::getCategory() const {
return static_cast<UFieldCategory>(bits >> 4);
}
static inline bool isNumericField(FormattedStringBuilder::Field field) {
int8_t category = field >> 4;
return category == 0 || category == UFIELD_CATEGORY_NUMBER;
}
};
inline int32_t FormattedStringBuilder::Field::getField() const {
return bits & 0xf;
}
inline bool FormattedStringBuilder::Field::isNumeric() const {
return getCategory() == UFIELD_CATEGORY_NUMBER || *this == kGeneralNumericField;
}
inline bool FormattedStringBuilder::Field::isUndefined() const {
return getCategory() == UFIELD_CATEGORY_UNDEFINED;
}
inline bool FormattedStringBuilder::Field::operator==(const Field& other) const {
return bits == other.bits;
}
inline bool FormattedStringBuilder::Field::operator!=(const Field& other) const {
return bits != other.bits;
}
U_NAMESPACE_END
-1
View File
@@ -153,7 +153,6 @@ private:
bool nextPositionImpl(ConstrainedFieldPosition& cfpos, FormattedStringBuilder::Field numericField, UErrorCode& status) const;
static bool isIntOrGroup(FormattedStringBuilder::Field field);
static bool isNumericField(FormattedStringBuilder::Field field);
int32_t trimBack(int32_t limit) const;
int32_t trimFront(int32_t start) const;
};
+27 -34
View File
@@ -63,7 +63,7 @@ UBool FormattedValueStringBuilderImpl::nextFieldPosition(FieldPosition& fp, UErr
ConstrainedFieldPosition cfpos;
cfpos.constrainField(UFIELD_CATEGORY_NUMBER, rawField);
cfpos.setState(UFIELD_CATEGORY_NUMBER, rawField, fp.getBeginIndex(), fp.getEndIndex());
if (nextPositionImpl(cfpos, 0, status)) {
if (nextPositionImpl(cfpos, kUndefinedField, status)) {
fp.setBeginIndex(cfpos.getStart());
fp.setEndIndex(cfpos.getLimit());
return TRUE;
@@ -74,7 +74,7 @@ UBool FormattedValueStringBuilderImpl::nextFieldPosition(FieldPosition& fp, UErr
bool inside = false;
int32_t i = fString.fZero;
for (; i < fString.fZero + fString.fLength; i++) {
if (isIntOrGroup(fString.getFieldPtr()[i]) || fString.getFieldPtr()[i] == UNUM_DECIMAL_SEPARATOR_FIELD) {
if (isIntOrGroup(fString.getFieldPtr()[i]) || fString.getFieldPtr()[i] == Field(UFIELD_CATEGORY_NUMBER, UNUM_DECIMAL_SEPARATOR_FIELD)) {
inside = true;
} else if (inside) {
break;
@@ -90,42 +90,40 @@ UBool FormattedValueStringBuilderImpl::nextFieldPosition(FieldPosition& fp, UErr
void FormattedValueStringBuilderImpl::getAllFieldPositions(FieldPositionIteratorHandler& fpih,
UErrorCode& status) const {
ConstrainedFieldPosition cfpos;
while (nextPositionImpl(cfpos, 0, status)) {
while (nextPositionImpl(cfpos, kUndefinedField, status)) {
fpih.addAttribute(cfpos.getField(), cfpos.getStart(), cfpos.getLimit());
}
}
// Signal the end of the string using a field that doesn't exist and that is
// different from UNUM_FIELD_COUNT, which is used for "null number field".
static constexpr Field kEndField = 0xff;
// different from kUndefinedField, which is used for "null field".
static constexpr Field kEndField = Field(0xf, 0xf);
bool FormattedValueStringBuilderImpl::nextPositionImpl(ConstrainedFieldPosition& cfpos, Field numericField, UErrorCode& /*status*/) const {
auto numericCAF = StringBuilderFieldUtils::expand(numericField);
int32_t fieldStart = -1;
Field currField = UNUM_FIELD_COUNT;
Field currField = kUndefinedField;
for (int32_t i = fString.fZero + cfpos.getLimit(); i <= fString.fZero + fString.fLength; i++) {
Field _field = (i < fString.fZero + fString.fLength) ? fString.getFieldPtr()[i] : kEndField;
// Case 1: currently scanning a field.
if (currField != UNUM_FIELD_COUNT) {
if (currField != kUndefinedField) {
if (currField != _field) {
int32_t end = i - fString.fZero;
// Grouping separators can be whitespace; don't throw them out!
if (currField != UNUM_GROUPING_SEPARATOR_FIELD) {
if (currField != Field(UFIELD_CATEGORY_NUMBER, UNUM_GROUPING_SEPARATOR_FIELD)) {
end = trimBack(i - fString.fZero);
}
if (end <= fieldStart) {
// Entire field position is ignorable; skip.
fieldStart = -1;
currField = UNUM_FIELD_COUNT;
currField = kUndefinedField;
i--; // look at this index again
continue;
}
int32_t start = fieldStart;
if (currField != UNUM_GROUPING_SEPARATOR_FIELD) {
if (currField != Field(UFIELD_CATEGORY_NUMBER, UNUM_GROUPING_SEPARATOR_FIELD)) {
start = trimFront(start);
}
auto caf = StringBuilderFieldUtils::expand(currField);
cfpos.setState(caf.category, caf.field, start, end);
cfpos.setState(currField.getCategory(), currField.getField(), start, end);
return true;
}
continue;
@@ -147,51 +145,46 @@ bool FormattedValueStringBuilderImpl::nextPositionImpl(ConstrainedFieldPosition&
return true;
}
// Special case: coalesce NUMERIC if we are pointing at the end of the NUMERIC.
if (numericField != 0
&& cfpos.matchesField(numericCAF.category, numericCAF.field)
if (numericField != kUndefinedField
&& cfpos.matchesField(numericField.getCategory(), numericField.getField())
&& i > fString.fZero
// don't return the same field twice in a row:
&& (i - fString.fZero > cfpos.getLimit()
|| cfpos.getCategory() != numericCAF.category
|| cfpos.getField() != numericCAF.field)
&& isNumericField(fString.getFieldPtr()[i - 1])
&& !isNumericField(_field)) {
|| cfpos.getCategory() != numericField.getCategory()
|| cfpos.getField() != numericField.getField())
&& fString.getFieldPtr()[i - 1].isNumeric()
&& !_field.isNumeric()) {
int j = i - 1;
for (; j >= fString.fZero && isNumericField(fString.getFieldPtr()[j]); j--) {}
for (; j >= fString.fZero && fString.getFieldPtr()[j].isNumeric(); j--) {}
cfpos.setState(
numericCAF.category,
numericCAF.field,
numericField.getCategory(),
numericField.getField(),
j - fString.fZero + 1,
i - fString.fZero);
return true;
}
// Special case: skip over INTEGER; will be coalesced later.
if (_field == UNUM_INTEGER_FIELD) {
_field = UNUM_FIELD_COUNT;
if (_field == Field(UFIELD_CATEGORY_NUMBER, UNUM_INTEGER_FIELD)) {
_field = kUndefinedField;
}
// Case 2: no field starting at this position.
if (_field == UNUM_FIELD_COUNT || _field == kEndField) {
if (_field.isUndefined() || _field == kEndField) {
continue;
}
// Case 3: check for field starting at this position
auto caf = StringBuilderFieldUtils::expand(_field);
if (cfpos.matchesField(caf.category, caf.field)) {
if (cfpos.matchesField(_field.getCategory(), _field.getField())) {
fieldStart = i - fString.fZero;
currField = _field;
}
}
U_ASSERT(currField == UNUM_FIELD_COUNT);
U_ASSERT(currField == kUndefinedField);
return false;
}
bool FormattedValueStringBuilderImpl::isIntOrGroup(Field field) {
return field == UNUM_INTEGER_FIELD
|| field == UNUM_GROUPING_SEPARATOR_FIELD;
}
bool FormattedValueStringBuilderImpl::isNumericField(Field field) {
return StringBuilderFieldUtils::isNumericField(field);
return field == Field(UFIELD_CATEGORY_NUMBER, UNUM_INTEGER_FIELD)
|| field == Field(UFIELD_CATEGORY_NUMBER, UNUM_GROUPING_SEPARATOR_FIELD);
}
int32_t FormattedValueStringBuilderImpl::trimBack(int32_t limit) const {
+2 -1
View File
@@ -62,8 +62,9 @@ class FieldPositionOnlyHandler : public FieldPositionHandler {
// utility subclass FieldPositionIteratorHandler
// exported as U_I18N_API for tests
class FieldPositionIteratorHandler : public FieldPositionHandler {
class U_I18N_API FieldPositionIteratorHandler : public FieldPositionHandler {
FieldPositionIterator* iter; // can be NULL
UVector32* vec;
UErrorCode status;
+1 -1
View File
@@ -160,7 +160,7 @@ const GenderInfo* GenderInfo::loadInstance(const Locale& locale, UErrorCode& sta
if (s == NULL) {
return &gObjs[NEUTRAL];
}
char type_str[256];
char type_str[256] = "";
u_UCharsToChars(s, type_str, resLen + 1);
if (uprv_strcmp(type_str, gNeutralStr) == 0) {
return &gObjs[NEUTRAL];
+267 -35
View File
@@ -21,6 +21,7 @@
#include "unicode/listformatter.h"
#include "unicode/simpleformatter.h"
#include "unicode/ulistformatter.h"
#include "unicode/uscript.h"
#include "fphdlimp.h"
#include "mutex.h"
#include "hash.h"
@@ -35,34 +36,203 @@
U_NAMESPACE_BEGIN
struct ListFormatInternal : public UMemory {
namespace {
class PatternHandler : public UObject {
public:
PatternHandler(const UnicodeString& two, const UnicodeString& end, UErrorCode& errorCode) :
twoPattern(two, 2, 2, errorCode),
endPattern(end, 2, 2, errorCode) { }
PatternHandler(const SimpleFormatter& two, const SimpleFormatter& end) :
twoPattern(two),
endPattern(end) { }
virtual ~PatternHandler();
virtual PatternHandler* clone() const { return new PatternHandler(twoPattern, endPattern); }
virtual const SimpleFormatter& getTwoPattern(const UnicodeString&) const {
return twoPattern;
}
virtual const SimpleFormatter& getEndPattern(const UnicodeString&) const {
return endPattern;
}
protected:
SimpleFormatter twoPattern;
SimpleFormatter endPattern;
};
PatternHandler::~PatternHandler() {
}
class ContextualHandler : public PatternHandler {
public:
ContextualHandler(bool (*testFunc)(const UnicodeString& text),
const UnicodeString& thenTwo,
const UnicodeString& elseTwo,
const UnicodeString& thenEnd,
const UnicodeString& elseEnd,
UErrorCode& errorCode) :
PatternHandler(elseTwo, elseEnd, errorCode),
test(testFunc),
thenTwoPattern(thenTwo, 2, 2, errorCode),
thenEndPattern(thenEnd, 2, 2, errorCode) { }
ContextualHandler(bool (*testFunc)(const UnicodeString& text),
const SimpleFormatter& thenTwo, SimpleFormatter elseTwo,
const SimpleFormatter& thenEnd, SimpleFormatter elseEnd) :
PatternHandler(elseTwo, elseEnd),
test(testFunc),
thenTwoPattern(thenTwo),
thenEndPattern(thenEnd) { }
~ContextualHandler() override;
PatternHandler* clone() const override {
return new ContextualHandler(
test, thenTwoPattern, twoPattern, thenEndPattern, endPattern);
}
const SimpleFormatter& getTwoPattern(
const UnicodeString& text) const override {
return (test)(text) ? thenTwoPattern : twoPattern;
}
const SimpleFormatter& getEndPattern(
const UnicodeString& text) const override {
return (test)(text) ? thenEndPattern : endPattern;
}
private:
bool (*test)(const UnicodeString&);
SimpleFormatter thenTwoPattern;
SimpleFormatter thenEndPattern;
};
ContextualHandler::~ContextualHandler() {
}
static const char16_t *spanishY = u"{0} y {1}";
static const char16_t *spanishE = u"{0} e {1}";
static const char16_t *spanishO = u"{0} o {1}";
static const char16_t *spanishU = u"{0} u {1}";
static const char16_t *hebrewVav = u"{0} \u05D5{1}";
static const char16_t *hebrewVavDash = u"{0} \u05D5-{1}";
// Condiction to change to e.
// Starts with "hi" or "i" but not with "hie" nor "hia"
static bool shouldChangeToE(const UnicodeString& text) {
int32_t len = text.length();
if (len == 0) { return false; }
// Case insensitive match hi but not hie nor hia.
if ((text[0] == u'h' || text[0] == u'H') &&
((len > 1) && (text[1] == u'i' || text[1] == u'I')) &&
((len == 2) || !(text[2] == u'a' || text[2] == u'A' || text[2] == u'e' || text[2] == u'E'))) {
return true;
}
// Case insensitive for "start with i"
if (text[0] == u'i' || text[0] == u'I') { return true; }
return false;
}
// Condiction to change to u.
// Starts with "o", "ho", and "8". Also "11" by itself.
// re: ^((o|ho|8).*|11)$
static bool shouldChangeToU(const UnicodeString& text) {
int32_t len = text.length();
if (len == 0) { return false; }
// Case insensitive match o.* and 8.*
if (text[0] == u'o' || text[0] == u'O' || text[0] == u'8') { return true; }
// Case insensitive match ho.*
if ((text[0] == u'h' || text[0] == u'H') &&
((len > 1) && (text[1] == 'o' || text[1] == u'O'))) {
return true;
}
// match "^11$" and "^11 .*"
if ((len >= 2) && text[0] == u'1' && text[1] == u'1' && (len == 2 || text[2] == u' ')) { return true; }
return false;
}
// Condiction to change to VAV follow by a dash.
// Starts with non Hebrew letter.
static bool shouldChangeToVavDash(const UnicodeString& text) {
if (text.isEmpty()) { return false; }
UErrorCode status = U_ZERO_ERROR;
return uscript_getScript(text.char32At(0), &status) != USCRIPT_HEBREW;
}
PatternHandler* createPatternHandler(
const char* lang, const UnicodeString& two, const UnicodeString& end,
UErrorCode& status) {
if (uprv_strcmp(lang, "es") == 0) {
// Spanish
UnicodeString spanishYStr(TRUE, spanishY, -1);
bool twoIsY = two == spanishYStr;
bool endIsY = end == spanishYStr;
if (twoIsY || endIsY) {
UnicodeString replacement(TRUE, spanishE, -1);
return new ContextualHandler(
shouldChangeToE,
twoIsY ? replacement : two, two,
endIsY ? replacement : end, end, status);
}
UnicodeString spanishOStr(TRUE, spanishO, -1);
bool twoIsO = two == spanishOStr;
bool endIsO = end == spanishOStr;
if (twoIsO || endIsO) {
UnicodeString replacement(TRUE, spanishU, -1);
return new ContextualHandler(
shouldChangeToU,
twoIsO ? replacement : two, two,
endIsO ? replacement : end, end, status);
}
} else if (uprv_strcmp(lang, "he") == 0 || uprv_strcmp(lang, "iw") == 0) {
// Hebrew
UnicodeString hebrewVavStr(TRUE, hebrewVav, -1);
bool twoIsVav = two == hebrewVavStr;
bool endIsVav = end == hebrewVavStr;
if (twoIsVav || endIsVav) {
UnicodeString replacement(TRUE, hebrewVavDash, -1);
return new ContextualHandler(
shouldChangeToVavDash,
twoIsVav ? replacement : two, two,
endIsVav ? replacement : end, end, status);
}
}
return new PatternHandler(two, end, status);
}
} // namespace
struct ListFormatInternal : public UMemory {
SimpleFormatter startPattern;
SimpleFormatter middlePattern;
SimpleFormatter endPattern;
LocalPointer<PatternHandler> patternHandler;
ListFormatInternal(
const UnicodeString& two,
const UnicodeString& start,
const UnicodeString& middle,
const UnicodeString& end,
const Locale& locale,
UErrorCode &errorCode) :
twoPattern(two, 2, 2, errorCode),
startPattern(start, 2, 2, errorCode),
middlePattern(middle, 2, 2, errorCode),
endPattern(end, 2, 2, errorCode) {}
patternHandler(createPatternHandler(locale.getLanguage(), two, end, errorCode), errorCode) { }
ListFormatInternal(const ListFormatData &data, UErrorCode &errorCode) :
twoPattern(data.twoPattern, errorCode),
startPattern(data.startPattern, errorCode),
middlePattern(data.middlePattern, errorCode),
endPattern(data.endPattern, errorCode) { }
patternHandler(createPatternHandler(
data.locale.getLanguage(), data.twoPattern, data.endPattern, errorCode), errorCode) { }
ListFormatInternal(const ListFormatInternal &other) :
twoPattern(other.twoPattern),
startPattern(other.startPattern),
middlePattern(other.middlePattern),
endPattern(other.endPattern) { }
patternHandler(other.patternHandler->clone()) { }
};
@@ -80,7 +250,6 @@ UPRV_FORMATTED_VALUE_SUBCLASS_AUTO_IMPL(FormattedList)
static Hashtable* listPatternHash = nullptr;
static const char STANDARD_STYLE[] = "standard";
U_CDECL_BEGIN
static UBool U_CALLCONV uprv_listformatter_cleanup() {
@@ -179,6 +348,52 @@ const ListFormatInternal* ListFormatter::getListFormatInternal(
return result;
}
#if !UCONFIG_NO_FORMATTING
static const char* typeWidthToStyleString(UListFormatterType type, UListFormatterWidth width) {
switch (type) {
case ULISTFMT_TYPE_AND:
switch (width) {
case ULISTFMT_WIDTH_WIDE:
return "standard";
case ULISTFMT_WIDTH_SHORT:
return "standard-short";
case ULISTFMT_WIDTH_NARROW:
return "standard-narrow";
default:
return nullptr;
}
break;
case ULISTFMT_TYPE_OR:
switch (width) {
case ULISTFMT_WIDTH_WIDE:
return "or";
case ULISTFMT_WIDTH_SHORT:
return "or-short";
case ULISTFMT_WIDTH_NARROW:
return "or-narrow";
default:
return nullptr;
}
break;
case ULISTFMT_TYPE_UNITS:
switch (width) {
case ULISTFMT_WIDTH_WIDE:
return "unit";
case ULISTFMT_WIDTH_SHORT:
return "unit-short";
case ULISTFMT_WIDTH_NARROW:
return "unit-narrow";
default:
return nullptr;
}
}
return nullptr;
}
#endif
static const UChar solidus = 0x2F;
static const UChar aliasPrefix[] = { 0x6C,0x69,0x73,0x74,0x50,0x61,0x74,0x74,0x65,0x72,0x6E,0x2F }; // "listPattern/"
enum {
@@ -279,7 +494,8 @@ ListFormatInternal* ListFormatter::loadListFormatInternal(
errorCode = U_MISSING_RESOURCE_ERROR;
return nullptr;
}
ListFormatInternal* result = new ListFormatInternal(sink.two, sink.start, sink.middle, sink.end, errorCode);
ListFormatInternal* result = new ListFormatInternal(sink.two, sink.start, sink.middle, sink.end, locale, errorCode);
if (result == nullptr) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return nullptr;
@@ -297,9 +513,25 @@ ListFormatter* ListFormatter::createInstance(UErrorCode& errorCode) {
}
ListFormatter* ListFormatter::createInstance(const Locale& locale, UErrorCode& errorCode) {
return createInstance(locale, STANDARD_STYLE, errorCode);
#if !UCONFIG_NO_FORMATTING
return createInstance(locale, ULISTFMT_TYPE_AND, ULISTFMT_WIDTH_WIDE, errorCode);
#else
return createInstance(locale, "standard", errorCode);
#endif
}
#if !UCONFIG_NO_FORMATTING
ListFormatter* ListFormatter::createInstance(
const Locale& locale, UListFormatterType type, UListFormatterWidth width, UErrorCode& errorCode) {
const char* style = typeWidthToStyleString(type, width);
if (style == nullptr) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return nullptr;
}
return createInstance(locale, style, errorCode);
}
#endif
ListFormatter* ListFormatter::createInstance(const Locale& locale, const char *style, UErrorCode& errorCode) {
const ListFormatInternal* listFormatInternal = getListFormatInternal(locale, style, errorCode);
if (U_FAILURE(errorCode)) {
@@ -380,19 +612,6 @@ UnicodeString& ListFormatter::format(
return format(items, nItems, appendTo, -1, offset, errorCode);
}
#if !UCONFIG_NO_FORMATTING
UnicodeString& ListFormatter::format(
const UnicodeString items[],
int32_t nItems,
UnicodeString & appendTo,
FieldPositionIterator* posIter,
UErrorCode& errorCode) const {
int32_t offset;
FieldPositionIteratorHandler handler(posIter, errorCode);
return format_(items, nItems, appendTo, -1, offset, &handler, errorCode);
}
#endif
UnicodeString& ListFormatter::format(
const UnicodeString items[],
int32_t nItems,
@@ -484,16 +703,29 @@ UnicodeString& ListFormatter::format_(
// for n items, there are 2 * (n + 1) boundary including 0 and the upper
// edge.
MaybeStackArray<int32_t, 10> offsets((handler != nullptr) ? 2 * (nItems + 1): 0);
joinStringsAndReplace(
nItems == 2 ? data->twoPattern : data->startPattern,
result,
items[1],
result,
index == 1,
offset,
&offsetFirst,
&offsetSecond,
errorCode);
if (nItems == 2) {
joinStringsAndReplace(
data->patternHandler->getTwoPattern(items[1]),
result,
items[1],
result,
index == 1,
offset,
&offsetFirst,
&offsetSecond,
errorCode);
} else {
joinStringsAndReplace(
data->startPattern,
result,
items[1],
result,
index == 1,
offset,
&offsetFirst,
&offsetSecond,
errorCode);
}
if (handler != nullptr) {
offsets[0] = 0;
prefixLength += offsetFirst;
@@ -517,7 +749,7 @@ UnicodeString& ListFormatter::format_(
}
}
joinStringsAndReplace(
data->endPattern,
data->patternHandler->getEndPattern(items[nItems - 1]),
result,
items[nItems - 1],
result,
+15 -15
View File
@@ -38,6 +38,7 @@
#include "uassert.h"
#include "unicode/numberformatter.h"
#include "number_longnames.h"
#include "number_utypes.h"
#include "sharednumberformat.h"
#include "sharedpluralrules.h"
@@ -47,6 +48,8 @@
U_NAMESPACE_BEGIN
using number::impl::UFormattedNumberData;
static constexpr int32_t WIDTH_INDEX_COUNT = UMEASFMT_WIDTH_NARROW + 1;
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(MeasureFormat)
@@ -504,12 +507,13 @@ UnicodeString &MeasureFormat::formatMeasurePerUnit(
status = U_UNSUPPORTED_ERROR;
return appendTo;
}
number::FormattedNumber result;
UFormattedNumberData result;
if (auto* lnf = df->toNumberFormatter(status)) {
result = lnf->unit(measure.getUnit())
result.quantity.setToDouble(measure.getNumber().getDouble(status));
lnf->unit(measure.getUnit())
.perUnit(perUnit)
.unitWidth(getUnitWidth(fWidth))
.formatDouble(measure.getNumber().getDouble(status), status);
.formatImpl(&result, status);
}
DecimalFormat::fieldPositionHelper(result, pos, appendTo.length(), status);
appendTo.append(result.toTempString(status));
@@ -699,11 +703,12 @@ UnicodeString &MeasureFormat::formatMeasure(
SimpleFormatter formatter(pattern, 0, 1, status);
return QuantityFormatter::format(formatter, formattedNumber, appendTo, pos, status);
}
number::FormattedNumber result;
UFormattedNumberData result;
if (auto* lnf = df->toNumberFormatter(status)) {
result = lnf->unit(amtUnit)
result.quantity.setToDouble(amtNumber.getDouble(status));
lnf->unit(amtUnit)
.unitWidth(getUnitWidth(fWidth))
.formatDouble(amtNumber.getDouble(status), status);
.formatImpl(&result, status);
}
DecimalFormat::fieldPositionHelper(result, pos, appendTo.length(), status);
appendTo.append(result.toTempString(status));
@@ -774,11 +779,6 @@ UnicodeString &MeasureFormat::formatNumeric(
case u's': value = seconds; break;
}
// For undefined field we use UNUM_FIELD_COUNT, for historical reasons.
// See cleanup bug: https://unicode-org.atlassian.net/browse/ICU-20665
// But we give it a clear name, to keep "the ugly part" in one place.
constexpr UNumberFormatFields undefinedField = UNUM_FIELD_COUNT;
// 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...
@@ -787,7 +787,7 @@ UnicodeString &MeasureFormat::formatNumeric(
case u'm':
case u's':
if (protect) {
fsb.appendChar16(c, undefinedField, status);
fsb.appendChar16(c, kUndefinedField, status);
} else {
UnicodeString tmp;
if ((i + 1 < patternLength) && pattern[i + 1] == c) { // doubled
@@ -797,20 +797,20 @@ UnicodeString &MeasureFormat::formatNumeric(
numberFormatter->format(value, tmp, status);
}
// TODO: Use proper Field
fsb.append(tmp, undefinedField, status);
fsb.append(tmp, kUndefinedField, status);
}
break;
case u'\'':
// '' is escaped apostrophe
if ((i + 1 < patternLength) && pattern[i + 1] == c) {
fsb.appendChar16(c, undefinedField, status);
fsb.appendChar16(c, kUndefinedField, status);
i++;
} else {
protect = !protect;
}
break;
default:
fsb.appendChar16(c, undefinedField, status);
fsb.appendChar16(c, kUndefinedField, status);
}
}
+128 -48
View File
@@ -17,9 +17,11 @@
#if !UCONFIG_NO_FORMATTING
#include "unicode/uenum.h"
#include "unicode/errorcode.h"
#include "ustrenum.h"
#include "cstring.h"
#include "uassert.h"
#include "measunit_impl.h"
U_NAMESPACE_BEGIN
@@ -118,7 +120,7 @@ static const char * const gTypes[] = {
// Must be grouped by type and sorted alphabetically within each type.
static const char * const gSubTypes[] = {
"g-force",
"meter-per-second-squared",
"meter-per-square-second",
"arc-minute",
"arc-second",
"degree",
@@ -138,11 +140,11 @@ static const char * const gSubTypes[] = {
"milligram-per-deciliter",
"millimole-per-liter",
"mole",
"part-per-million",
"percent",
"permille",
"permillion",
"permyriad",
"liter-per-100kilometers",
"liter-per-100-kilometer",
"liter-per-kilometer",
"mile-per-gallon",
"mile-per-gallon-imperial",
@@ -535,9 +537,9 @@ static const char * const gSubTypes[] = {
"solar-mass",
"stone",
"ton",
"base",
"percent",
"permille",
"", // TODO(ICU-21076): manual edit of what should have been generated by Java.
"percent", // TODO(ICU-21076): regenerate, deal with duplication.
"permille", // TODO(ICU-21076): regenerate, deal with duplication.
"gigawatt",
"horsepower",
"kilowatt",
@@ -547,13 +549,13 @@ static const char * const gSubTypes[] = {
"atmosphere",
"bar",
"hectopascal",
"inch-hg",
"inch-ofhg",
"kilopascal",
"megapascal",
"millibar",
"millimeter-of-mercury",
"millimeter-ofhg",
"pascal",
"pound-per-square-inch",
"pound-force-per-square-inch",
"kilometer-per-hour",
"knot",
"meter-per-second",
@@ -563,7 +565,7 @@ static const char * const gSubTypes[] = {
"generic",
"kelvin",
"newton-meter",
"pound-foot",
"pound-force-foot",
"acre-foot",
"barrel",
"bushel",
@@ -780,29 +782,29 @@ MeasureUnit MeasureUnit::getMole() {
}
MeasureUnit *MeasureUnit::createPartPerMillion(UErrorCode &status) {
return MeasureUnit::create(3, 4, status);
}
MeasureUnit MeasureUnit::getPartPerMillion() {
return MeasureUnit(3, 4);
}
MeasureUnit *MeasureUnit::createPercent(UErrorCode &status) {
return MeasureUnit::create(3, 5, status);
}
MeasureUnit MeasureUnit::getPercent() {
return MeasureUnit(3, 5);
}
MeasureUnit *MeasureUnit::createPermille(UErrorCode &status) {
return MeasureUnit::create(3, 6, status);
}
MeasureUnit MeasureUnit::getPermille() {
MeasureUnit MeasureUnit::getPartPerMillion() {
return MeasureUnit(3, 6);
}
MeasureUnit *MeasureUnit::createPercent(UErrorCode &status) {
return MeasureUnit::create(3, 4, status);
}
MeasureUnit MeasureUnit::getPercent() {
return MeasureUnit(3, 4);
}
MeasureUnit *MeasureUnit::createPermille(UErrorCode &status) {
return MeasureUnit::create(3, 5, status);
}
MeasureUnit MeasureUnit::getPermille() {
return MeasureUnit(3, 5);
}
MeasureUnit *MeasureUnit::createPermyriad(UErrorCode &status) {
return MeasureUnit::create(3, 7, status);
}
@@ -1990,10 +1992,10 @@ MeasureUnit MeasureUnit::getTeaspoon() {
// End generated code
static int32_t binarySearch(
const char * const * array, int32_t start, int32_t end, const char * key) {
const char * const * array, int32_t start, int32_t end, StringPiece key) {
while (start < end) {
int32_t mid = (start + end) / 2;
int32_t cmp = uprv_strcmp(array[mid], key);
int32_t cmp = StringPiece(array[mid]).compare(key);
if (cmp < 0) {
start = mid + 1;
continue;
@@ -2006,24 +2008,62 @@ static int32_t binarySearch(
return -1;
}
MeasureUnit::MeasureUnit() {
fCurrency[0] = 0;
fTypeId = kBaseTypeIdx;
fSubTypeId = kBaseSubTypeIdx;
MeasureUnit::MeasureUnit() : MeasureUnit(kBaseTypeIdx, kBaseSubTypeIdx) {
}
MeasureUnit::MeasureUnit(int32_t typeId, int32_t subTypeId)
: fImpl(nullptr), fSubTypeId(subTypeId), fTypeId(typeId) {
}
MeasureUnit::MeasureUnit(const MeasureUnit &other)
: fTypeId(other.fTypeId), fSubTypeId(other.fSubTypeId) {
uprv_strcpy(fCurrency, other.fCurrency);
: fImpl(nullptr) {
*this = other;
}
MeasureUnit::MeasureUnit(MeasureUnit &&other) noexcept
: fImpl(other.fImpl),
fSubTypeId(other.fSubTypeId),
fTypeId(other.fTypeId) {
other.fImpl = nullptr;
}
MeasureUnit::MeasureUnit(MeasureUnitImpl&& impl)
: fImpl(nullptr), fSubTypeId(-1), fTypeId(-1) {
if (!findBySubType(impl.identifier.toStringPiece(), this)) {
fImpl = new MeasureUnitImpl(std::move(impl));
}
}
MeasureUnit &MeasureUnit::operator=(const MeasureUnit &other) {
if (this == &other) {
return *this;
}
delete fImpl;
if (other.fImpl) {
ErrorCode localStatus;
fImpl = new MeasureUnitImpl(other.fImpl->copy(localStatus));
if (!fImpl || localStatus.isFailure()) {
// Unrecoverable allocation error; set to the default unit
*this = MeasureUnit();
return *this;
}
} else {
fImpl = nullptr;
}
fTypeId = other.fTypeId;
fSubTypeId = other.fSubTypeId;
return *this;
}
MeasureUnit &MeasureUnit::operator=(MeasureUnit &&other) noexcept {
if (this == &other) {
return *this;
}
delete fImpl;
fImpl = other.fImpl;
other.fImpl = nullptr;
fTypeId = other.fTypeId;
fSubTypeId = other.fSubTypeId;
uprv_strcpy(fCurrency, other.fCurrency);
return *this;
}
@@ -2032,14 +2072,28 @@ MeasureUnit *MeasureUnit::clone() const {
}
MeasureUnit::~MeasureUnit() {
delete fImpl;
fImpl = nullptr;
}
const char *MeasureUnit::getType() const {
// We have a type & subtype only if fTypeId is present.
if (fTypeId == -1) {
return "";
}
return gTypes[fTypeId];
}
const char *MeasureUnit::getSubtype() const {
return fCurrency[0] == 0 ? gSubTypes[getOffset()] : fCurrency;
// We have a type & subtype only if fTypeId is present.
if (fTypeId == -1) {
return "";
}
return getIdentifier();
}
const char *MeasureUnit::getIdentifier() const {
return fImpl ? fImpl->identifier.data() : gSubTypes[getOffset()];
}
UBool MeasureUnit::operator==(const UObject& other) const {
@@ -2050,10 +2104,7 @@ UBool MeasureUnit::operator==(const UObject& other) const {
return FALSE;
}
const MeasureUnit &rhs = static_cast<const MeasureUnit&>(other);
return (
fTypeId == rhs.fTypeId
&& fSubTypeId == rhs.fSubTypeId
&& uprv_strcmp(fCurrency, rhs.fCurrency) == 0);
return uprv_strcmp(getIdentifier(), rhs.getIdentifier()) == 0;
}
int32_t MeasureUnit::getIndex() const {
@@ -2138,10 +2189,29 @@ int32_t MeasureUnit::internalGetIndexForTypeAndSubtype(const char *type, const c
return gIndexes[t] + st - gOffsets[t];
}
bool MeasureUnit::findBySubType(StringPiece subType, MeasureUnit* output) {
for (int32_t t = 0; t < UPRV_LENGTHOF(gOffsets) - 1; t++) {
// Skip currency units
if (gIndexes[t] == gIndexes[t + 1]) {
continue;
}
int32_t st = binarySearch(gSubTypes, gOffsets[t], gOffsets[t + 1], subType);
if (st >= 0) {
output->setTo(t, st - gOffsets[t]);
return true;
}
}
return false;
}
MeasureUnit MeasureUnit::resolveUnitPerUnit(
const MeasureUnit &unit, const MeasureUnit &perUnit, bool* isResolved) {
int32_t unitOffset = unit.getOffset();
int32_t perUnitOffset = perUnit.getOffset();
if (unitOffset == -1 || perUnitOffset == -1) {
*isResolved = false;
return MeasureUnit();
}
// binary search for (unitOffset, perUnitOffset)
int32_t start = 0;
@@ -2189,18 +2259,24 @@ void MeasureUnit::initTime(const char *timeId) {
fSubTypeId = result - gOffsets[fTypeId];
}
void MeasureUnit::initCurrency(const char *isoCurrency) {
void MeasureUnit::initCurrency(StringPiece isoCurrency) {
int32_t result = binarySearch(gTypes, 0, UPRV_LENGTHOF(gTypes), "currency");
U_ASSERT(result != -1);
fTypeId = result;
result = binarySearch(
gSubTypes, gOffsets[fTypeId], gOffsets[fTypeId + 1], isoCurrency);
if (result != -1) {
fSubTypeId = result - gOffsets[fTypeId];
} else {
uprv_strncpy(fCurrency, isoCurrency, UPRV_LENGTHOF(fCurrency));
fCurrency[3] = 0;
if (result == -1) {
fImpl = new MeasureUnitImpl(MeasureUnitImpl::forCurrencyCode(isoCurrency));
if (fImpl) {
fSubTypeId = -1;
return;
}
// malloc error: fall back to the undefined currency
result = binarySearch(
gSubTypes, gOffsets[fTypeId], gOffsets[fTypeId + 1], kDefaultCurrency8);
U_ASSERT(result != -1);
}
fSubTypeId = result - gOffsets[fTypeId];
}
void MeasureUnit::initNoUnit(const char *subtype) {
@@ -2215,10 +2291,14 @@ void MeasureUnit::initNoUnit(const char *subtype) {
void MeasureUnit::setTo(int32_t typeId, int32_t subTypeId) {
fTypeId = typeId;
fSubTypeId = subTypeId;
fCurrency[0] = 0;
delete fImpl;
fImpl = nullptr;
}
int32_t MeasureUnit::getOffset() const {
if (fTypeId < 0 || fSubTypeId < 0) {
return -1;
}
return gOffsets[fTypeId] + fSubTypeId;
}
+893
View File
@@ -0,0 +1,893 @@
// © 2020 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
// Extra functions for MeasureUnit not needed for all clients.
// Separate .o file so that it can be removed for modularity.
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
// Allow implicit conversion from char16_t* to UnicodeString for this file:
// Helpful in toString methods and elsewhere.
#define UNISTR_FROM_STRING_EXPLICIT
#include <cstdlib>
#include "cstring.h"
#include "measunit_impl.h"
#include "uarrsort.h"
#include "uassert.h"
#include "ucln_in.h"
#include "umutex.h"
#include "unicode/errorcode.h"
#include "unicode/localpointer.h"
#include "unicode/measunit.h"
#include "unicode/ucharstrie.h"
#include "unicode/ucharstriebuilder.h"
#include "cstr.h"
U_NAMESPACE_BEGIN
namespace {
// TODO: Propose a new error code for this?
constexpr UErrorCode kUnitIdentifierSyntaxError = U_ILLEGAL_ARGUMENT_ERROR;
// Trie value offset for SI Prefixes. This is big enough to ensure we only
// insert positive integers into the trie.
constexpr int32_t kSIPrefixOffset = 64;
// Trie value offset for compound parts, e.g. "-per-", "-", "-and-".
constexpr int32_t kCompoundPartOffset = 128;
enum CompoundPart {
// Represents "-per-"
COMPOUND_PART_PER = kCompoundPartOffset,
// Represents "-"
COMPOUND_PART_TIMES,
// Represents "-and-"
COMPOUND_PART_AND,
};
// Trie value offset for "per-".
constexpr int32_t kInitialCompoundPartOffset = 192;
enum InitialCompoundPart {
// Represents "per-", the only compound part that can appear at the start of
// an identifier.
INITIAL_COMPOUND_PART_PER = kInitialCompoundPartOffset,
};
// Trie value offset for powers like "square-", "cubic-", "p2-" etc.
constexpr int32_t kPowerPartOffset = 256;
enum PowerPart {
POWER_PART_P2 = kPowerPartOffset + 2,
POWER_PART_P3,
POWER_PART_P4,
POWER_PART_P5,
POWER_PART_P6,
POWER_PART_P7,
POWER_PART_P8,
POWER_PART_P9,
POWER_PART_P10,
POWER_PART_P11,
POWER_PART_P12,
POWER_PART_P13,
POWER_PART_P14,
POWER_PART_P15,
};
// Trie value offset for simple units, e.g. "gram", "nautical-mile",
// "fluid-ounce-imperial".
constexpr int32_t kSimpleUnitOffset = 512;
const struct SIPrefixStrings {
const char* const string;
UMeasureSIPrefix value;
} gSIPrefixStrings[] = {
{ "yotta", UMEASURE_SI_PREFIX_YOTTA },
{ "zetta", UMEASURE_SI_PREFIX_ZETTA },
{ "exa", UMEASURE_SI_PREFIX_EXA },
{ "peta", UMEASURE_SI_PREFIX_PETA },
{ "tera", UMEASURE_SI_PREFIX_TERA },
{ "giga", UMEASURE_SI_PREFIX_GIGA },
{ "mega", UMEASURE_SI_PREFIX_MEGA },
{ "kilo", UMEASURE_SI_PREFIX_KILO },
{ "hecto", UMEASURE_SI_PREFIX_HECTO },
{ "deka", UMEASURE_SI_PREFIX_DEKA },
{ "deci", UMEASURE_SI_PREFIX_DECI },
{ "centi", UMEASURE_SI_PREFIX_CENTI },
{ "milli", UMEASURE_SI_PREFIX_MILLI },
{ "micro", UMEASURE_SI_PREFIX_MICRO },
{ "nano", UMEASURE_SI_PREFIX_NANO },
{ "pico", UMEASURE_SI_PREFIX_PICO },
{ "femto", UMEASURE_SI_PREFIX_FEMTO },
{ "atto", UMEASURE_SI_PREFIX_ATTO },
{ "zepto", UMEASURE_SI_PREFIX_ZEPTO },
{ "yocto", UMEASURE_SI_PREFIX_YOCTO },
};
// TODO(ICU-21059): Get this list from data
const char16_t* const gSimpleUnits[] = {
u"candela",
u"carat",
u"gram",
u"ounce",
u"ounce-troy",
u"pound",
u"kilogram",
u"stone",
u"ton",
u"metric-ton",
u"earth-mass",
u"solar-mass",
u"point",
u"inch",
u"foot",
u"yard",
u"meter",
u"fathom",
u"furlong",
u"mile",
u"nautical-mile",
u"mile-scandinavian",
u"100-kilometer",
u"earth-radius",
u"solar-radius",
u"astronomical-unit",
u"light-year",
u"parsec",
u"second",
u"minute",
u"hour",
u"day",
u"day-person",
u"week",
u"week-person",
u"month",
u"month-person",
u"year",
u"year-person",
u"decade",
u"century",
u"ampere",
u"fahrenheit",
u"kelvin",
u"celsius",
u"arc-second",
u"arc-minute",
u"degree",
u"radian",
u"revolution",
u"item",
u"mole",
u"permillion",
u"permyriad",
u"permille",
u"percent",
u"karat",
u"portion",
u"bit",
u"byte",
u"dot",
u"pixel",
u"em",
u"hertz",
u"newton",
u"pound-force",
u"pascal",
u"bar",
u"atmosphere",
u"ofhg",
u"electronvolt",
u"dalton",
u"joule",
u"calorie",
u"british-thermal-unit",
u"foodcalorie",
u"therm-us",
u"watt",
u"horsepower",
u"solar-luminosity",
u"volt",
u"ohm",
u"dunam",
u"acre",
u"hectare",
u"teaspoon",
u"tablespoon",
u"fluid-ounce-imperial",
u"fluid-ounce",
u"cup",
u"cup-metric",
u"pint",
u"pint-metric",
u"quart",
u"liter",
u"gallon",
u"gallon-imperial",
u"bushel",
u"barrel",
u"knot",
u"g-force",
u"lux",
};
icu::UInitOnce gUnitExtrasInitOnce = U_INITONCE_INITIALIZER;
char16_t* kSerializedUnitExtrasStemTrie = nullptr;
UBool U_CALLCONV cleanupUnitExtras() {
uprv_free(kSerializedUnitExtrasStemTrie);
kSerializedUnitExtrasStemTrie = nullptr;
gUnitExtrasInitOnce.reset();
return TRUE;
}
void U_CALLCONV initUnitExtras(UErrorCode& status) {
ucln_i18n_registerCleanup(UCLN_I18N_UNIT_EXTRAS, cleanupUnitExtras);
UCharsTrieBuilder b(status);
if (U_FAILURE(status)) { return; }
// Add SI prefixes
for (const auto& siPrefixInfo : gSIPrefixStrings) {
UnicodeString uSIPrefix(siPrefixInfo.string, -1, US_INV);
b.add(uSIPrefix, siPrefixInfo.value + kSIPrefixOffset, status);
}
if (U_FAILURE(status)) { return; }
// Add syntax parts (compound, power prefixes)
b.add(u"-per-", COMPOUND_PART_PER, status);
b.add(u"-", COMPOUND_PART_TIMES, status);
b.add(u"-and-", COMPOUND_PART_AND, status);
b.add(u"per-", INITIAL_COMPOUND_PART_PER, status);
b.add(u"square-", POWER_PART_P2, status);
b.add(u"cubic-", POWER_PART_P3, status);
b.add(u"p2-", POWER_PART_P2, status);
b.add(u"p3-", POWER_PART_P3, status);
b.add(u"p4-", POWER_PART_P4, status);
b.add(u"p5-", POWER_PART_P5, status);
b.add(u"p6-", POWER_PART_P6, status);
b.add(u"p7-", POWER_PART_P7, status);
b.add(u"p8-", POWER_PART_P8, status);
b.add(u"p9-", POWER_PART_P9, status);
b.add(u"p10-", POWER_PART_P10, status);
b.add(u"p11-", POWER_PART_P11, status);
b.add(u"p12-", POWER_PART_P12, status);
b.add(u"p13-", POWER_PART_P13, status);
b.add(u"p14-", POWER_PART_P14, status);
b.add(u"p15-", POWER_PART_P15, status);
if (U_FAILURE(status)) { return; }
// Add sanctioned simple units by offset
int32_t simpleUnitOffset = kSimpleUnitOffset;
for (auto simpleUnit : gSimpleUnits) {
b.add(simpleUnit, simpleUnitOffset++, status);
}
// Build the CharsTrie
// TODO: Use SLOW or FAST here?
UnicodeString result;
b.buildUnicodeString(USTRINGTRIE_BUILD_FAST, result, status);
if (U_FAILURE(status)) { return; }
// Copy the result into the global constant pointer
size_t numBytes = result.length() * sizeof(char16_t);
kSerializedUnitExtrasStemTrie = static_cast<char16_t*>(uprv_malloc(numBytes));
uprv_memcpy(kSerializedUnitExtrasStemTrie, result.getBuffer(), numBytes);
}
class Token {
public:
Token(int32_t match) : fMatch(match) {}
enum Type {
TYPE_UNDEFINED,
TYPE_SI_PREFIX,
// Token type for "-per-", "-", and "-and-".
TYPE_COMPOUND_PART,
// Token type for "per-".
TYPE_INITIAL_COMPOUND_PART,
TYPE_POWER_PART,
TYPE_SIMPLE_UNIT,
};
// Calling getType() is invalid, resulting in an assertion failure, if Token
// value isn't positive.
Type getType() const {
U_ASSERT(fMatch > 0);
if (fMatch < kCompoundPartOffset) {
return TYPE_SI_PREFIX;
}
if (fMatch < kInitialCompoundPartOffset) {
return TYPE_COMPOUND_PART;
}
if (fMatch < kPowerPartOffset) {
return TYPE_INITIAL_COMPOUND_PART;
}
if (fMatch < kSimpleUnitOffset) {
return TYPE_POWER_PART;
}
return TYPE_SIMPLE_UNIT;
}
UMeasureSIPrefix getSIPrefix() const {
U_ASSERT(getType() == TYPE_SI_PREFIX);
return static_cast<UMeasureSIPrefix>(fMatch - kSIPrefixOffset);
}
// Valid only for tokens with type TYPE_COMPOUND_PART.
int32_t getMatch() const {
U_ASSERT(getType() == TYPE_COMPOUND_PART);
return fMatch;
}
int32_t getInitialCompoundPart() const {
// Even if there is only one InitialCompoundPart value, we have this
// function for the simplicity of code consistency.
U_ASSERT(getType() == TYPE_INITIAL_COMPOUND_PART);
// Defensive: if this assert fails, code using this function also needs
// to change.
U_ASSERT(fMatch == INITIAL_COMPOUND_PART_PER);
return fMatch;
}
int8_t getPower() const {
U_ASSERT(getType() == TYPE_POWER_PART);
return static_cast<int8_t>(fMatch - kPowerPartOffset);
}
int32_t getSimpleUnitIndex() const {
U_ASSERT(getType() == TYPE_SIMPLE_UNIT);
return fMatch - kSimpleUnitOffset;
}
private:
int32_t fMatch;
};
class Parser {
public:
/**
* Factory function for parsing the given identifier.
*
* @param source The identifier to parse. This function does not make a copy
* of source: the underlying string that source points at, must outlive the
* parser.
* @param status ICU error code.
*/
static Parser from(StringPiece source, UErrorCode& status) {
if (U_FAILURE(status)) {
return Parser();
}
umtx_initOnce(gUnitExtrasInitOnce, &initUnitExtras, status);
if (U_FAILURE(status)) {
return Parser();
}
return Parser(source);
}
MeasureUnitImpl parse(UErrorCode& status) {
MeasureUnitImpl result;
parseImpl(result, status);
return result;
}
private:
// Tracks parser progress: the offset into fSource.
int32_t fIndex = 0;
// Since we're not owning this memory, whatever is passed to the constructor
// should live longer than this Parser - and the parser shouldn't return any
// references to that string.
StringPiece fSource;
UCharsTrie fTrie;
// Set to true when we've seen a "-per-" or a "per-", after which all units
// are in the denominator. Until we find an "-and-", at which point the
// identifier is invalid pending TODO(CLDR-13700).
bool fAfterPer = false;
Parser() : fSource(""), fTrie(u"") {}
Parser(StringPiece source)
: fSource(source), fTrie(kSerializedUnitExtrasStemTrie) {}
inline bool hasNext() const {
return fIndex < fSource.length();
}
// Returns the next Token parsed from fSource, advancing fIndex to the end
// of that token in fSource. In case of U_FAILURE(status), the token
// returned will cause an abort if getType() is called on it.
Token nextToken(UErrorCode& status) {
fTrie.reset();
int32_t match = -1;
// Saves the position in the fSource string for the end of the most
// recent matching token.
int32_t previ = -1;
// Find the longest token that matches a value in the trie:
while (fIndex < fSource.length()) {
auto result = fTrie.next(fSource.data()[fIndex++]);
if (result == USTRINGTRIE_NO_MATCH) {
break;
} else if (result == USTRINGTRIE_NO_VALUE) {
continue;
}
U_ASSERT(USTRINGTRIE_HAS_VALUE(result));
match = fTrie.getValue();
previ = fIndex;
if (result == USTRINGTRIE_FINAL_VALUE) {
break;
}
U_ASSERT(result == USTRINGTRIE_INTERMEDIATE_VALUE);
// continue;
}
if (match < 0) {
status = kUnitIdentifierSyntaxError;
} else {
fIndex = previ;
}
return Token(match);
}
/**
* Returns the next "single unit" via result.
*
* If a "-per-" was parsed, the result will have appropriate negative
* dimensionality.
*
* Returns an error if we parse both compound units and "-and-", since mixed
* compound units are not yet supported - TODO(CLDR-13700).
*
* @param result Will be overwritten by the result, if status shows success.
* @param sawAnd If an "-and-" was parsed prior to finding the "single
* unit", sawAnd is set to true. If not, it is left as is.
* @param status ICU error code.
*/
void nextSingleUnit(SingleUnitImpl& result, bool& sawAnd, UErrorCode& status) {
if (U_FAILURE(status)) {
return;
}
// state:
// 0 = no tokens seen yet (will accept power, SI prefix, or simple unit)
// 1 = power token seen (will not accept another power token)
// 2 = SI prefix token seen (will not accept a power or SI prefix token)
int32_t state = 0;
bool atStart = fIndex == 0;
Token token = nextToken(status);
if (U_FAILURE(status)) { return; }
if (atStart) {
// Identifiers optionally start with "per-".
if (token.getType() == Token::TYPE_INITIAL_COMPOUND_PART) {
U_ASSERT(token.getInitialCompoundPart() == INITIAL_COMPOUND_PART_PER);
fAfterPer = true;
result.dimensionality = -1;
token = nextToken(status);
if (U_FAILURE(status)) { return; }
}
} else {
// All other SingleUnit's are separated from previous SingleUnit's
// via a compound part:
if (token.getType() != Token::TYPE_COMPOUND_PART) {
status = kUnitIdentifierSyntaxError;
return;
}
switch (token.getMatch()) {
case COMPOUND_PART_PER:
if (sawAnd) {
// Mixed compound units not yet supported,
// TODO(CLDR-13700).
status = kUnitIdentifierSyntaxError;
return;
}
fAfterPer = true;
result.dimensionality = -1;
break;
case COMPOUND_PART_TIMES:
if (fAfterPer) {
result.dimensionality = -1;
}
break;
case COMPOUND_PART_AND:
if (fAfterPer) {
// Can't start with "-and-", and mixed compound units
// not yet supported, TODO(CLDR-13700).
status = kUnitIdentifierSyntaxError;
return;
}
sawAnd = true;
break;
}
token = nextToken(status);
if (U_FAILURE(status)) { return; }
}
// Read tokens until we have a complete SingleUnit or we reach the end.
while (true) {
switch (token.getType()) {
case Token::TYPE_POWER_PART:
if (state > 0) {
status = kUnitIdentifierSyntaxError;
return;
}
result.dimensionality *= token.getPower();
state = 1;
break;
case Token::TYPE_SI_PREFIX:
if (state > 1) {
status = kUnitIdentifierSyntaxError;
return;
}
result.siPrefix = token.getSIPrefix();
state = 2;
break;
case Token::TYPE_SIMPLE_UNIT:
result.index = token.getSimpleUnitIndex();
return;
default:
status = kUnitIdentifierSyntaxError;
return;
}
if (!hasNext()) {
// We ran out of tokens before finding a complete single unit.
status = kUnitIdentifierSyntaxError;
return;
}
token = nextToken(status);
if (U_FAILURE(status)) {
return;
}
}
}
/// @param result is modified, not overridden. Caller must pass in a
/// default-constructed (empty) MeasureUnitImpl instance.
void parseImpl(MeasureUnitImpl& result, UErrorCode& status) {
if (U_FAILURE(status)) {
return;
}
if (fSource.empty()) {
// The dimenionless unit: nothing to parse. leave result as is.
return;
}
int32_t unitNum = 0;
while (hasNext()) {
bool sawAnd = false;
SingleUnitImpl singleUnit;
nextSingleUnit(singleUnit, sawAnd, status);
if (U_FAILURE(status)) {
return;
}
U_ASSERT(!singleUnit.isDimensionless());
bool added = result.append(singleUnit, status);
if (sawAnd && !added) {
// Two similar units are not allowed in a mixed unit
status = kUnitIdentifierSyntaxError;
return;
}
if ((++unitNum) >= 2) {
// nextSingleUnit fails appropriately for "per" and "and" in the
// same identifier. It doesn't fail for other compound units
// (COMPOUND_PART_TIMES). Consequently we take care of that
// here.
UMeasureUnitComplexity complexity =
sawAnd ? UMEASURE_UNIT_MIXED : UMEASURE_UNIT_COMPOUND;
if (unitNum == 2) {
U_ASSERT(result.complexity == UMEASURE_UNIT_SINGLE);
result.complexity = complexity;
} else if (result.complexity != complexity) {
// Can't have mixed compound units
status = kUnitIdentifierSyntaxError;
return;
}
}
}
}
};
int32_t U_CALLCONV
compareSingleUnits(const void* /*context*/, const void* left, const void* right) {
auto realLeft = static_cast<const SingleUnitImpl* const*>(left);
auto realRight = static_cast<const SingleUnitImpl* const*>(right);
return (*realLeft)->compareTo(**realRight);
}
/**
* Generate the identifier string for a single unit in place.
*
* Does not support the dimensionless SingleUnitImpl: calling serializeSingle
* with the dimensionless unit results in an U_INTERNAL_PROGRAM_ERROR.
*
* @param first If singleUnit is part of a compound unit, and not its first
* single unit, set this to false. Otherwise: set to true.
*/
void serializeSingle(const SingleUnitImpl& singleUnit, bool first, CharString& output, UErrorCode& status) {
if (first && singleUnit.dimensionality < 0) {
// Essentially the "unary per". For compound units with a numerator, the
// caller takes care of the "binary per".
output.append("per-", status);
}
if (singleUnit.isDimensionless()) {
status = U_INTERNAL_PROGRAM_ERROR;
return;
}
int8_t posPower = std::abs(singleUnit.dimensionality);
if (posPower == 0) {
status = U_INTERNAL_PROGRAM_ERROR;
} else if (posPower == 1) {
// no-op
} else if (posPower == 2) {
output.append("square-", status);
} else if (posPower == 3) {
output.append("cubic-", status);
} else if (posPower < 10) {
output.append('p', status);
output.append(posPower + '0', status);
output.append('-', status);
} else if (posPower <= 15) {
output.append("p1", status);
output.append('0' + (posPower % 10), status);
output.append('-', status);
} else {
status = kUnitIdentifierSyntaxError;
}
if (U_FAILURE(status)) {
return;
}
if (singleUnit.siPrefix != UMEASURE_SI_PREFIX_ONE) {
for (const auto& siPrefixInfo : gSIPrefixStrings) {
if (siPrefixInfo.value == singleUnit.siPrefix) {
output.append(siPrefixInfo.string, status);
break;
}
}
}
if (U_FAILURE(status)) {
return;
}
output.appendInvariantChars(gSimpleUnits[singleUnit.index], status);
}
/**
* Normalize a MeasureUnitImpl and generate the identifier string in place.
*/
void serialize(MeasureUnitImpl& impl, UErrorCode& status) {
if (U_FAILURE(status)) {
return;
}
U_ASSERT(impl.identifier.isEmpty());
if (impl.units.length() == 0) {
// Dimensionless, constructed by the default constructor: no appending
// to impl.identifier, we wish it to contain the zero-length string.
return;
}
if (impl.complexity == UMEASURE_UNIT_COMPOUND) {
// Note: don't sort a MIXED unit
uprv_sortArray(
impl.units.getAlias(),
impl.units.length(),
sizeof(impl.units[0]),
compareSingleUnits,
nullptr,
false,
&status);
if (U_FAILURE(status)) {
return;
}
}
serializeSingle(*impl.units[0], true, impl.identifier, status);
if (impl.units.length() == 1) {
return;
}
for (int32_t i = 1; i < impl.units.length(); i++) {
const SingleUnitImpl& prev = *impl.units[i-1];
const SingleUnitImpl& curr = *impl.units[i];
if (impl.complexity == UMEASURE_UNIT_MIXED) {
impl.identifier.append("-and-", status);
serializeSingle(curr, true, impl.identifier, status);
} else {
if (prev.dimensionality > 0 && curr.dimensionality < 0) {
impl.identifier.append("-per-", status);
} else {
impl.identifier.append('-', status);
}
serializeSingle(curr, false, impl.identifier, status);
}
}
}
/**
* Appends a SingleUnitImpl to a MeasureUnitImpl.
*
* @return true if a new item was added. If unit is the dimensionless unit, it
* is never added: the return value will always be false.
*/
bool appendImpl(MeasureUnitImpl& impl, const SingleUnitImpl& unit, UErrorCode& status) {
if (unit.isDimensionless()) {
// We don't append dimensionless units.
return false;
}
// Find a similar unit that already exists, to attempt to coalesce
SingleUnitImpl* oldUnit = nullptr;
for (int32_t i = 0; i < impl.units.length(); i++) {
auto* candidate = impl.units[i];
if (candidate->isCompatibleWith(unit)) {
oldUnit = candidate;
}
}
if (oldUnit) {
// Both dimensionalities will be positive, or both will be negative, by
// virtue of isCompatibleWith().
oldUnit->dimensionality += unit.dimensionality;
} else {
SingleUnitImpl* destination = impl.units.emplaceBack();
if (!destination) {
status = U_MEMORY_ALLOCATION_ERROR;
return false;
}
*destination = unit;
}
return (oldUnit == nullptr);
}
} // namespace
SingleUnitImpl SingleUnitImpl::forMeasureUnit(const MeasureUnit& measureUnit, UErrorCode& status) {
MeasureUnitImpl temp;
const MeasureUnitImpl& impl = MeasureUnitImpl::forMeasureUnit(measureUnit, temp, status);
if (U_FAILURE(status)) {
return {};
}
if (impl.units.length() == 0) {
return {};
}
if (impl.units.length() == 1) {
return *impl.units[0];
}
status = U_ILLEGAL_ARGUMENT_ERROR;
return {};
}
MeasureUnit SingleUnitImpl::build(UErrorCode& status) const {
MeasureUnitImpl temp;
temp.append(*this, status);
return std::move(temp).build(status);
}
MeasureUnitImpl MeasureUnitImpl::forIdentifier(StringPiece identifier, UErrorCode& status) {
return Parser::from(identifier, status).parse(status);
}
const MeasureUnitImpl& MeasureUnitImpl::forMeasureUnit(
const MeasureUnit& measureUnit, MeasureUnitImpl& memory, UErrorCode& status) {
if (measureUnit.fImpl) {
return *measureUnit.fImpl;
} else {
memory = Parser::from(measureUnit.getIdentifier(), status).parse(status);
return memory;
}
}
MeasureUnitImpl MeasureUnitImpl::forMeasureUnitMaybeCopy(
const MeasureUnit& measureUnit, UErrorCode& status) {
if (measureUnit.fImpl) {
return measureUnit.fImpl->copy(status);
} else {
return Parser::from(measureUnit.getIdentifier(), status).parse(status);
}
}
void MeasureUnitImpl::takeReciprocal(UErrorCode& /*status*/) {
identifier.clear();
for (int32_t i = 0; i < units.length(); i++) {
units[i]->dimensionality *= -1;
}
}
bool MeasureUnitImpl::append(const SingleUnitImpl& singleUnit, UErrorCode& status) {
identifier.clear();
return appendImpl(*this, singleUnit, status);
}
MeasureUnit MeasureUnitImpl::build(UErrorCode& status) && {
serialize(*this, status);
return MeasureUnit(std::move(*this));
}
MeasureUnit MeasureUnit::forIdentifier(StringPiece identifier, UErrorCode& status) {
return Parser::from(identifier, status).parse(status).build(status);
}
UMeasureUnitComplexity MeasureUnit::getComplexity(UErrorCode& status) const {
MeasureUnitImpl temp;
return MeasureUnitImpl::forMeasureUnit(*this, temp, status).complexity;
}
UMeasureSIPrefix MeasureUnit::getSIPrefix(UErrorCode& status) const {
return SingleUnitImpl::forMeasureUnit(*this, status).siPrefix;
}
MeasureUnit MeasureUnit::withSIPrefix(UMeasureSIPrefix prefix, UErrorCode& status) const {
SingleUnitImpl singleUnit = SingleUnitImpl::forMeasureUnit(*this, status);
singleUnit.siPrefix = prefix;
return singleUnit.build(status);
}
int32_t MeasureUnit::getDimensionality(UErrorCode& status) const {
SingleUnitImpl singleUnit = SingleUnitImpl::forMeasureUnit(*this, status);
if (U_FAILURE(status)) { return 0; }
if (singleUnit.isDimensionless()) {
return 0;
}
return singleUnit.dimensionality;
}
MeasureUnit MeasureUnit::withDimensionality(int32_t dimensionality, UErrorCode& status) const {
SingleUnitImpl singleUnit = SingleUnitImpl::forMeasureUnit(*this, status);
singleUnit.dimensionality = dimensionality;
return singleUnit.build(status);
}
MeasureUnit MeasureUnit::reciprocal(UErrorCode& status) const {
MeasureUnitImpl impl = MeasureUnitImpl::forMeasureUnitMaybeCopy(*this, status);
impl.takeReciprocal(status);
return std::move(impl).build(status);
}
MeasureUnit MeasureUnit::product(const MeasureUnit& other, UErrorCode& status) const {
MeasureUnitImpl impl = MeasureUnitImpl::forMeasureUnitMaybeCopy(*this, status);
MeasureUnitImpl temp;
const MeasureUnitImpl& otherImpl = MeasureUnitImpl::forMeasureUnit(other, temp, status);
if (impl.complexity == UMEASURE_UNIT_MIXED || otherImpl.complexity == UMEASURE_UNIT_MIXED) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return {};
}
for (int32_t i = 0; i < otherImpl.units.length(); i++) {
impl.append(*otherImpl.units[i], status);
}
if (impl.units.length() > 1) {
impl.complexity = UMEASURE_UNIT_COMPOUND;
}
return std::move(impl).build(status);
}
LocalArray<MeasureUnit> MeasureUnit::splitToSingleUnits(int32_t& outCount, UErrorCode& status) const {
MeasureUnitImpl temp;
const MeasureUnitImpl& impl = MeasureUnitImpl::forMeasureUnit(*this, temp, status);
outCount = impl.units.length();
MeasureUnit* arr = new MeasureUnit[outCount];
for (int32_t i = 0; i < outCount; i++) {
arr[i] = impl.units[i]->build(status);
}
return LocalArray<MeasureUnit>(arr, status);
}
U_NAMESPACE_END
#endif /* !UNCONFIG_NO_FORMATTING */
+213
View File
@@ -0,0 +1,213 @@
// © 2020 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#ifndef __MEASUNIT_IMPL_H__
#define __MEASUNIT_IMPL_H__
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/measunit.h"
#include "cmemory.h"
#include "charstr.h"
U_NAMESPACE_BEGIN
static const char16_t kDefaultCurrency[] = u"XXX";
static const char kDefaultCurrency8[] = "XXX";
/**
* A struct representing a single unit (optional SI prefix and dimensionality).
*/
struct SingleUnitImpl : public UMemory {
/**
* Gets a single unit from the MeasureUnit. If there are multiple single units, sets an error
* code and returns the base dimensionless unit. Parses if necessary.
*/
static SingleUnitImpl forMeasureUnit(const MeasureUnit& measureUnit, UErrorCode& status);
/** Transform this SingleUnitImpl into a MeasureUnit, simplifying if possible. */
MeasureUnit build(UErrorCode& status) const;
/**
* Compare this SingleUnitImpl to another SingleUnitImpl for the sake of
* sorting and coalescing.
*
* Takes the sign of dimensionality into account, but not the absolute
* value: per-meter is not considered the same as meter, but meter is
* considered the same as square-meter.
*
* The dimensionless unit generally does not get compared, but if it did, it
* would sort before other units by virtue of index being < 0 and
* dimensionality not being negative.
*/
int32_t compareTo(const SingleUnitImpl& other) const {
if (dimensionality < 0 && other.dimensionality > 0) {
// Positive dimensions first
return 1;
}
if (dimensionality > 0 && other.dimensionality < 0) {
return -1;
}
if (index < other.index) {
return -1;
}
if (index > other.index) {
return 1;
}
if (siPrefix < other.siPrefix) {
return -1;
}
if (siPrefix > other.siPrefix) {
return 1;
}
return 0;
}
/**
* Return whether this SingleUnitImpl is compatible with another for the purpose of coalescing.
*
* Units with the same base unit and SI prefix should match, except that they must also have
* the same dimensionality sign, such that we don't merge numerator and denominator.
*/
bool isCompatibleWith(const SingleUnitImpl& other) const {
return (compareTo(other) == 0);
}
/**
* Returns true if this unit is the "dimensionless base unit", as produced
* by the MeasureUnit() default constructor. (This does not include the
* likes of concentrations or angles.)
*/
bool isDimensionless() const {
return index == -1;
}
/**
* Simple unit index, unique for every simple unit, -1 for the dimensionless
* unit. This is an index into a string list in measunit_extra.cpp.
*
* The default value is -1, meaning the dimensionless unit:
* isDimensionless() will return true, until index is changed.
*/
int32_t index = -1;
/**
* SI prefix.
*
* This is ignored for the dimensionless unit.
*/
UMeasureSIPrefix siPrefix = UMEASURE_SI_PREFIX_ONE;
/**
* Dimensionality.
*
* This is meaningless for the dimensionless unit.
*/
int32_t dimensionality = 1;
};
/**
* Internal representation of measurement units. Capable of representing all complexities of units,
* including mixed and compound units.
*/
struct MeasureUnitImpl : public UMemory {
/** Extract the MeasureUnitImpl from a MeasureUnit. */
static inline const MeasureUnitImpl* get(const MeasureUnit& measureUnit) {
return measureUnit.fImpl;
}
/**
* Parse a unit identifier into a MeasureUnitImpl.
*
* @param identifier The unit identifier string.
* @param status Set if the identifier string is not valid.
* @return A newly parsed value object. Behaviour of this unit is
* unspecified if an error is returned via status.
*/
static MeasureUnitImpl forIdentifier(StringPiece identifier, UErrorCode& status);
/**
* Extract the MeasureUnitImpl from a MeasureUnit, or parse if it is not present.
*
* @param measureUnit The source MeasureUnit.
* @param memory A place to write the new MeasureUnitImpl if parsing is required.
* @param status Set if an error occurs.
* @return A reference to either measureUnit.fImpl or memory.
*/
static const MeasureUnitImpl& forMeasureUnit(
const MeasureUnit& measureUnit, MeasureUnitImpl& memory, UErrorCode& status);
/**
* Extract the MeasureUnitImpl from a MeasureUnit, or parse if it is not present.
*
* @param measureUnit The source MeasureUnit.
* @param status Set if an error occurs.
* @return A value object, either newly parsed or copied from measureUnit.
*/
static MeasureUnitImpl forMeasureUnitMaybeCopy(
const MeasureUnit& measureUnit, UErrorCode& status);
/**
* Used for currency units.
*/
static inline MeasureUnitImpl forCurrencyCode(StringPiece currencyCode) {
MeasureUnitImpl result;
UErrorCode localStatus = U_ZERO_ERROR;
result.identifier.append(currencyCode, localStatus);
// localStatus is not expected to fail since currencyCode should be 3 chars long
return result;
}
/** Transform this MeasureUnitImpl into a MeasureUnit, simplifying if possible. */
MeasureUnit build(UErrorCode& status) &&;
/**
* Create a copy of this MeasureUnitImpl. Don't use copy constructor to make this explicit.
*/
inline MeasureUnitImpl copy(UErrorCode& status) const {
MeasureUnitImpl result;
result.complexity = complexity;
result.units.appendAll(units, status);
result.identifier.append(identifier, status);
return result;
}
/** Mutates this MeasureUnitImpl to take the reciprocal. */
void takeReciprocal(UErrorCode& status);
/**
* Mutates this MeasureUnitImpl to append a single unit.
*
* @return true if a new item was added. If unit is the dimensionless unit,
* it is never added: the return value will always be false.
*/
bool append(const SingleUnitImpl& singleUnit, UErrorCode& status);
/** The complexity, either SINGLE, COMPOUND, or MIXED. */
UMeasureUnitComplexity complexity = UMEASURE_UNIT_SINGLE;
/**
* The list of simple units. These may be summed or multiplied, based on the
* value of the complexity field.
*
* The "dimensionless" unit (SingleUnitImpl default constructor) must not be
* added to this list.
*/
MaybeStackVector<SingleUnitImpl> units;
/**
* The full unit identifier. Owned by the MeasureUnitImpl. Empty if not computed.
*/
CharString identifier;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif //__MEASUNIT_IMPL_H__
+1
View File
@@ -190,6 +190,7 @@ void NameUnicodeTransliterator::handleTransliterate(Replaceable& text, UTransPos
}
if (uprv_isInvariantUString(name.getBuffer(), len)) {
cbuf[0] = 0;
name.extract(0, len, cbuf, maxLen, US_INV);
UErrorCode status = U_ZERO_ERROR;
+1 -1
View File
@@ -11,7 +11,7 @@ U_NAMESPACE_BEGIN
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(NoUnit)
NoUnit U_EXPORT2 NoUnit::base() {
return NoUnit("base");
return NoUnit("");
}
NoUnit U_EXPORT2 NoUnit::percent() {
+16 -12
View File
@@ -131,25 +131,25 @@ UnicodeString AffixUtils::escape(const UnicodeString &input) {
Field AffixUtils::getFieldForType(AffixPatternType type) {
switch (type) {
case TYPE_MINUS_SIGN:
return UNUM_SIGN_FIELD;
return {UFIELD_CATEGORY_NUMBER, UNUM_SIGN_FIELD};
case TYPE_PLUS_SIGN:
return UNUM_SIGN_FIELD;
return {UFIELD_CATEGORY_NUMBER, UNUM_SIGN_FIELD};
case TYPE_PERCENT:
return UNUM_PERCENT_FIELD;
return {UFIELD_CATEGORY_NUMBER, UNUM_PERCENT_FIELD};
case TYPE_PERMILLE:
return UNUM_PERMILL_FIELD;
return {UFIELD_CATEGORY_NUMBER, UNUM_PERMILL_FIELD};
case TYPE_CURRENCY_SINGLE:
return UNUM_CURRENCY_FIELD;
return {UFIELD_CATEGORY_NUMBER, UNUM_CURRENCY_FIELD};
case TYPE_CURRENCY_DOUBLE:
return UNUM_CURRENCY_FIELD;
return {UFIELD_CATEGORY_NUMBER, UNUM_CURRENCY_FIELD};
case TYPE_CURRENCY_TRIPLE:
return UNUM_CURRENCY_FIELD;
return {UFIELD_CATEGORY_NUMBER, UNUM_CURRENCY_FIELD};
case TYPE_CURRENCY_QUAD:
return UNUM_CURRENCY_FIELD;
return {UFIELD_CATEGORY_NUMBER, UNUM_CURRENCY_FIELD};
case TYPE_CURRENCY_QUINT:
return UNUM_CURRENCY_FIELD;
return {UFIELD_CATEGORY_NUMBER, UNUM_CURRENCY_FIELD};
case TYPE_CURRENCY_OVERFLOW:
return UNUM_CURRENCY_FIELD;
return {UFIELD_CATEGORY_NUMBER, UNUM_CURRENCY_FIELD};
default:
UPRV_UNREACHABLE;
}
@@ -165,7 +165,11 @@ AffixUtils::unescape(const UnicodeString &affixPattern, FormattedStringBuilder &
if (U_FAILURE(status)) { return length; }
if (tag.type == TYPE_CURRENCY_OVERFLOW) {
// Don't go to the provider for this special case
length += output.insertCodePoint(position + length, 0xFFFD, UNUM_CURRENCY_FIELD, status);
length += output.insertCodePoint(
position + length,
0xFFFD,
{UFIELD_CATEGORY_NUMBER, UNUM_CURRENCY_FIELD},
status);
} else if (tag.type < 0) {
length += output.insert(
position + length, provider.getSymbol(tag.type), getFieldForType(tag.type), status);
@@ -218,7 +222,7 @@ bool AffixUtils::hasCurrencySymbols(const UnicodeString &affixPattern, UErrorCod
while (hasNext(tag, affixPattern)) {
tag = nextToken(tag, affixPattern, status);
if (U_FAILURE(status)) { return false; }
if (tag.type < 0 && getFieldForType(tag.type) == UNUM_CURRENCY_FIELD) {
if (tag.type < 0 && getFieldForType(tag.type) == Field(UFIELD_CATEGORY_NUMBER, UNUM_CURRENCY_FIELD)) {
return true;
}
}
+12
View File
@@ -102,4 +102,16 @@ const LocalizedNumberFormatter& LocalizedNumberFormatterAsFormat::getNumberForma
return fFormatter;
}
// Definitions of public API methods (put here for dependency disentanglement)
Format* LocalizedNumberFormatter::toFormat(UErrorCode& status) const {
if (U_FAILURE(status)) {
return nullptr;
}
LocalPointer<LocalizedNumberFormatterAsFormat> retval(
new LocalizedNumberFormatterAsFormat(*this, fMacros.locale), status);
return retval.orphan();
}
#endif /* #if !UCONFIG_NO_FORMATTING */
+4 -3
View File
@@ -156,7 +156,7 @@ unumf_resultToString(const UFormattedNumber* uresult, UChar* buffer, int32_t buf
return 0;
}
return result->fImpl.toTempString(*ec).extract(buffer, bufferCapacity, *ec);
return result->fData.toTempString(*ec).extract(buffer, bufferCapacity, *ec);
}
U_CAPI UBool U_EXPORT2
@@ -173,7 +173,7 @@ unumf_resultNextFieldPosition(const UFormattedNumber* uresult, UFieldPosition* u
fp.setField(ufpos->field);
fp.setBeginIndex(ufpos->beginIndex);
fp.setEndIndex(ufpos->endIndex);
bool retval = result->fImpl.nextFieldPosition(fp, *ec);
bool retval = result->fData.nextFieldPosition(fp, *ec);
ufpos->beginIndex = fp.getBeginIndex();
ufpos->endIndex = fp.getEndIndex();
// NOTE: MSVC sometimes complains when implicitly converting between bool and UBool
@@ -192,7 +192,8 @@ unumf_resultGetAllFieldPositions(const UFormattedNumber* uresult, UFieldPosition
}
auto* fpi = reinterpret_cast<FieldPositionIterator*>(ufpositer);
result->fImpl.getAllFieldPositions(*fpi, *ec);
FieldPositionIteratorHandler fpih(fpi, *ec);
result->fData.getAllFieldPositions(fpih, *ec);
}
U_CAPI void U_EXPORT2
+27 -12
View File
@@ -215,19 +215,25 @@ void CompactData::CompactDataSink::put(const char *key, ResourceValue &value, UB
/// END OF CompactData.java; BEGIN CompactNotation.java ///
///////////////////////////////////////////////////////////
CompactHandler::CompactHandler(CompactStyle compactStyle, const Locale &locale, const char *nsName,
CompactType compactType, const PluralRules *rules,
MutablePatternModifier *buildReference, const MicroPropsGenerator *parent,
UErrorCode &status)
: rules(rules), parent(parent) {
CompactHandler::CompactHandler(
CompactStyle compactStyle,
const Locale &locale,
const char *nsName,
CompactType compactType,
const PluralRules *rules,
MutablePatternModifier *buildReference,
bool safe,
const MicroPropsGenerator *parent,
UErrorCode &status)
: rules(rules), parent(parent), safe(safe) {
data.populate(locale, nsName, compactStyle, compactType, status);
if (buildReference != nullptr) {
if (safe) {
// Safe code path
precomputeAllModifiers(*buildReference, status);
safe = TRUE;
} else {
// Unsafe code path
safe = FALSE;
// Store the MutablePatternModifier reference.
unsafePatternModifier = buildReference;
}
}
@@ -260,7 +266,7 @@ void CompactHandler::precomputeAllModifiers(MutablePatternModifier &buildReferen
ParsedPatternInfo patternInfo;
PatternParser::parseToPatternInfo(UnicodeString(patternString), patternInfo, status);
if (U_FAILURE(status)) { return; }
buildReference.setPatternInfo(&patternInfo, UNUM_COMPACT_FIELD);
buildReference.setPatternInfo(&patternInfo, {UFIELD_CATEGORY_NUMBER, UNUM_COMPACT_FIELD});
info.mod = buildReference.createImmutable(status);
if (U_FAILURE(status)) { return; }
info.patternString = patternString;
@@ -274,12 +280,13 @@ void CompactHandler::processQuantity(DecimalQuantity &quantity, MicroProps &micr
// Treat zero, NaN, and infinity as if they had magnitude 0
int32_t magnitude;
int32_t multiplier = 0;
if (quantity.isZeroish()) {
magnitude = 0;
micros.rounder.apply(quantity, status);
} else {
// TODO: Revisit chooseMultiplierAndApply
int32_t multiplier = micros.rounder.chooseMultiplierAndApply(quantity, data, status);
multiplier = micros.rounder.chooseMultiplierAndApply(quantity, data, status);
magnitude = quantity.isZeroish() ? 0 : quantity.getMagnitude();
magnitude -= multiplier;
}
@@ -309,10 +316,18 @@ void CompactHandler::processQuantity(DecimalQuantity &quantity, MicroProps &micr
// C++ Note: Use unsafePatternInfo for proper lifecycle.
ParsedPatternInfo &patternInfo = const_cast<CompactHandler *>(this)->unsafePatternInfo;
PatternParser::parseToPatternInfo(UnicodeString(patternString), patternInfo, status);
static_cast<MutablePatternModifier*>(const_cast<Modifier*>(micros.modMiddle))
->setPatternInfo(&patternInfo, UNUM_COMPACT_FIELD);
unsafePatternModifier->setPatternInfo(
&unsafePatternInfo,
{UFIELD_CATEGORY_NUMBER, UNUM_COMPACT_FIELD});
unsafePatternModifier->setNumberProperties(quantity.signum(), StandardPlural::Form::COUNT);
micros.modMiddle = unsafePatternModifier;
}
// Change the exponent only after we select appropriate plural form
// for formatting purposes so that we preserve expected formatted
// string behavior.
quantity.adjustExponent(-1 * multiplier);
// We already performed rounding. Do not perform it again.
micros.rounder = RoundingImpl::passThrough();
}
+11 -4
View File
@@ -56,10 +56,16 @@ struct CompactModInfo {
class CompactHandler : public MicroPropsGenerator, public UMemory {
public:
CompactHandler(CompactStyle compactStyle, const Locale &locale, const char *nsName,
CompactType compactType, const PluralRules *rules,
MutablePatternModifier *buildReference, const MicroPropsGenerator *parent,
UErrorCode &status);
CompactHandler(
CompactStyle compactStyle,
const Locale &locale,
const char *nsName,
CompactType compactType,
const PluralRules *rules,
MutablePatternModifier *buildReference,
bool safe,
const MicroPropsGenerator *parent,
UErrorCode &status);
~CompactHandler() U_OVERRIDE;
@@ -74,6 +80,7 @@ class CompactHandler : public MicroPropsGenerator, public UMemory {
int32_t precomputedModsLength = 0;
CompactData data;
ParsedPatternInfo unsafePatternInfo;
MutablePatternModifier* unsafePatternModifier;
UBool safe;
/** Used by the safe code path */
+58 -19
View File
@@ -120,6 +120,7 @@ void DecimalQuantity::copyFieldsFrom(const DecimalQuantity& other) {
origDouble = other.origDouble;
origDelta = other.origDelta;
isApproximate = other.isApproximate;
exponent = other.exponent;
}
void DecimalQuantity::clear() {
@@ -269,11 +270,21 @@ double DecimalQuantity::getPluralOperand(PluralOperand operand) const {
return fractionCount();
case PLURAL_OPERAND_W:
return fractionCountWithoutTrailingZeros();
case PLURAL_OPERAND_E:
return static_cast<double>(getExponent());
default:
return std::abs(toDouble());
}
}
int32_t DecimalQuantity::getExponent() const {
return exponent;
}
void DecimalQuantity::adjustExponent(int delta) {
exponent = exponent + delta;
}
bool DecimalQuantity::hasIntegerValue() const {
return scale >= 0;
}
@@ -307,11 +318,13 @@ int8_t DecimalQuantity::getDigit(int32_t magnitude) const {
}
int32_t DecimalQuantity::fractionCount() const {
return -getLowerDisplayMagnitude();
int32_t fractionCountWithExponent = -getLowerDisplayMagnitude() - exponent;
return fractionCountWithExponent > 0 ? fractionCountWithExponent : 0;
}
int32_t DecimalQuantity::fractionCountWithoutTrailingZeros() const {
return -scale > 0 ? -scale : 0; // max(-scale, 0)
int32_t fractionCountWithExponent = -scale - exponent;
return fractionCountWithExponent > 0 ? fractionCountWithExponent : 0; // max(-fractionCountWithExponent, 0)
}
bool DecimalQuantity::isNegative() const {
@@ -319,10 +332,14 @@ bool DecimalQuantity::isNegative() const {
}
Signum DecimalQuantity::signum() const {
if (isNegative()) {
bool isZero = (isZeroish() && !isInfinite());
bool isNeg = isNegative();
if (isZero && isNeg) {
return SIGNUM_NEG_ZERO;
} else if (isZero) {
return SIGNUM_POS_ZERO;
} else if (isNeg) {
return SIGNUM_NEG;
} else if (isZeroish() && !isInfinite()) {
return SIGNUM_ZERO;
} else {
return SIGNUM_POS;
}
@@ -422,9 +439,6 @@ void DecimalQuantity::_setToDoubleFast(double n) {
// TODO: Make a fast path for other types of doubles.
if (!std::numeric_limits<double>::is_iec559) {
convertToAccurateDouble();
// Turn off the approximate double flag, since the value is now exact.
isApproximate = false;
origDouble = 0.0;
return;
}
@@ -439,8 +453,14 @@ void DecimalQuantity::_setToDoubleFast(double n) {
return;
}
if (exponent == -1023 || exponent == 1024) {
// The extreme values of exponent are special; use slow path.
convertToAccurateDouble();
return;
}
// 3.3219... is log2(10)
auto fracLength = static_cast<int32_t> ((52 - exponent) / 3.32192809489);
auto fracLength = static_cast<int32_t> ((52 - exponent) / 3.32192809488736234787031942948939017586);
if (fracLength >= 0) {
int32_t i = fracLength;
// 1e22 is the largest exact double.
@@ -452,7 +472,7 @@ void DecimalQuantity::_setToDoubleFast(double n) {
for (; i <= -22; i += 22) n /= 1e22;
n /= DOUBLE_MULTIPLIERS[-i];
}
auto result = static_cast<int64_t>(std::round(n));
auto result = static_cast<int64_t>(uprv_round(n));
if (result != 0) {
_setToLong(result);
scale -= fracLength;
@@ -521,12 +541,12 @@ int64_t DecimalQuantity::toLong(bool truncateIfOverflow) const {
// if (dq.fitsInLong()) { /* use dq.toLong() */ } else { /* use some fallback */ }
// Fallback behavior upon truncateIfOverflow is to truncate at 17 digits.
uint64_t result = 0L;
int32_t upperMagnitude = scale + precision - 1;
int32_t upperMagnitude = exponent + scale + precision - 1;
if (truncateIfOverflow) {
upperMagnitude = std::min(upperMagnitude, 17);
}
for (int32_t magnitude = upperMagnitude; magnitude >= 0; magnitude--) {
result = result * 10 + getDigitPos(magnitude - scale);
result = result * 10 + getDigitPos(magnitude - scale - exponent);
}
if (isNegative()) {
return static_cast<int64_t>(0LL - result); // i.e., -result
@@ -536,7 +556,7 @@ int64_t DecimalQuantity::toLong(bool truncateIfOverflow) const {
uint64_t DecimalQuantity::toFractionLong(bool includeTrailingZeros) const {
uint64_t result = 0L;
int32_t magnitude = -1;
int32_t magnitude = -1 - exponent;
int32_t lowerMagnitude = scale;
if (includeTrailingZeros) {
lowerMagnitude = std::min(lowerMagnitude, rReqPos);
@@ -560,7 +580,7 @@ bool DecimalQuantity::fitsInLong(bool ignoreFraction) const {
if (isZeroish()) {
return true;
}
if (scale < 0 && !ignoreFraction) {
if (exponent + scale < 0 && !ignoreFraction) {
return false;
}
int magnitude = getMagnitude();
@@ -877,12 +897,30 @@ UnicodeString DecimalQuantity::toPlainString() const {
if (isNegative()) {
sb.append(u'-');
}
if (precision == 0 || getMagnitude() < 0) {
if (precision == 0) {
sb.append(u'0');
return sb;
}
int32_t upper = scale + precision + exponent - 1;
int32_t lower = scale + exponent;
if (upper < lReqPos - 1) {
upper = lReqPos - 1;
}
if (lower > rReqPos) {
lower = rReqPos;
}
int32_t p = upper;
if (p < 0) {
sb.append(u'0');
}
for (int m = getUpperDisplayMagnitude(); m >= getLowerDisplayMagnitude(); m--) {
if (m == -1) { sb.append(u'.'); }
sb.append(getDigit(m) + u'0');
for (; p >= 0; p--) {
sb.append(u'0' + getDigitPos(p - scale - exponent));
}
if (lower < 0) {
sb.append(u'.');
}
for(; p >= lower; p--) {
sb.append(u'0' + getDigitPos(p - scale - exponent));
}
return sb;
}
@@ -908,7 +946,7 @@ UnicodeString DecimalQuantity::toScientificString() const {
}
}
result.append(u'E');
int32_t _scale = upperPos + scale;
int32_t _scale = upperPos + scale + exponent;
if (_scale == INT32_MIN) {
result.append({u"-2147483648", -1});
return result;
@@ -1021,6 +1059,7 @@ void DecimalQuantity::setBcdToZero() {
isApproximate = false;
origDouble = 0;
origDelta = 0;
exponent = 0;
}
void DecimalQuantity::readIntToBcd(int32_t n) {
+36 -2
View File
@@ -146,6 +146,26 @@ class U_I18N_API DecimalQuantity : public IFixedDecimal, public UMemory {
*/
int32_t getMagnitude() const;
/**
* @return The value of the (suppressed) exponent after the number has been
* put into a notation with exponents (ex: compact, scientific). Ex: given
* the number 1000 as "1K" / "1E3", the return value will be 3 (positive).
*/
int32_t getExponent() const;
/**
* Adjusts the value for the (suppressed) exponent stored when using
* notation with exponents (ex: compact, scientific).
*
* <p>Adjusting the exponent is decoupled from {@link #adjustMagnitude} in
* order to allow flexibility for {@link StandardPlural} to be selected in
* formatting (ex: for compact notation) either with or without the exponent
* applied in the value of the number.
* @param delta
* The value to adjust the exponent by.
*/
void adjustExponent(int32_t delta);
/**
* @return Whether the value represented by this {@link DecimalQuantity} is
* zero, infinity, or NaN.
@@ -164,9 +184,19 @@ class U_I18N_API DecimalQuantity : public IFixedDecimal, public UMemory {
/** @return Whether the value represented by this {@link DecimalQuantity} is not a number. */
bool isNaN() const U_OVERRIDE;
/** @param truncateIfOverflow if false and the number does NOT fit, fails with an assertion error. */
/**
* Note: this method incorporates the value of {@code exponent}
* (for cases such as compact notation) to return the proper long value
* represented by the result.
* @param truncateIfOverflow if false and the number does NOT fit, fails with an assertion error.
*/
int64_t toLong(bool truncateIfOverflow = false) const;
/**
* Note: this method incorporates the value of {@code exponent}
* (for cases such as compact notation) to return the proper long value
* represented by the result.
*/
uint64_t toFractionLong(bool includeTrailingZeros) const;
/**
@@ -351,6 +381,10 @@ class U_I18N_API DecimalQuantity : public IFixedDecimal, public UMemory {
int32_t lReqPos = 0;
int32_t rReqPos = 0;
// The value of the (suppressed) exponent after the number has been put into
// a notation with exponents (ex: compact, scientific).
int32_t exponent = 0;
/**
* The BCD of the 16 digits of the number represented by this object. Every 4 bits of the long map
* to one digit. For example, the number "12345" in BCD is "0x12345".
@@ -423,7 +457,7 @@ class U_I18N_API DecimalQuantity : public IFixedDecimal, public UMemory {
/**
* Sets the internal representation to zero. Clears any values stored in scale, precision,
* hasDouble, origDouble, origDelta, and BCD data.
* hasDouble, origDouble, origDelta, exponent, and BCD data.
*/
void setBcdToZero();
+17 -28
View File
@@ -11,7 +11,6 @@
#include "number_formatimpl.h"
#include "umutex.h"
#include "number_asformat.h"
#include "number_skeletons.h"
#include "number_utils.h"
#include "number_utypes.h"
#include "util.h"
@@ -21,6 +20,16 @@ using namespace icu;
using namespace icu::number;
using namespace icu::number::impl;
#if (U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN) && defined(_MSC_VER)
// Ignore MSVC warning 4661. This is generated for NumberFormatterSettings<>::toSkeleton() as this method
// is defined elsewhere (in number_skeletons.cpp). The compiler is warning that the explicit template instantiation
// inside this single translation unit (CPP file) is incomplete, and thus it isn't sure if the template class is
// fully defined. However, since each translation unit explicitly instantiates all the necessary template classes,
// they will all be passed to the linker, and the linker will still find and export all the class members.
#pragma warning(push)
#pragma warning(disable: 4661)
#endif
template<typename Derived>
Derived NumberFormatterSettings<Derived>::notation(const Notation& notation) const& {
Derived copy(*this);
@@ -320,16 +329,7 @@ Derived NumberFormatterSettings<Derived>::macros(impl::MacroProps&& macros)&& {
return move;
}
template<typename Derived>
UnicodeString NumberFormatterSettings<Derived>::toSkeleton(UErrorCode& status) const {
if (U_FAILURE(status)) {
return ICU_Utility::makeBogusString();
}
if (fMacros.copyErrorTo(status)) {
return ICU_Utility::makeBogusString();
}
return skeleton::generate(fMacros, status);
}
// Note: toSkeleton defined in number_skeletons.cpp
template<typename Derived>
LocalPointer<Derived> NumberFormatterSettings<Derived>::clone() const & {
@@ -358,15 +358,7 @@ LocalizedNumberFormatter NumberFormatter::withLocale(const Locale& locale) {
return with().locale(locale);
}
UnlocalizedNumberFormatter
NumberFormatter::forSkeleton(const UnicodeString& skeleton, UErrorCode& status) {
return skeleton::create(skeleton, nullptr, status);
}
UnlocalizedNumberFormatter
NumberFormatter::forSkeleton(const UnicodeString& skeleton, UParseError& perror, UErrorCode& status) {
return skeleton::create(skeleton, &perror, status);
}
// Note: forSkeleton defined in number_skeletons.cpp
template<typename T> using NFS = NumberFormatterSettings<T>;
@@ -766,14 +758,11 @@ int32_t LocalizedNumberFormatter::getCallCount() const {
return umtx_loadAcquire(*callCount);
}
Format* LocalizedNumberFormatter::toFormat(UErrorCode& status) const {
if (U_FAILURE(status)) {
return nullptr;
}
LocalPointer<LocalizedNumberFormatterAsFormat> retval(
new LocalizedNumberFormatterAsFormat(*this, fMacros.locale), status);
return retval.orphan();
}
// Note: toFormat defined in number_asformat.cpp
#if (U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN) && defined(_MSC_VER)
// Warning 4661.
#pragma warning(pop)
#endif
#endif /* #if !UCONFIG_NO_FORMATTING */
+76 -95
View File
@@ -24,45 +24,6 @@ using namespace icu;
using namespace icu::number;
using namespace icu::number::impl;
namespace {
struct CurrencyFormatInfoResult {
bool exists;
const char16_t* pattern;
const char16_t* decimalSeparator;
const char16_t* groupingSeparator;
};
CurrencyFormatInfoResult
getCurrencyFormatInfo(const Locale& locale, const char* isoCode, UErrorCode& status) {
// TODO: Load this data in a centralized location like ICU4J?
// TODO: Move this into the CurrencySymbols class?
// TODO: Parts of this same data are loaded in dcfmtsym.cpp; should clean up.
CurrencyFormatInfoResult result = {false, nullptr, nullptr, nullptr};
if (U_FAILURE(status)) { return result; }
CharString key;
key.append("Currencies/", status);
key.append(isoCode, status);
UErrorCode localStatus = status;
LocalUResourceBundlePointer bundle(ures_open(U_ICUDATA_CURR, locale.getName(), &localStatus));
ures_getByKeyWithFallback(bundle.getAlias(), key.data(), bundle.getAlias(), &localStatus);
if (U_SUCCESS(localStatus) &&
ures_getSize(bundle.getAlias()) > 2) { // the length is 3 if more data is present
ures_getByIndex(bundle.getAlias(), 2, bundle.getAlias(), &localStatus);
int32_t dummy;
result.exists = true;
result.pattern = ures_getStringByIndex(bundle.getAlias(), 0, &dummy, &localStatus);
result.decimalSeparator = ures_getStringByIndex(bundle.getAlias(), 1, &dummy, &localStatus);
result.groupingSeparator = ures_getStringByIndex(bundle.getAlias(), 2, &dummy, &localStatus);
status = localStatus;
} else if (localStatus != U_MISSING_RESOURCE_ERROR) {
status = localStatus;
}
return result;
}
} // namespace
MicroPropsGenerator::~MicroPropsGenerator() = default;
@@ -111,7 +72,6 @@ void NumberFormatterImpl::preProcess(DecimalQuantity& inValue, MicroProps& micro
return;
}
fMicroPropsGenerator->processQuantity(inValue, microsOut, status);
microsOut.rounder.apply(inValue, status);
microsOut.integerWidth.apply(inValue, status);
}
@@ -124,7 +84,6 @@ MicroProps& NumberFormatterImpl::preProcessUnsafe(DecimalQuantity& inValue, UErr
return fMicros; // must always return a value
}
fMicroPropsGenerator->processQuantity(inValue, fMicros, status);
fMicros.rounder.apply(inValue, status);
fMicros.integerWidth.apply(inValue, status);
return fMicros;
}
@@ -181,14 +140,6 @@ NumberFormatterImpl::macrosToMicroGenerator(const MacroProps& macros, bool safe,
if (isCurrency) {
currency = CurrencyUnit(macros.unit, status); // Restore CurrencyUnit from MeasureUnit
}
const CurrencySymbols* currencySymbols;
if (macros.currencySymbols != nullptr) {
// Used by the DecimalFormat code path
currencySymbols = macros.currencySymbols;
} else {
fWarehouse.fCurrencySymbols = {currency, macros.locale, status};
currencySymbols = &fWarehouse.fCurrencySymbols;
}
UNumberUnitWidth unitWidth = UNUM_UNIT_WIDTH_SHORT;
if (macros.unitWidth != UNUM_UNIT_WIDTH_COUNT) {
unitWidth = macros.unitWidth;
@@ -215,41 +166,26 @@ NumberFormatterImpl::macrosToMicroGenerator(const MacroProps& macros, bool safe,
if (macros.symbols.isDecimalFormatSymbols()) {
fMicros.symbols = macros.symbols.getDecimalFormatSymbols();
} else {
auto newSymbols = new DecimalFormatSymbols(macros.locale, *ns, status);
if (newSymbols == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
LocalPointer<DecimalFormatSymbols> newSymbols(
new DecimalFormatSymbols(macros.locale, *ns, status), status);
if (U_FAILURE(status)) {
return nullptr;
}
fMicros.symbols = newSymbols;
// Give ownership to the NumberFormatterImpl.
fSymbols.adoptInstead(fMicros.symbols);
if (isCurrency) {
newSymbols->setCurrency(currency.getISOCurrency(), status);
if (U_FAILURE(status)) {
return nullptr;
}
}
fMicros.symbols = newSymbols.getAlias();
fSymbols.adoptInstead(newSymbols.orphan());
}
// Load and parse the pattern string. It is used for grouping sizes and affixes only.
// If we are formatting currency, check for a currency-specific pattern.
const char16_t* pattern = nullptr;
if (isCurrency) {
CurrencyFormatInfoResult info = getCurrencyFormatInfo(
macros.locale, currency.getSubtype(), status);
if (info.exists) {
pattern = info.pattern;
// It's clunky to clone an object here, but this code is not frequently executed.
auto symbols = new DecimalFormatSymbols(*fMicros.symbols);
if (symbols == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return nullptr;
}
fMicros.symbols = symbols;
fSymbols.adoptInstead(symbols);
symbols->setSymbol(
DecimalFormatSymbols::ENumberFormatSymbol::kMonetarySeparatorSymbol,
UnicodeString(info.decimalSeparator),
FALSE);
symbols->setSymbol(
DecimalFormatSymbols::ENumberFormatSymbol::kMonetaryGroupingSeparatorSymbol,
UnicodeString(info.groupingSeparator),
FALSE);
}
if (isCurrency && fMicros.symbols->getCurrencyPattern() != nullptr) {
pattern = fMicros.symbols->getCurrencyPattern();
}
if (pattern == nullptr) {
CldrPatternStyle patternStyle;
@@ -267,6 +203,9 @@ NumberFormatterImpl::macrosToMicroGenerator(const MacroProps& macros, bool safe,
patternStyle = CLDR_PATTERN_STYLE_CURRENCY;
}
pattern = utils::getPatternForStyle(macros.locale, nsName, patternStyle, status);
if (U_FAILURE(status)) {
return nullptr;
}
}
auto patternInfo = new ParsedPatternInfo();
if (patternInfo == nullptr) {
@@ -275,6 +214,9 @@ NumberFormatterImpl::macrosToMicroGenerator(const MacroProps& macros, bool safe,
}
fPatternInfo.adoptInstead(patternInfo);
PatternParser::parseToPatternInfo(UnicodeString(pattern), *patternInfo, status);
if (U_FAILURE(status)) {
return nullptr;
}
/////////////////////////////////////////////////////////////////////////////////////
/// START POPULATING THE DEFAULT MICROPROPS AND BUILDING THE MICROPROPS GENERATOR ///
@@ -305,6 +247,9 @@ NumberFormatterImpl::macrosToMicroGenerator(const MacroProps& macros, bool safe,
roundingMode = precision.fRoundingMode;
}
fMicros.rounder = {precision, roundingMode, currency, status};
if (U_FAILURE(status)) {
return nullptr;
}
// Grouping strategy
if (!macros.grouper.isBogus()) {
@@ -372,23 +317,23 @@ NumberFormatterImpl::macrosToMicroGenerator(const MacroProps& macros, bool safe,
patternModifier->setPatternInfo(
macros.affixProvider != nullptr ? macros.affixProvider
: static_cast<const AffixPatternProvider*>(fPatternInfo.getAlias()),
UNUM_FIELD_COUNT);
kUndefinedField);
patternModifier->setPatternAttributes(fMicros.sign, isPermille);
if (patternModifier->needsPlurals()) {
patternModifier->setSymbols(
fMicros.symbols,
currencySymbols,
currency,
unitWidth,
resolvePluralRules(macros.rules, macros.locale, status));
resolvePluralRules(macros.rules, macros.locale, status),
status);
} else {
patternModifier->setSymbols(fMicros.symbols, currencySymbols, unitWidth, nullptr);
patternModifier->setSymbols(fMicros.symbols, currency, unitWidth, nullptr, status);
}
if (safe) {
fImmutablePatternModifier.adoptInstead(patternModifier->createImmutableAndChain(chain, status));
chain = fImmutablePatternModifier.getAlias();
} else {
patternModifier->addToChain(chain);
chain = patternModifier;
fImmutablePatternModifier.adoptInstead(patternModifier->createImmutable(status));
}
if (U_FAILURE(status)) {
return nullptr;
}
// Outer modifier (CLDR units and currency long names)
@@ -416,10 +361,11 @@ NumberFormatterImpl::macrosToMicroGenerator(const MacroProps& macros, bool safe,
// No outer modifier required
fMicros.modOuter = &fMicros.helpers.emptyWeakModifier;
}
if (U_FAILURE(status)) {
return nullptr;
}
// Compact notation
// NOTE: Compact notation can (but might not) override the middle modifier and rounding.
// It therefore needs to go at the end of the chain.
if (macros.notation.fType == Notation::NTN_COMPACT) {
CompactType compactType = (isCurrency && unitWidth != UNUM_UNIT_WIDTH_FULL_NAME)
? CompactType::TYPE_CURRENCY : CompactType::TYPE_DECIMAL;
@@ -429,7 +375,8 @@ NumberFormatterImpl::macrosToMicroGenerator(const MacroProps& macros, bool safe,
nsName,
compactType,
resolvePluralRules(macros.rules, macros.locale, status),
safe ? patternModifier : nullptr,
patternModifier,
safe,
chain,
status);
if (newCompactHandler == nullptr) {
@@ -439,6 +386,18 @@ NumberFormatterImpl::macrosToMicroGenerator(const MacroProps& macros, bool safe,
fCompactHandler.adoptInstead(newCompactHandler);
chain = fCompactHandler.getAlias();
}
if (U_FAILURE(status)) {
return nullptr;
}
// Always add the pattern modifier as the last element of the chain.
if (safe) {
fImmutablePatternModifier->addToChain(chain);
chain = fImmutablePatternModifier.getAlias();
} else {
patternModifier->addToChain(chain);
chain = patternModifier;
}
return chain;
}
@@ -478,14 +437,14 @@ int32_t NumberFormatterImpl::writeNumber(const MicroProps& micros, DecimalQuanti
length += string.insert(
length + index,
micros.symbols->getSymbol(DecimalFormatSymbols::ENumberFormatSymbol::kInfinitySymbol),
UNUM_INTEGER_FIELD,
{UFIELD_CATEGORY_NUMBER, UNUM_INTEGER_FIELD},
status);
} else if (quantity.isNaN()) {
length += string.insert(
length + index,
micros.symbols->getSymbol(DecimalFormatSymbols::ENumberFormatSymbol::kNaNSymbol),
UNUM_INTEGER_FIELD,
{UFIELD_CATEGORY_NUMBER, UNUM_INTEGER_FIELD},
status);
} else {
@@ -501,12 +460,23 @@ int32_t NumberFormatterImpl::writeNumber(const MicroProps& micros, DecimalQuanti
.symbols
->getSymbol(
DecimalFormatSymbols::ENumberFormatSymbol::kDecimalSeparatorSymbol),
UNUM_DECIMAL_SEPARATOR_FIELD,
{UFIELD_CATEGORY_NUMBER, UNUM_DECIMAL_SEPARATOR_FIELD},
status);
}
// Add the fraction digits
length += writeFractionDigits(micros, quantity, string, length + index, status);
if (length == 0) {
// Force output of the digit for value 0
length += utils::insertDigitFromSymbols(
string,
index,
0,
*micros.symbols,
{UFIELD_CATEGORY_NUMBER, UNUM_INTEGER_FIELD},
status);
}
}
return length;
@@ -526,14 +496,20 @@ int32_t NumberFormatterImpl::writeIntegerDigits(const MicroProps& micros, Decima
DecimalFormatSymbols::ENumberFormatSymbol::kMonetaryGroupingSeparatorSymbol)
: micros.symbols->getSymbol(
DecimalFormatSymbols::ENumberFormatSymbol::kGroupingSeparatorSymbol),
UNUM_GROUPING_SEPARATOR_FIELD,
{UFIELD_CATEGORY_NUMBER, UNUM_GROUPING_SEPARATOR_FIELD},
status);
}
// Get and append the next digit value
int8_t nextDigit = quantity.getDigit(i);
length += utils::insertDigitFromSymbols(
string, index, nextDigit, *micros.symbols, UNUM_INTEGER_FIELD, status);
string,
index,
nextDigit,
*micros.symbols,
{UFIELD_CATEGORY_NUMBER,
UNUM_INTEGER_FIELD},
status);
}
return length;
}
@@ -547,7 +523,12 @@ int32_t NumberFormatterImpl::writeFractionDigits(const MicroProps& micros, Decim
// Get and append the next digit value
int8_t nextDigit = quantity.getDigit(-i - 1);
length += utils::insertDigitFromSymbols(
string, length + index, nextDigit, *micros.symbols, UNUM_FRACTION_FIELD, status);
string,
length + index,
nextDigit,
*micros.symbols,
{UFIELD_CATEGORY_NUMBER, UNUM_FRACTION_FIELD},
status);
}
return length;
}
+1 -1
View File
@@ -95,7 +95,7 @@ class NumberFormatterImpl : public UMemory {
LocalPointer<const ParsedPatternInfo> fPatternInfo;
LocalPointer<const ScientificHandler> fScientificHandler;
LocalPointer<MutablePatternModifier> fPatternModifier;
LocalPointer<const ImmutablePatternModifier> fImmutablePatternModifier;
LocalPointer<ImmutablePatternModifier> fImmutablePatternModifier;
LocalPointer<const LongNameHandler> fLongNameHandler;
LocalPointer<const CompactHandler> fCompactHandler;
+13 -6
View File
@@ -188,6 +188,12 @@ LongNameHandler*
LongNameHandler::forMeasureUnit(const Locale &loc, const MeasureUnit &unitRef, const MeasureUnit &perUnit,
const UNumberUnitWidth &width, const PluralRules *rules,
const MicroPropsGenerator *parent, UErrorCode &status) {
if (uprv_strlen(unitRef.getType()) == 0 || uprv_strlen(perUnit.getType()) == 0) {
// TODO(ICU-20941): Unsanctioned unit. Not yet fully supported. Set an error code.
status = U_UNSUPPORTED_ERROR;
return nullptr;
}
MeasureUnit unit = unitRef;
if (uprv_strcmp(perUnit.getType(), "none") != 0) {
// Compound unit: first try to simplify (e.g., meters per second is its own unit).
@@ -209,7 +215,7 @@ LongNameHandler::forMeasureUnit(const Locale &loc, const MeasureUnit &unitRef, c
UnicodeString simpleFormats[ARRAY_LENGTH];
getMeasureData(loc, unit, width, simpleFormats, status);
if (U_FAILURE(status)) { return result; }
result->simpleFormatsToModifiers(simpleFormats, UNUM_MEASURE_UNIT_FIELD, status);
result->simpleFormatsToModifiers(simpleFormats, {UFIELD_CATEGORY_NUMBER, UNUM_MEASURE_UNIT_FIELD}, status);
return result;
}
@@ -240,14 +246,15 @@ LongNameHandler::forCompoundUnit(const Locale &loc, const MeasureUnit &unit, con
if (U_FAILURE(status)) { return result; }
UnicodeString secondaryFormat = getWithPlural(secondaryData, StandardPlural::Form::ONE, status);
if (U_FAILURE(status)) { return result; }
SimpleFormatter secondaryCompiled(secondaryFormat, 1, 1, status);
// Some "one" pattern may not contain "{0}". For example in "ar" or "ne" locale.
SimpleFormatter secondaryCompiled(secondaryFormat, 0, 1, status);
if (U_FAILURE(status)) { return result; }
UnicodeString secondaryString = secondaryCompiled.getTextWithNoArguments().trim();
// TODO: Why does UnicodeString need to be explicit in the following line?
compiled.format(UnicodeString(u"{0}"), secondaryString, perUnitFormat, status);
if (U_FAILURE(status)) { return result; }
}
result->multiSimpleFormatsToModifiers(primaryData, perUnitFormat, UNUM_MEASURE_UNIT_FIELD, status);
result->multiSimpleFormatsToModifiers(primaryData, perUnitFormat, {UFIELD_CATEGORY_NUMBER, UNUM_MEASURE_UNIT_FIELD}, status);
return result;
}
@@ -296,7 +303,7 @@ LongNameHandler* LongNameHandler::forCurrencyLongNames(const Locale &loc, const
UnicodeString simpleFormats[ARRAY_LENGTH];
getCurrencyLongNameData(loc, currency, simpleFormats, status);
if (U_FAILURE(status)) { return nullptr; }
result->simpleFormatsToModifiers(simpleFormats, UNUM_CURRENCY_FIELD, status);
result->simpleFormatsToModifiers(simpleFormats, {UFIELD_CATEGORY_NUMBER, UNUM_CURRENCY_FIELD}, status);
return result;
}
@@ -308,7 +315,7 @@ void LongNameHandler::simpleFormatsToModifiers(const UnicodeString *simpleFormat
if (U_FAILURE(status)) { return; }
SimpleFormatter compiledFormatter(simpleFormat, 0, 1, status);
if (U_FAILURE(status)) { return; }
fModifiers[i] = SimpleModifier(compiledFormatter, field, false, {this, SIGNUM_ZERO, plural});
fModifiers[i] = SimpleModifier(compiledFormatter, field, false, {this, SIGNUM_POS_ZERO, plural});
}
}
@@ -325,7 +332,7 @@ void LongNameHandler::multiSimpleFormatsToModifiers(const UnicodeString *leadFor
if (U_FAILURE(status)) { return; }
SimpleFormatter compoundCompiled(compoundFormat, 0, 1, status);
if (U_FAILURE(status)) { return; }
fModifiers[i] = SimpleModifier(compoundCompiled, field, false, {this, SIGNUM_ZERO, plural});
fModifiers[i] = SimpleModifier(compoundCompiled, field, false, {this, SIGNUM_POS_ZERO, plural});
}
}
+4 -18
View File
@@ -13,7 +13,6 @@
#include "number_patternstring.h"
#include "unicode/errorcode.h"
#include "number_utils.h"
#include "number_currencysymbols.h"
using namespace icu;
using namespace icu::number;
@@ -63,17 +62,8 @@ MacroProps NumberPropertyMapper::oldToNew(const DecimalFormatProperties& propert
// AFFIXES //
/////////////
AffixPatternProvider* affixProvider;
if (properties.currencyPluralInfo.fPtr.isNull()) {
warehouse.currencyPluralInfoAPP.setToBogus();
warehouse.propertiesAPP.setTo(properties, status);
affixProvider = &warehouse.propertiesAPP;
} else {
warehouse.currencyPluralInfoAPP.setTo(*properties.currencyPluralInfo.fPtr, properties, status);
warehouse.propertiesAPP.setToBogus();
affixProvider = &warehouse.currencyPluralInfoAPP;
}
macros.affixProvider = affixProvider;
warehouse.affixProvider.setTo(properties, status);
macros.affixProvider = &warehouse.affixProvider.get();
///////////
// UNITS //
@@ -83,15 +73,13 @@ MacroProps NumberPropertyMapper::oldToNew(const DecimalFormatProperties& propert
!properties.currency.isNull() ||
!properties.currencyPluralInfo.fPtr.isNull() ||
!properties.currencyUsage.isNull() ||
affixProvider->hasCurrencySign());
warehouse.affixProvider.get().hasCurrencySign());
CurrencyUnit currency = resolveCurrency(properties, locale, status);
UCurrencyUsage currencyUsage = properties.currencyUsage.getOrDefault(UCURR_USAGE_STANDARD);
if (useCurrency) {
// NOTE: Slicing is OK.
macros.unit = currency; // NOLINT
}
warehouse.currencySymbols = {currency, locale, symbols, status};
macros.currencySymbols = &warehouse.currencySymbols;
///////////////////////
// ROUNDING STRATEGY //
@@ -125,10 +113,8 @@ MacroProps NumberPropertyMapper::oldToNew(const DecimalFormatProperties& propert
}
// Validate min/max int/frac.
// For backwards compatibility, minimum overrides maximum if the two conflict.
// The following logic ensures that there is always a minimum of at least one digit.
if (minInt == 0 && maxFrac != 0) {
// Force a digit after the decimal point.
minFrac = minFrac <= 0 ? 1 : minFrac;
minFrac = (minFrac < 0 || (minFrac == 0 && maxInt == 0)) ? 1 : minFrac;
maxFrac = maxFrac < 0 ? -1 : maxFrac < minFrac ? minFrac : maxFrac;
minInt = 0;
maxInt = maxInt < 0 ? -1 : maxInt > kMaxIntFracSig ? -1 : maxInt;
+47 -9
View File
@@ -20,6 +20,10 @@ namespace number {
namespace impl {
class AutoAffixPatternProvider;
class CurrencyPluralInfoAffixProvider;
class PropertiesAffixPatternProvider : public AffixPatternProvider, public UMemory {
public:
bool isBogus() const {
@@ -32,12 +36,6 @@ class PropertiesAffixPatternProvider : public AffixPatternProvider, public UMemo
void setTo(const DecimalFormatProperties& properties, UErrorCode& status);
PropertiesAffixPatternProvider() = default; // puts instance in valid but undefined state
PropertiesAffixPatternProvider(const DecimalFormatProperties& properties, UErrorCode& status) {
setTo(properties, status);
}
// AffixPatternProvider Methods:
char16_t charAt(int32_t flags, int32_t i) const U_OVERRIDE;
@@ -65,9 +63,14 @@ class PropertiesAffixPatternProvider : public AffixPatternProvider, public UMemo
UnicodeString negSuffix;
bool isCurrencyPattern;
PropertiesAffixPatternProvider() = default; // puts instance in valid but undefined state
const UnicodeString& getStringInternal(int32_t flags) const;
bool fBogus{true};
friend class AutoAffixPatternProvider;
friend class CurrencyPluralInfoAffixProvider;
};
@@ -107,7 +110,43 @@ class CurrencyPluralInfoAffixProvider : public AffixPatternProvider, public UMem
private:
PropertiesAffixPatternProvider affixesByPlural[StandardPlural::COUNT];
CurrencyPluralInfoAffixProvider() = default;
bool fBogus{true};
friend class AutoAffixPatternProvider;
};
class AutoAffixPatternProvider {
public:
inline AutoAffixPatternProvider() = default;
inline AutoAffixPatternProvider(const DecimalFormatProperties& properties, UErrorCode& status) {
setTo(properties, status);
}
inline void setTo(const DecimalFormatProperties& properties, UErrorCode& status) {
if (properties.currencyPluralInfo.fPtr.isNull()) {
propertiesAPP.setTo(properties, status);
currencyPluralInfoAPP.setToBogus();
} else {
propertiesAPP.setToBogus();
currencyPluralInfoAPP.setTo(*properties.currencyPluralInfo.fPtr, properties, status);
}
}
inline const AffixPatternProvider& get() const {
if (!currencyPluralInfoAPP.isBogus()) {
return currencyPluralInfoAPP;
} else {
return propertiesAPP;
}
}
private:
PropertiesAffixPatternProvider propertiesAPP;
CurrencyPluralInfoAffixProvider currencyPluralInfoAPP;
};
@@ -115,9 +154,8 @@ class CurrencyPluralInfoAffixProvider : public AffixPatternProvider, public UMem
* A struct for ownership of a few objects needed for formatting.
*/
struct DecimalFormatWarehouse {
PropertiesAffixPatternProvider propertiesAPP;
CurrencyPluralInfoAffixProvider currencyPluralInfoAPP;
CurrencySymbols currencySymbols;
AutoAffixPatternProvider affixProvider;
};
+1 -1
View File
@@ -37,7 +37,7 @@ struct MicroProps : public MicroPropsGenerator {
// Note: This struct has no direct ownership of the following pointers.
const DecimalFormatSymbols* symbols;
const Modifier* modOuter;
const Modifier* modMiddle;
const Modifier* modMiddle = nullptr;
const Modifier* modInner;
// The following "helper" fields may optionally be used during the MicroPropsGenerator.
+20 -12
View File
@@ -89,7 +89,7 @@ bool ConstantAffixModifier::isStrong() const {
return fStrong;
}
bool ConstantAffixModifier::containsField(UNumberFormatFields field) const {
bool ConstantAffixModifier::containsField(Field field) const {
(void)field;
// This method is not currently used.
UPRV_UNREACHABLE;
@@ -151,7 +151,7 @@ SimpleModifier::SimpleModifier(const SimpleFormatter &simpleFormatter, Field fie
}
SimpleModifier::SimpleModifier()
: fField(UNUM_FIELD_COUNT), fStrong(false), fPrefixLength(0), fSuffixLength(0) {
: fField(kUndefinedField), fStrong(false), fPrefixLength(0), fSuffixLength(0) {
}
int32_t SimpleModifier::apply(FormattedStringBuilder &output, int leftIndex, int rightIndex,
@@ -178,7 +178,7 @@ bool SimpleModifier::isStrong() const {
return fStrong;
}
bool SimpleModifier::containsField(UNumberFormatFields field) const {
bool SimpleModifier::containsField(Field field) const {
(void)field;
// This method is not currently used.
UPRV_UNREACHABLE;
@@ -292,7 +292,7 @@ int32_t ConstantMultiFieldModifier::apply(FormattedStringBuilder &output, int le
leftIndex + length,
rightIndex + length,
UnicodeString(), 0, 0,
UNUM_FIELD_COUNT, status);
kUndefinedField, status);
}
length += output.insert(rightIndex + length, fSuffix, status);
return length;
@@ -310,7 +310,7 @@ bool ConstantMultiFieldModifier::isStrong() const {
return fStrong;
}
bool ConstantMultiFieldModifier::containsField(UNumberFormatFields field) const {
bool ConstantMultiFieldModifier::containsField(Field field) const {
return fPrefix.containsField(field) || fSuffix.containsField(field);
}
@@ -342,7 +342,7 @@ CurrencySpacingEnabledModifier::CurrencySpacingEnabledModifier(const FormattedSt
: ConstantMultiFieldModifier(prefix, suffix, overwrite, strong) {
// Check for currency spacing. Do not build the UnicodeSets unless there is
// a currency code point at a boundary.
if (prefix.length() > 0 && prefix.fieldAt(prefix.length() - 1) == UNUM_CURRENCY_FIELD) {
if (prefix.length() > 0 && prefix.fieldAt(prefix.length() - 1) == Field(UFIELD_CATEGORY_NUMBER, UNUM_CURRENCY_FIELD)) {
int prefixCp = prefix.getLastCodePoint();
UnicodeSet prefixUnicodeSet = getUnicodeSet(symbols, IN_CURRENCY, PREFIX, status);
if (prefixUnicodeSet.contains(prefixCp)) {
@@ -357,8 +357,8 @@ CurrencySpacingEnabledModifier::CurrencySpacingEnabledModifier(const FormattedSt
fAfterPrefixUnicodeSet.setToBogus();
fAfterPrefixInsert.setToBogus();
}
if (suffix.length() > 0 && suffix.fieldAt(0) == UNUM_CURRENCY_FIELD) {
int suffixCp = suffix.getLastCodePoint();
if (suffix.length() > 0 && suffix.fieldAt(0) == Field(UFIELD_CATEGORY_NUMBER, UNUM_CURRENCY_FIELD)) {
int suffixCp = suffix.getFirstCodePoint();
UnicodeSet suffixUnicodeSet = getUnicodeSet(symbols, IN_CURRENCY, SUFFIX, status);
if (suffixUnicodeSet.contains(suffixCp)) {
fBeforeSuffixUnicodeSet = getUnicodeSet(symbols, IN_NUMBER, SUFFIX, status);
@@ -381,12 +381,20 @@ int32_t CurrencySpacingEnabledModifier::apply(FormattedStringBuilder &output, in
if (rightIndex - leftIndex > 0 && !fAfterPrefixUnicodeSet.isBogus() &&
fAfterPrefixUnicodeSet.contains(output.codePointAt(leftIndex))) {
// TODO: Should we use the CURRENCY field here?
length += output.insert(leftIndex, fAfterPrefixInsert, UNUM_FIELD_COUNT, status);
length += output.insert(
leftIndex,
fAfterPrefixInsert,
kUndefinedField,
status);
}
if (rightIndex - leftIndex > 0 && !fBeforeSuffixUnicodeSet.isBogus() &&
fBeforeSuffixUnicodeSet.contains(output.codePointBefore(rightIndex))) {
// TODO: Should we use the CURRENCY field here?
length += output.insert(rightIndex + length, fBeforeSuffixInsert, UNUM_FIELD_COUNT, status);
length += output.insert(
rightIndex + length,
fBeforeSuffixInsert,
kUndefinedField,
status);
}
// Call super for the remaining logic
@@ -422,7 +430,7 @@ CurrencySpacingEnabledModifier::applyCurrencySpacingAffix(FormattedStringBuilder
// This works even if the last code point in the prefix is 2 code units because the
// field value gets populated to both indices in the field array.
Field affixField = (affix == PREFIX) ? output.fieldAt(index - 1) : output.fieldAt(index);
if (affixField != UNUM_CURRENCY_FIELD) {
if (affixField != Field(UFIELD_CATEGORY_NUMBER, UNUM_CURRENCY_FIELD)) {
return 0;
}
int affixCp = (affix == PREFIX) ? output.codePointBefore(index) : output.codePointAt(index);
@@ -443,7 +451,7 @@ CurrencySpacingEnabledModifier::applyCurrencySpacingAffix(FormattedStringBuilder
// However, the build code path is more efficient, and this is the most natural
// place to put currency spacing in the non-build code path.
// TODO: Should we use the CURRENCY field here?
return output.insert(index, spacingString, UNUM_FIELD_COUNT, status);
return output.insert(index, spacingString, kUndefinedField, status);
}
UnicodeSet
+7 -7
View File
@@ -37,7 +37,7 @@ class U_I18N_API ConstantAffixModifier : public Modifier, public UObject {
bool isStrong() const U_OVERRIDE;
bool containsField(UNumberFormatFields field) const U_OVERRIDE;
bool containsField(Field field) const U_OVERRIDE;
void getParameters(Parameters& output) const U_OVERRIDE;
@@ -73,7 +73,7 @@ class U_I18N_API SimpleModifier : public Modifier, public UMemory {
bool isStrong() const U_OVERRIDE;
bool containsField(UNumberFormatFields field) const U_OVERRIDE;
bool containsField(Field field) const U_OVERRIDE;
void getParameters(Parameters& output) const U_OVERRIDE;
@@ -166,7 +166,7 @@ class U_I18N_API ConstantMultiFieldModifier : public Modifier, public UMemory {
bool isStrong() const U_OVERRIDE;
bool containsField(UNumberFormatFields field) const U_OVERRIDE;
bool containsField(Field field) const U_OVERRIDE;
void getParameters(Parameters& output) const U_OVERRIDE;
@@ -255,7 +255,7 @@ class U_I18N_API EmptyModifier : public Modifier, public UMemory {
return fStrong;
}
bool containsField(UNumberFormatFields field) const U_OVERRIDE {
bool containsField(Field field) const U_OVERRIDE {
(void)field;
return false;
}
@@ -319,12 +319,12 @@ class U_I18N_API AdoptingModifierStore : public ModifierStore, public UMemory {
private:
// NOTE: mods is zero-initialized (to nullptr)
const Modifier *mods[3 * StandardPlural::COUNT] = {};
const Modifier *mods[4 * StandardPlural::COUNT] = {};
inline static int32_t getModIndex(Signum signum, StandardPlural::Form plural) {
U_ASSERT(signum >= -1 && signum <= 1);
U_ASSERT(signum >= 0 && signum < SIGNUM_COUNT);
U_ASSERT(plural >= 0 && plural < StandardPlural::COUNT);
return static_cast<int32_t>(plural) * 3 + (signum + 1);
return static_cast<int32_t>(plural) * SIGNUM_COUNT + signum;
}
};
-10
View File
@@ -19,16 +19,6 @@ UPRV_FORMATTED_VALUE_SUBCLASS_AUTO_IMPL(FormattedNumber)
#define UPRV_NOARG
UBool FormattedNumber::nextFieldPosition(FieldPosition& fieldPosition, UErrorCode& status) const {
UPRV_FORMATTED_VALUE_METHOD_GUARD(FALSE)
return fData->nextFieldPosition(fieldPosition, status);
}
void FormattedNumber::getAllFieldPositions(FieldPositionIterator& iterator, UErrorCode& status) const {
FieldPositionIteratorHandler fpih(&iterator, status);
getAllFieldPositionsImpl(fpih, status);
}
void FormattedNumber::toDecimalNumber(ByteSink& sink, UErrorCode& status) const {
UPRV_FORMATTED_VALUE_METHOD_GUARD(UPRV_NOARG)
impl::DecNum decnum;
+1 -1
View File
@@ -21,7 +21,7 @@ addPaddingHelper(UChar32 paddingCp, int32_t requiredPadding, FormattedStringBuil
UErrorCode &status) {
for (int32_t i = 0; i < requiredPadding; i++) {
// TODO: If appending to the end, this will cause actual insertion operations. Improve.
string.insertCodePoint(index, paddingCp, UNUM_FIELD_COUNT, status);
string.insertCodePoint(index, paddingCp, kUndefinedField, status);
}
return U16_LENGTH(paddingCp) * requiredPadding;
}
+42 -26
View File
@@ -34,11 +34,13 @@ void MutablePatternModifier::setPatternAttributes(UNumberSignDisplay signDisplay
}
void MutablePatternModifier::setSymbols(const DecimalFormatSymbols* symbols,
const CurrencySymbols* currencySymbols,
const UNumberUnitWidth unitWidth, const PluralRules* rules) {
const CurrencyUnit& currency,
const UNumberUnitWidth unitWidth,
const PluralRules* rules,
UErrorCode& status) {
U_ASSERT((rules != nullptr) == needsPlurals());
fSymbols = symbols;
fCurrencySymbols = currencySymbols;
fCurrencySymbols = {currency, symbols->getLocale(), *symbols, status};
fUnitWidth = unitWidth;
fRules = rules;
}
@@ -55,12 +57,6 @@ bool MutablePatternModifier::needsPlurals() const {
}
ImmutablePatternModifier* MutablePatternModifier::createImmutable(UErrorCode& status) {
return createImmutableAndChain(nullptr, status);
}
ImmutablePatternModifier*
MutablePatternModifier::createImmutableAndChain(const MicroPropsGenerator* parent, UErrorCode& status) {
// TODO: Move StandardPlural VALUES to standardplural.h
static const StandardPlural::Form STANDARD_PLURAL_VALUES[] = {
StandardPlural::Form::ZERO,
@@ -81,8 +77,10 @@ MutablePatternModifier::createImmutableAndChain(const MicroPropsGenerator* paren
for (StandardPlural::Form plural : STANDARD_PLURAL_VALUES) {
setNumberProperties(SIGNUM_POS, plural);
pm->adoptModifier(SIGNUM_POS, plural, createConstantModifier(status));
setNumberProperties(SIGNUM_ZERO, plural);
pm->adoptModifier(SIGNUM_ZERO, plural, createConstantModifier(status));
setNumberProperties(SIGNUM_NEG_ZERO, plural);
pm->adoptModifier(SIGNUM_NEG_ZERO, plural, createConstantModifier(status));
setNumberProperties(SIGNUM_POS_ZERO, plural);
pm->adoptModifier(SIGNUM_POS_ZERO, plural, createConstantModifier(status));
setNumberProperties(SIGNUM_NEG, plural);
pm->adoptModifier(SIGNUM_NEG, plural, createConstantModifier(status));
}
@@ -90,20 +88,22 @@ MutablePatternModifier::createImmutableAndChain(const MicroPropsGenerator* paren
delete pm;
return nullptr;
}
return new ImmutablePatternModifier(pm, fRules, parent); // adopts pm
return new ImmutablePatternModifier(pm, fRules); // adopts pm
} else {
// Faster path when plural keyword is not needed.
setNumberProperties(SIGNUM_POS, StandardPlural::Form::COUNT);
pm->adoptModifierWithoutPlural(SIGNUM_POS, createConstantModifier(status));
setNumberProperties(SIGNUM_ZERO, StandardPlural::Form::COUNT);
pm->adoptModifierWithoutPlural(SIGNUM_ZERO, createConstantModifier(status));
setNumberProperties(SIGNUM_NEG_ZERO, StandardPlural::Form::COUNT);
pm->adoptModifierWithoutPlural(SIGNUM_NEG_ZERO, createConstantModifier(status));
setNumberProperties(SIGNUM_POS_ZERO, StandardPlural::Form::COUNT);
pm->adoptModifierWithoutPlural(SIGNUM_POS_ZERO, createConstantModifier(status));
setNumberProperties(SIGNUM_NEG, StandardPlural::Form::COUNT);
pm->adoptModifierWithoutPlural(SIGNUM_NEG, createConstantModifier(status));
if (U_FAILURE(status)) {
delete pm;
return nullptr;
}
return new ImmutablePatternModifier(pm, nullptr, parent); // adopts pm
return new ImmutablePatternModifier(pm, nullptr); // adopts pm
}
}
@@ -120,13 +120,16 @@ ConstantMultiFieldModifier* MutablePatternModifier::createConstantModifier(UErro
}
}
ImmutablePatternModifier::ImmutablePatternModifier(AdoptingModifierStore* pm, const PluralRules* rules,
const MicroPropsGenerator* parent)
: pm(pm), rules(rules), parent(parent) {}
ImmutablePatternModifier::ImmutablePatternModifier(AdoptingModifierStore* pm, const PluralRules* rules)
: pm(pm), rules(rules), parent(nullptr) {}
void ImmutablePatternModifier::processQuantity(DecimalQuantity& quantity, MicroProps& micros,
UErrorCode& status) const {
parent->processQuantity(quantity, micros, status);
micros.rounder.apply(quantity, status);
if (micros.modMiddle != nullptr) {
return;
}
applyToMicros(micros, quantity, status);
}
@@ -148,6 +151,10 @@ const Modifier* ImmutablePatternModifier::getModifier(Signum signum, StandardPlu
}
}
void ImmutablePatternModifier::addToChain(const MicroPropsGenerator* parent) {
this->parent = parent;
}
/** Used by the unsafe code path. */
MicroPropsGenerator& MutablePatternModifier::addToChain(const MicroPropsGenerator* parent) {
@@ -158,6 +165,10 @@ MicroPropsGenerator& MutablePatternModifier::addToChain(const MicroPropsGenerato
void MutablePatternModifier::processQuantity(DecimalQuantity& fq, MicroProps& micros,
UErrorCode& status) const {
fParent->processQuantity(fq, micros, status);
micros.rounder.apply(fq, status);
if (micros.modMiddle != nullptr) {
return;
}
// The unsafe code path performs self-mutation, so we need a const_cast.
// This method needs to be const because it overrides a const method in the parent class.
auto nonConstThis = const_cast<MutablePatternModifier*>(this);
@@ -186,7 +197,7 @@ int32_t MutablePatternModifier::apply(FormattedStringBuilder& output, int32_t le
UnicodeString(),
0,
0,
UNUM_FIELD_COUNT,
kUndefinedField,
status);
}
CurrencySpacingEnabledModifier::applyCurrencySpacing(
@@ -230,7 +241,7 @@ bool MutablePatternModifier::isStrong() const {
return fStrong;
}
bool MutablePatternModifier::containsField(UNumberFormatFields field) const {
bool MutablePatternModifier::containsField(Field field) const {
(void)field;
// This method is not currently used.
UPRV_UNREACHABLE;
@@ -263,7 +274,12 @@ int32_t MutablePatternModifier::insertSuffix(FormattedStringBuilder& sb, int pos
/** This method contains the heart of the logic for rendering LDML affix strings. */
void MutablePatternModifier::prepareAffix(bool isPrefix) {
PatternStringUtils::patternInfoToStringBuilder(
*fPatternInfo, isPrefix, fSignum, fSignDisplay, fPlural, fPerMilleReplacesPercent, currentAffix);
*fPatternInfo,
isPrefix,
PatternStringUtils::resolveSignDisplay(fSignDisplay, fSignum),
fPlural,
fPerMilleReplacesPercent,
currentAffix);
}
UnicodeString MutablePatternModifier::getSymbol(AffixPatternType type) const {
@@ -280,23 +296,23 @@ UnicodeString MutablePatternModifier::getSymbol(AffixPatternType type) const {
case AffixPatternType::TYPE_CURRENCY_SINGLE: {
// UnitWidth ISO and HIDDEN overrides the singular currency symbol.
if (fUnitWidth == UNumberUnitWidth::UNUM_UNIT_WIDTH_ISO_CODE) {
return fCurrencySymbols->getIntlCurrencySymbol(localStatus);
return fCurrencySymbols.getIntlCurrencySymbol(localStatus);
} else if (fUnitWidth == UNumberUnitWidth::UNUM_UNIT_WIDTH_HIDDEN) {
return UnicodeString();
} else if (fUnitWidth == UNumberUnitWidth::UNUM_UNIT_WIDTH_NARROW) {
return fCurrencySymbols->getNarrowCurrencySymbol(localStatus);
return fCurrencySymbols.getNarrowCurrencySymbol(localStatus);
} else {
return fCurrencySymbols->getCurrencySymbol(localStatus);
return fCurrencySymbols.getCurrencySymbol(localStatus);
}
}
case AffixPatternType::TYPE_CURRENCY_DOUBLE:
return fCurrencySymbols->getIntlCurrencySymbol(localStatus);
return fCurrencySymbols.getIntlCurrencySymbol(localStatus);
case AffixPatternType::TYPE_CURRENCY_TRIPLE:
// NOTE: This is the code path only for patterns containing "¤¤¤".
// Plural currencies set via the API are formatted in LongNameHandler.
// This code path is used by DecimalFormat via CurrencyPluralInfo.
U_ASSERT(fPlural != StandardPlural::Form::COUNT);
return fCurrencySymbols->getPluralName(fPlural, localStatus);
return fCurrencySymbols.getPluralName(fPlural, localStatus);
case AffixPatternType::TYPE_CURRENCY_QUAD:
return UnicodeString(u"\uFFFD");
case AffixPatternType::TYPE_CURRENCY_QUINT:
Loaded 100 of 172 files, more files were not shown because too many files have changed in this diff. Show more