tools: update icu to 65.1

Update the version of the bundled ICU (deps/icu-small) to ICU version
65.2.

Fixes: https://github.com/nodejs/node/issues/30211
Fixes: https://github.com/nodejs/node/issues/29540

Backport-PR-URL: https://github.com/nodejs/node/pull/31433
PR-URL: https://github.com/nodejs/node/pull/30232
Reviewed-By: Steven R Loomis <srloomis@us.ibm.com>
Reviewed-By: Michael Dawson <michael_dawson@ca.ibm.com>
Reviewed-By: Ujjwal Sharma <usharma1998@gmail.com>
This commit is contained in:
Albert Wang authored and Myles Borins committed 2020-04-01 01:54:31 -04:00
1 parent d57719098c
commit dca3d298dd
453 files changed
+11972 -6037

No files matched your search

+2 -2
View File
@@ -1,8 +1,8 @@
Small ICU sources - auto generated by shrink-icu-src.py
This directory contains the ICU subset used by --with-intl=small-icu (the default)
It is a strict subset of ICU 64 source files with the following exception(s):
* deps/icu-small/source/data/in/icudt64l.dat : Reduced-size data file
It is a strict subset of ICU 65 source files with the following exception(s):
* deps/icu-small/source/data/in/icudt65l.dat : Reduced-size data file
To rebuild this directory, see ../../tools/icu/README.md
+1 -1
View File
@@ -129,7 +129,7 @@ ICULanguageBreakFactory::getEngineFor(UChar32 c) {
const LanguageBreakEngine *lbe = NULL;
UErrorCode status = U_ZERO_ERROR;
static UMutex gBreakEngineMutex = U_MUTEX_INITIALIZER;
static UMutex gBreakEngineMutex;
Mutex m(&gBreakEngineMutex);
if (fEngines == NULL) {
+1 -1
View File
@@ -277,7 +277,7 @@ ICUBreakIteratorService::~ICUBreakIteratorService() {}
// defined in ucln_cmn.h
U_NAMESPACE_END
static icu::UInitOnce gInitOnceBrkiter;
static icu::UInitOnce gInitOnceBrkiter = U_INITONCE_INITIALIZER;
static icu::ICULocaleService* gService = NULL;
+1 -1
View File
@@ -59,7 +59,7 @@ private:
ByteSink &sink, uint32_t options, Edits *edits);
};
class CharStringByteSink : public ByteSink {
class U_COMMON_API CharStringByteSink : public ByteSink {
public:
CharStringByteSink(CharString* dest);
~CharStringByteSink() override;
+5 -8
View File
@@ -38,8 +38,8 @@ UBool U_CALLCONV characterproperties_cleanup();
constexpr int32_t NUM_INCLUSIONS = UPROPS_SRC_COUNT + UCHAR_INT_LIMIT - UCHAR_INT_START;
struct Inclusion {
UnicodeSet *fSet;
UInitOnce fInitOnce;
UnicodeSet *fSet = nullptr;
UInitOnce fInitOnce = U_INITONCE_INITIALIZER;
};
Inclusion gInclusions[NUM_INCLUSIONS]; // cached getInclusions()
@@ -47,10 +47,7 @@ UnicodeSet *sets[UCHAR_BINARY_LIMIT] = {};
UCPMap *maps[UCHAR_INT_LIMIT - UCHAR_INT_START] = {};
icu::UMutex *cpMutex() {
static icu::UMutex m = U_MUTEX_INITIALIZER;
return &m;
}
icu::UMutex cpMutex;
//----------------------------------------------------------------
// Inclusions list
@@ -361,7 +358,7 @@ u_getBinaryPropertySet(UProperty property, UErrorCode *pErrorCode) {
*pErrorCode = U_ILLEGAL_ARGUMENT_ERROR;
return nullptr;
}
Mutex m(cpMutex());
Mutex m(&cpMutex);
UnicodeSet *set = sets[property];
if (set == nullptr) {
sets[property] = set = makeSet(property, *pErrorCode);
@@ -377,7 +374,7 @@ u_getIntPropertyMap(UProperty property, UErrorCode *pErrorCode) {
*pErrorCode = U_ILLEGAL_ARGUMENT_ERROR;
return nullptr;
}
Mutex m(cpMutex());
Mutex m(&cpMutex);
UCPMap *map = maps[property - UCHAR_INT_START];
if (map == nullptr) {
maps[property - UCHAR_INT_START] = map = makeMap(property, *pErrorCode);
+23
View File
@@ -35,6 +35,17 @@ CharString& CharString::operator=(CharString&& src) U_NOEXCEPT {
return *this;
}
char *CharString::cloneData(UErrorCode &errorCode) const {
if (U_FAILURE(errorCode)) { return nullptr; }
char *p = static_cast<char *>(uprv_malloc(len + 1));
if (p == nullptr) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return nullptr;
}
uprv_memcpy(p, buffer.getAlias(), len + 1);
return p;
}
CharString &CharString::copyFrom(const CharString &s, UErrorCode &errorCode) {
if(U_SUCCESS(errorCode) && this!=&s && ensureCapacity(s.len+1, 0, errorCode)) {
len=s.len;
@@ -52,6 +63,18 @@ int32_t CharString::lastIndexOf(char c) const {
return -1;
}
bool CharString::contains(StringPiece s) const {
if (s.empty()) { return false; }
const char *p = buffer.getAlias();
int32_t lastStart = len - s.length();
for (int32_t i = 0; i <= lastStart; ++i) {
if (uprv_memcmp(p + i, s.data(), s.length()) == 0) {
return true;
}
}
return false;
}
CharString &CharString::truncate(int32_t newLength) {
if(newLength<0) {
newLength=0;
+14
View File
@@ -82,10 +82,24 @@ public:
const char *data() const { return buffer.getAlias(); }
char *data() { return buffer.getAlias(); }
/**
* Allocates length()+1 chars and copies the NUL-terminated data().
* The caller must uprv_free() the result.
*/
char *cloneData(UErrorCode &errorCode) const;
bool operator==(StringPiece other) const {
return len == other.length() && (len == 0 || uprv_memcmp(data(), other.data(), len) == 0);
}
bool operator!=(StringPiece other) const {
return !operator==(other);
}
/** @return last index of c, or -1 if c is not in this string */
int32_t lastIndexOf(char c) const;
bool contains(StringPiece s) const;
CharString &clear() { len=0; buffer[0]=0; return *this; }
CharString &truncate(int32_t newLength);
+22 -23
View File
@@ -64,38 +64,37 @@ uprv_free(void *mem);
U_CAPI void * U_EXPORT2
uprv_calloc(size_t num, size_t size) U_MALLOC_ATTR U_ALLOC_SIZE_ATTR2(1,2);
/**
* This should align the memory properly on any machine.
* This is very useful for the safeClone functions.
*/
typedef union {
long t1;
double t2;
void *t3;
} UAlignedMemory;
/**
* Get the least significant bits of a pointer (a memory address).
* For example, with a mask of 3, the macro gets the 2 least significant bits,
* which will be 0 if the pointer is 32-bit (4-byte) aligned.
*
* ptrdiff_t is the most appropriate integer type to cast to.
* size_t should work too, since on most (or all?) platforms it has the same
* width as ptrdiff_t.
* uintptr_t is the most appropriate integer type to cast to.
*/
#define U_POINTER_MASK_LSB(ptr, mask) (((ptrdiff_t)(char *)(ptr)) & (mask))
#define U_POINTER_MASK_LSB(ptr, mask) ((uintptr_t)(ptr) & (mask))
/**
* Get the amount of bytes that a pointer is off by from
* the previous UAlignedMemory-aligned pointer.
* Create & return an instance of "type" in statically allocated storage.
* e.g.
* static std::mutex *myMutex = STATIC_NEW(std::mutex);
* To destroy an object created in this way, invoke the destructor explicitly, e.g.
* myMutex->~mutex();
* DO NOT use delete.
* DO NOT use with class UMutex, which has specific support for static instances.
*
* STATIC_NEW is intended for use when
* - We want a static (or global) object.
* - We don't want it to ever be destructed, or to explicitly control destruction,
* to avoid use-after-destruction problems.
* - We want to avoid an ordinary heap allocated object,
* to avoid the possibility of memory allocation failures, and
* to avoid memory leak reports, from valgrind, for example.
* This is defined as a macro rather than a template function because each invocation
* must define distinct static storage for the object being returned.
*/
#define U_ALIGNMENT_OFFSET(ptr) U_POINTER_MASK_LSB(ptr, sizeof(UAlignedMemory) - 1)
/**
* Get the amount of bytes to add to a pointer
* in order to get the next UAlignedMemory-aligned address.
*/
#define U_ALIGNMENT_OFFSET_UP(ptr) (sizeof(UAlignedMemory) - U_ALIGNMENT_OFFSET(ptr))
#define STATIC_NEW(type) [] () { \
alignas(type) static char storage[sizeof(type)]; \
return new(storage) type();} ()
/**
* Heap clean up function, called from u_cleanup()
+1 -1
View File
@@ -243,7 +243,7 @@ UBool Edits::growArray() {
return TRUE;
}
UBool Edits::copyErrorTo(UErrorCode &outErrorCode) {
UBool Edits::copyErrorTo(UErrorCode &outErrorCode) const {
if (U_FAILURE(outErrorCode)) { return TRUE; }
if (U_SUCCESS(errorCode_)) { return FALSE; }
outErrorCode = errorCode_;
+1 -1
View File
@@ -173,7 +173,7 @@ public:
status = U_SAFECLONE_ALLOCATED_WARNING;
return clone();
}
virtual BreakIterator* clone(void) const { return new SimpleFilteredSentenceBreakIterator(*this); }
virtual SimpleFilteredSentenceBreakIterator* clone() const { return new SimpleFilteredSentenceBreakIterator(*this); }
virtual UClassID getDynamicClassID(void) const { return NULL; }
virtual UBool operator==(const BreakIterator& o) const { if(this==&o) return true; return false; }
+46 -14
View File
@@ -157,13 +157,18 @@ _isKeywordValue(const char* key, const char* value, int32_t value_len)
}
static void
_copyExtensions(const Locale& from, Locale* to, bool validate, UErrorCode& errorCode)
_copyExtensions(const Locale& from, icu::StringEnumeration *keywords,
Locale& to, bool validate, UErrorCode& errorCode)
{
if (U_FAILURE(errorCode)) { return; }
LocalPointer<icu::StringEnumeration> iter(from.createKeywords(errorCode));
if (U_FAILURE(errorCode) || iter.isNull()) { return; }
LocalPointer<icu::StringEnumeration> ownedKeywords;
if (keywords == nullptr) {
ownedKeywords.adoptInstead(from.createKeywords(errorCode));
if (U_FAILURE(errorCode) || ownedKeywords.isNull()) { return; }
keywords = ownedKeywords.getAlias();
}
const char* key;
while ((key = iter->next(nullptr, errorCode)) != nullptr) {
while ((key = keywords->next(nullptr, errorCode)) != nullptr) {
CharString value;
CharStringByteSink sink(&value);
from.getKeywordValue(key, sink, errorCode);
@@ -176,34 +181,34 @@ _copyExtensions(const Locale& from, Locale* to, bool validate, UErrorCode& error
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
to->setKeywordValue(key, value.data(), errorCode);
to.setKeywordValue(key, value.data(), errorCode);
if (U_FAILURE(errorCode)) { return; }
}
}
void static
_clearUAttributesAndKeyType(Locale* locale, UErrorCode& errorCode)
_clearUAttributesAndKeyType(Locale& locale, UErrorCode& errorCode)
{
// Clear Unicode attributes
locale->setKeywordValue(kAttributeKey, "", errorCode);
locale.setKeywordValue(kAttributeKey, "", errorCode);
// Clear all Unicode keyword values
LocalPointer<icu::StringEnumeration> iter(locale->createUnicodeKeywords(errorCode));
LocalPointer<icu::StringEnumeration> iter(locale.createUnicodeKeywords(errorCode));
if (U_FAILURE(errorCode) || iter.isNull()) { return; }
const char* key;
while ((key = iter->next(nullptr, errorCode)) != nullptr) {
locale->setUnicodeKeywordValue(key, nullptr, errorCode);
locale.setUnicodeKeywordValue(key, nullptr, errorCode);
}
}
static void
_setUnicodeExtensions(Locale* locale, const CharString& value, UErrorCode& errorCode)
_setUnicodeExtensions(Locale& locale, const CharString& value, UErrorCode& errorCode)
{
// Add the unicode extensions to extensions_
CharString locale_str("und-u-", errorCode);
locale_str.append(value, errorCode);
_copyExtensions(
Locale::forLanguageTag(locale_str.data(), errorCode),
Locale::forLanguageTag(locale_str.data(), errorCode), nullptr,
locale, false, errorCode);
}
@@ -235,10 +240,10 @@ LocaleBuilder& LocaleBuilder::setExtension(char key, StringPiece value)
status_);
return *this;
}
_clearUAttributesAndKeyType(extensions_, status_);
_clearUAttributesAndKeyType(*extensions_, status_);
if (U_FAILURE(status_)) { return *this; }
if (!value.empty()) {
_setUnicodeExtensions(extensions_, value_str, status_);
_setUnicodeExtensions(*extensions_, value_str, status_);
}
return *this;
}
@@ -401,6 +406,24 @@ Locale makeBogusLocale() {
return bogus;
}
void LocaleBuilder::copyExtensionsFrom(const Locale& src, UErrorCode& errorCode)
{
if (U_FAILURE(errorCode)) { return; }
LocalPointer<icu::StringEnumeration> keywords(src.createKeywords(errorCode));
if (U_FAILURE(errorCode) || keywords.isNull() || keywords->count(errorCode) == 0) {
// Error, or no extensions to copy.
return;
}
if (extensions_ == nullptr) {
extensions_ = new Locale();
if (extensions_ == nullptr) {
status_ = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
_copyExtensions(src, keywords.getAlias(), *extensions_, false, errorCode);
}
Locale LocaleBuilder::build(UErrorCode& errorCode)
{
if (U_FAILURE(errorCode)) {
@@ -425,7 +448,7 @@ Locale LocaleBuilder::build(UErrorCode& errorCode)
}
Locale product(locale_str.data());
if (extensions_ != nullptr) {
_copyExtensions(*extensions_, &product, true, errorCode);
_copyExtensions(*extensions_, nullptr, product, true, errorCode);
}
if (U_FAILURE(errorCode)) {
return makeBogusLocale();
@@ -433,4 +456,13 @@ Locale LocaleBuilder::build(UErrorCode& errorCode)
return product;
}
UBool LocaleBuilder::copyErrorTo(UErrorCode &outErrorCode) const {
if (U_FAILURE(outErrorCode)) {
// Do not overwrite the older error code
return TRUE;
}
outErrorCode = status_;
return U_FAILURE(outErrorCode);
}
U_NAMESPACE_END
+720
View File
@@ -0,0 +1,720 @@
// © 2019 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
// localematcher.cpp
// created: 2019may08 Markus W. Scherer
#ifndef __LOCMATCHER_H__
#define __LOCMATCHER_H__
#include "unicode/utypes.h"
#include "unicode/localebuilder.h"
#include "unicode/localematcher.h"
#include "unicode/locid.h"
#include "unicode/stringpiece.h"
#include "unicode/uobject.h"
#include "cstring.h"
#include "localeprioritylist.h"
#include "loclikelysubtags.h"
#include "locdistance.h"
#include "lsr.h"
#include "uassert.h"
#include "uhash.h"
#include "uvector.h"
#define UND_LSR LSR("und", "", "")
/**
* Indicator for the lifetime of desired-locale objects passed into the LocaleMatcher.
*
* @draft ICU 65
*/
enum ULocMatchLifetime {
/**
* Locale objects are temporary.
* The matcher will make a copy of a locale that will be used beyond one function call.
*
* @draft ICU 65
*/
ULOCMATCH_TEMPORARY_LOCALES,
/**
* Locale objects are stored at least as long as the matcher is used.
* The matcher will keep only a pointer to a locale that will be used beyond one function call,
* avoiding a copy.
*
* @draft ICU 65
*/
ULOCMATCH_STORED_LOCALES // TODO: permanent? cached? clone?
};
#ifndef U_IN_DOXYGEN
typedef enum ULocMatchLifetime ULocMatchLifetime;
#endif
U_NAMESPACE_BEGIN
LocaleMatcher::Result::Result(LocaleMatcher::Result &&src) U_NOEXCEPT :
desiredLocale(src.desiredLocale),
supportedLocale(src.supportedLocale),
desiredIndex(src.desiredIndex),
supportedIndex(src.supportedIndex),
desiredIsOwned(src.desiredIsOwned) {
if (desiredIsOwned) {
src.desiredLocale = nullptr;
src.desiredIndex = -1;
src.desiredIsOwned = FALSE;
}
}
LocaleMatcher::Result::~Result() {
if (desiredIsOwned) {
delete desiredLocale;
}
}
LocaleMatcher::Result &LocaleMatcher::Result::operator=(LocaleMatcher::Result &&src) U_NOEXCEPT {
this->~Result();
desiredLocale = src.desiredLocale;
supportedLocale = src.supportedLocale;
desiredIndex = src.desiredIndex;
supportedIndex = src.supportedIndex;
desiredIsOwned = src.desiredIsOwned;
if (desiredIsOwned) {
src.desiredLocale = nullptr;
src.desiredIndex = -1;
src.desiredIsOwned = FALSE;
}
return *this;
}
Locale LocaleMatcher::Result::makeResolvedLocale(UErrorCode &errorCode) const {
if (U_FAILURE(errorCode) || supportedLocale == nullptr) {
return Locale::getRoot();
}
const Locale *bestDesired = getDesiredLocale();
if (bestDesired == nullptr || *supportedLocale == *bestDesired) {
return *supportedLocale;
}
LocaleBuilder b;
b.setLocale(*supportedLocale);
// Copy the region from bestDesired, if there is one.
const char *region = bestDesired->getCountry();
if (*region != 0) {
b.setRegion(region);
}
// Copy the variants from bestDesired, if there are any.
// Note that this will override any supportedLocale variants.
// For example, "sco-ulster-fonipa" + "...-fonupa" => "sco-fonupa" (replacing ulster).
const char *variants = bestDesired->getVariant();
if (*variants != 0) {
b.setVariant(variants);
}
// Copy the extensions from bestDesired, if there are any.
// C++ note: The following note, copied from Java, may not be true,
// as long as C++ copies by legacy ICU keyword, not by extension singleton.
// Note that this will override any supportedLocale extensions.
// For example, "th-u-nu-latn-ca-buddhist" + "...-u-nu-native" => "th-u-nu-native"
// (replacing calendar).
b.copyExtensionsFrom(*bestDesired, errorCode);
return b.build(errorCode);
}
LocaleMatcher::Builder::Builder(LocaleMatcher::Builder &&src) U_NOEXCEPT :
errorCode_(src.errorCode_),
supportedLocales_(src.supportedLocales_),
thresholdDistance_(src.thresholdDistance_),
demotion_(src.demotion_),
defaultLocale_(src.defaultLocale_),
favor_(src.favor_) {
src.supportedLocales_ = nullptr;
src.defaultLocale_ = nullptr;
}
LocaleMatcher::Builder::~Builder() {
delete supportedLocales_;
delete defaultLocale_;
}
LocaleMatcher::Builder &LocaleMatcher::Builder::operator=(LocaleMatcher::Builder &&src) U_NOEXCEPT {
this->~Builder();
errorCode_ = src.errorCode_;
supportedLocales_ = src.supportedLocales_;
thresholdDistance_ = src.thresholdDistance_;
demotion_ = src.demotion_;
defaultLocale_ = src.defaultLocale_;
favor_ = src.favor_;
src.supportedLocales_ = nullptr;
src.defaultLocale_ = nullptr;
return *this;
}
void LocaleMatcher::Builder::clearSupportedLocales() {
if (supportedLocales_ != nullptr) {
supportedLocales_->removeAllElements();
}
}
bool LocaleMatcher::Builder::ensureSupportedLocaleVector() {
if (U_FAILURE(errorCode_)) { return false; }
if (supportedLocales_ != nullptr) { return true; }
supportedLocales_ = new UVector(uprv_deleteUObject, nullptr, errorCode_);
if (U_FAILURE(errorCode_)) { return false; }
if (supportedLocales_ == nullptr) {
errorCode_ = U_MEMORY_ALLOCATION_ERROR;
return false;
}
return true;
}
LocaleMatcher::Builder &LocaleMatcher::Builder::setSupportedLocalesFromListString(
StringPiece locales) {
LocalePriorityList list(locales, errorCode_);
if (U_FAILURE(errorCode_)) { return *this; }
clearSupportedLocales();
if (!ensureSupportedLocaleVector()) { return *this; }
int32_t length = list.getLengthIncludingRemoved();
for (int32_t i = 0; i < length; ++i) {
Locale *locale = list.orphanLocaleAt(i);
if (locale == nullptr) { continue; }
supportedLocales_->addElement(locale, errorCode_);
if (U_FAILURE(errorCode_)) {
delete locale;
break;
}
}
return *this;
}
LocaleMatcher::Builder &LocaleMatcher::Builder::setSupportedLocales(Locale::Iterator &locales) {
if (U_FAILURE(errorCode_)) { return *this; }
clearSupportedLocales();
if (!ensureSupportedLocaleVector()) { return *this; }
while (locales.hasNext()) {
const Locale &locale = locales.next();
Locale *clone = locale.clone();
if (clone == nullptr) {
errorCode_ = U_MEMORY_ALLOCATION_ERROR;
break;
}
supportedLocales_->addElement(clone, errorCode_);
if (U_FAILURE(errorCode_)) {
delete clone;
break;
}
}
return *this;
}
LocaleMatcher::Builder &LocaleMatcher::Builder::addSupportedLocale(const Locale &locale) {
if (!ensureSupportedLocaleVector()) { return *this; }
Locale *clone = locale.clone();
if (clone == nullptr) {
errorCode_ = U_MEMORY_ALLOCATION_ERROR;
return *this;
}
supportedLocales_->addElement(clone, errorCode_);
if (U_FAILURE(errorCode_)) {
delete clone;
}
return *this;
}
LocaleMatcher::Builder &LocaleMatcher::Builder::setDefaultLocale(const Locale *defaultLocale) {
if (U_FAILURE(errorCode_)) { return *this; }
Locale *clone = nullptr;
if (defaultLocale != nullptr) {
clone = defaultLocale->clone();
if (clone == nullptr) {
errorCode_ = U_MEMORY_ALLOCATION_ERROR;
return *this;
}
}
delete defaultLocale_;
defaultLocale_ = clone;
return *this;
}
LocaleMatcher::Builder &LocaleMatcher::Builder::setFavorSubtag(ULocMatchFavorSubtag subtag) {
if (U_FAILURE(errorCode_)) { return *this; }
favor_ = subtag;
return *this;
}
LocaleMatcher::Builder &LocaleMatcher::Builder::setDemotionPerDesiredLocale(ULocMatchDemotion demotion) {
if (U_FAILURE(errorCode_)) { return *this; }
demotion_ = demotion;
return *this;
}
#if 0
/**
* <i>Internal only!</i>
*
* @param thresholdDistance the thresholdDistance to set, with -1 = default
* @return this Builder object
* @internal
* @deprecated This API is ICU internal only.
*/
@Deprecated
LocaleMatcher::Builder &LocaleMatcher::Builder::internalSetThresholdDistance(int32_t thresholdDistance) {
if (U_FAILURE(errorCode_)) { return *this; }
if (thresholdDistance > 100) {
thresholdDistance = 100;
}
thresholdDistance_ = thresholdDistance;
return *this;
}
#endif
UBool LocaleMatcher::Builder::copyErrorTo(UErrorCode &outErrorCode) const {
if (U_FAILURE(outErrorCode)) { return TRUE; }
if (U_SUCCESS(errorCode_)) { return FALSE; }
outErrorCode = errorCode_;
return TRUE;
}
LocaleMatcher LocaleMatcher::Builder::build(UErrorCode &errorCode) const {
if (U_SUCCESS(errorCode) && U_FAILURE(errorCode_)) {
errorCode = errorCode_;
}
return LocaleMatcher(*this, errorCode);
}
namespace {
LSR getMaximalLsrOrUnd(const XLikelySubtags &likelySubtags, const Locale &locale,
UErrorCode &errorCode) {
if (U_FAILURE(errorCode) || locale.isBogus() || *locale.getName() == 0 /* "und" */) {
return UND_LSR;
} else {
return likelySubtags.makeMaximizedLsrFrom(locale, errorCode);
}
}
int32_t hashLSR(const UHashTok token) {
const LSR *lsr = static_cast<const LSR *>(token.pointer);
return lsr->hashCode;
}
UBool compareLSRs(const UHashTok t1, const UHashTok t2) {
const LSR *lsr1 = static_cast<const LSR *>(t1.pointer);
const LSR *lsr2 = static_cast<const LSR *>(t2.pointer);
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
LocaleMatcher::LocaleMatcher(const Builder &builder, UErrorCode &errorCode) :
likelySubtags(*XLikelySubtags::getSingleton(errorCode)),
localeDistance(*LocaleDistance::getSingleton(errorCode)),
thresholdDistance(builder.thresholdDistance_),
demotionPerDesiredLocale(0),
favorSubtag(builder.favor_),
supportedLocales(nullptr), lsrs(nullptr), supportedLocalesLength(0),
supportedLsrToIndex(nullptr),
supportedLSRs(nullptr), supportedIndexes(nullptr), supportedLSRsLength(0),
ownedDefaultLocale(nullptr), defaultLocale(nullptr), defaultLocaleIndex(-1) {
if (U_FAILURE(errorCode)) { return; }
if (thresholdDistance < 0) {
thresholdDistance = localeDistance.getDefaultScriptDistance();
}
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)
// we can return those by parallel index.
supportedLocales = static_cast<const Locale **>(
uprv_malloc(supportedLocalesLength * sizeof(const Locale *)));
// Supported LRSs in input order.
// In C++, we store these permanently to simplify ownership management
// in the hash tables. Duplicate LSRs (if any) are unused overhead.
lsrs = new LSR[supportedLocalesLength];
if (supportedLocales == nullptr || lsrs == nullptr) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
// 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();
if (supportedLocales[i] == nullptr) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
const Locale &supportedLocale = *supportedLocales[i];
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:
// 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 *)));
supportedIndexes = static_cast<int32_t *>(
uprv_malloc(suppLSRsCapacity * 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;
}
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.
} 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;
}
}
}
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));
}
supportedLSRsLength = otherIndex - (paradigmLimit - paradigmIndex);
}
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();
}
}
LocaleMatcher::LocaleMatcher(LocaleMatcher &&src) U_NOEXCEPT :
likelySubtags(src.likelySubtags),
localeDistance(src.localeDistance),
thresholdDistance(src.thresholdDistance),
demotionPerDesiredLocale(src.demotionPerDesiredLocale),
favorSubtag(src.favorSubtag),
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) {
src.supportedLocales = nullptr;
src.lsrs = nullptr;
src.supportedLocalesLength = 0;
src.supportedLsrToIndex = nullptr;
src.supportedLSRs = nullptr;
src.supportedIndexes = nullptr;
src.supportedLSRsLength = 0;
src.ownedDefaultLocale = nullptr;
src.defaultLocale = nullptr;
src.defaultLocaleIndex = -1;
}
LocaleMatcher::~LocaleMatcher() {
for (int32_t i = 0; i < supportedLocalesLength; ++i) {
delete supportedLocales[i];
}
uprv_free(supportedLocales);
delete[] lsrs;
uhash_close(supportedLsrToIndex);
uprv_free(supportedLSRs);
uprv_free(supportedIndexes);
delete ownedDefaultLocale;
}
LocaleMatcher &LocaleMatcher::operator=(LocaleMatcher &&src) U_NOEXCEPT {
this->~LocaleMatcher();
thresholdDistance = src.thresholdDistance;
demotionPerDesiredLocale = src.demotionPerDesiredLocale;
favorSubtag = src.favorSubtag;
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;
src.supportedLocales = nullptr;
src.lsrs = nullptr;
src.supportedLocalesLength = 0;
src.supportedLsrToIndex = nullptr;
src.supportedLSRs = nullptr;
src.supportedIndexes = nullptr;
src.supportedLSRsLength = 0;
src.ownedDefaultLocale = nullptr;
src.defaultLocale = nullptr;
src.defaultLocaleIndex = -1;
return *this;
}
class LocaleLsrIterator {
public:
LocaleLsrIterator(const XLikelySubtags &likelySubtags, Locale::Iterator &locales,
ULocMatchLifetime lifetime) :
likelySubtags(likelySubtags), locales(locales), lifetime(lifetime) {}
~LocaleLsrIterator() {
if (lifetime == ULOCMATCH_TEMPORARY_LOCALES) {
delete remembered;
}
}
bool hasNext() const {
return locales.hasNext();
}
LSR next(UErrorCode &errorCode) {
current = &locales.next();
return getMaximalLsrOrUnd(likelySubtags, *current, errorCode);
}
void rememberCurrent(int32_t desiredIndex, UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) { return; }
bestDesiredIndex = desiredIndex;
if (lifetime == ULOCMATCH_STORED_LOCALES) {
remembered = current;
} else {
// ULOCMATCH_TEMPORARY_LOCALES
delete remembered;
remembered = new Locale(*current);
if (remembered == nullptr) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
}
}
}
const Locale *orphanRemembered() {
const Locale *rem = remembered;
remembered = nullptr;
return rem;
}
int32_t getBestDesiredIndex() const {
return bestDesiredIndex;
}
private:
const XLikelySubtags &likelySubtags;
Locale::Iterator &locales;
ULocMatchLifetime lifetime;
const Locale *current = nullptr, *remembered = nullptr;
int32_t bestDesiredIndex = -1;
};
const Locale *LocaleMatcher::getBestMatch(const Locale &desiredLocale, UErrorCode &errorCode) const {
if (U_FAILURE(errorCode)) { return nullptr; }
int32_t suppIndex = getBestSuppIndex(
getMaximalLsrOrUnd(likelySubtags, desiredLocale, errorCode),
nullptr, errorCode);
return U_SUCCESS(errorCode) && suppIndex >= 0 ? supportedLocales[suppIndex] : defaultLocale;
}
const Locale *LocaleMatcher::getBestMatch(Locale::Iterator &desiredLocales,
UErrorCode &errorCode) const {
if (U_FAILURE(errorCode)) { return nullptr; }
if (!desiredLocales.hasNext()) {
return defaultLocale;
}
LocaleLsrIterator lsrIter(likelySubtags, desiredLocales, ULOCMATCH_TEMPORARY_LOCALES);
int32_t suppIndex = getBestSuppIndex(lsrIter.next(errorCode), &lsrIter, errorCode);
return U_SUCCESS(errorCode) && suppIndex >= 0 ? supportedLocales[suppIndex] : defaultLocale;
}
const Locale *LocaleMatcher::getBestMatchForListString(
StringPiece desiredLocaleList, UErrorCode &errorCode) const {
LocalePriorityList list(desiredLocaleList, errorCode);
LocalePriorityList::Iterator iter = list.iterator();
return getBestMatch(iter, errorCode);
}
LocaleMatcher::Result LocaleMatcher::getBestMatchResult(
const Locale &desiredLocale, UErrorCode &errorCode) const {
if (U_FAILURE(errorCode)) {
return Result(nullptr, defaultLocale, -1, defaultLocaleIndex, FALSE);
}
int32_t suppIndex = getBestSuppIndex(
getMaximalLsrOrUnd(likelySubtags, desiredLocale, errorCode),
nullptr, errorCode);
if (U_FAILURE(errorCode) || suppIndex < 0) {
return Result(nullptr, defaultLocale, -1, defaultLocaleIndex, FALSE);
} else {
return Result(&desiredLocale, supportedLocales[suppIndex], 0, suppIndex, FALSE);
}
}
LocaleMatcher::Result LocaleMatcher::getBestMatchResult(
Locale::Iterator &desiredLocales, UErrorCode &errorCode) const {
if (U_FAILURE(errorCode) || !desiredLocales.hasNext()) {
return Result(nullptr, defaultLocale, -1, defaultLocaleIndex, 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);
} else {
return Result(lsrIter.orphanRemembered(), supportedLocales[suppIndex],
lsrIter.getBestDesiredIndex(), suppIndex, TRUE);
}
}
int32_t LocaleMatcher::getBestSuppIndex(LSR desiredLSR, LocaleLsrIterator *remainingIter,
UErrorCode &errorCode) const {
if (U_FAILURE(errorCode)) { return -1; }
int32_t desiredIndex = 0;
int32_t bestSupportedLsrIndex = -1;
for (int32_t bestDistance = thresholdDistance;;) {
// Quick check for exact maximized LSR.
// Returns suppIndex+1 where 0 means not found.
if (supportedLsrToIndex != nullptr) {
desiredLSR.setHashCode();
int32_t index = uhash_geti(supportedLsrToIndex, &desiredLSR);
if (index != 0) {
int32_t suppIndex = index - 1;
if (remainingIter != nullptr) {
remainingIter->rememberCurrent(desiredIndex, errorCode);
}
return suppIndex;
}
}
int32_t bestIndexAndDistance = localeDistance.getBestIndexAndDistance(
desiredLSR, supportedLSRs, supportedLSRsLength, bestDistance, favorSubtag);
if (bestIndexAndDistance >= 0) {
bestDistance = bestIndexAndDistance & 0xff;
if (remainingIter != nullptr) {
remainingIter->rememberCurrent(desiredIndex, errorCode);
if (U_FAILURE(errorCode)) { return -1; }
}
bestSupportedLsrIndex = bestIndexAndDistance >= 0 ? bestIndexAndDistance >> 8 : -1;
}
if ((bestDistance -= demotionPerDesiredLocale) <= 0) {
break;
}
if (remainingIter == nullptr || !remainingIter->hasNext()) {
break;
}
desiredLSR = remainingIter->next(errorCode);
if (U_FAILURE(errorCode)) { return -1; }
++desiredIndex;
}
if (bestSupportedLsrIndex < 0) {
// no good match
return -1;
}
return supportedIndexes[bestSupportedLsrIndex];
}
double LocaleMatcher::internalMatch(const Locale &desired, const Locale &supported, UErrorCode &errorCode) const {
// Returns the inverse of the distance: That is, 1-distance(desired, supported).
LSR suppLSR = getMaximalLsrOrUnd(likelySubtags, supported, errorCode);
if (U_FAILURE(errorCode)) { return 0; }
const LSR *pSuppLSR = &suppLSR;
int32_t distance = localeDistance.getBestIndexAndDistance(
getMaximalLsrOrUnd(likelySubtags, desired, errorCode),
&pSuppLSR, 1,
thresholdDistance, favorSubtag) & 0xff;
return (100 - distance) / 100.0;
}
U_NAMESPACE_END
#endif // __LOCMATCHER_H__
+239
View File
@@ -0,0 +1,239 @@
// © 2019 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
// localeprioritylist.cpp
// created: 2019jul11 Markus W. Scherer
#include "unicode/utypes.h"
#include "unicode/localpointer.h"
#include "unicode/locid.h"
#include "unicode/stringpiece.h"
#include "unicode/uobject.h"
#include "charstr.h"
#include "cmemory.h"
#include "localeprioritylist.h"
#include "uarrsort.h"
#include "uassert.h"
#include "uhash.h"
U_NAMESPACE_BEGIN
namespace {
int32_t hashLocale(const UHashTok token) {
auto *locale = static_cast<const Locale *>(token.pointer);
return locale->hashCode();
}
UBool compareLocales(const UHashTok t1, const UHashTok t2) {
auto *l1 = static_cast<const Locale *>(t1.pointer);
auto *l2 = static_cast<const Locale *>(t2.pointer);
return *l1 == *l2;
}
constexpr int32_t WEIGHT_ONE = 1000;
struct LocaleAndWeight {
Locale *locale;
int32_t weight; // 0..1000 = 0.0..1.0
int32_t index; // force stable sort
int32_t compare(const LocaleAndWeight &other) const {
int32_t diff = other.weight - weight; // descending: other-this
if (diff != 0) { return diff; }
return index - other.index;
}
};
int32_t U_CALLCONV
compareLocaleAndWeight(const void * /*context*/, const void *left, const void *right) {
return static_cast<const LocaleAndWeight *>(left)->
compare(*static_cast<const LocaleAndWeight *>(right));
}
const char *skipSpaces(const char *p, const char *limit) {
while (p < limit && *p == ' ') { ++p; }
return p;
}
int32_t findTagLength(const char *p, const char *limit) {
// Look for accept-language delimiters.
// Leave other validation up to the Locale constructor.
const char *q;
for (q = p; q < limit; ++q) {
char c = *q;
if (c == ' ' || c == ',' || c == ';') { break; }
}
return static_cast<int32_t>(q - p);
}
/**
* Parses and returns a qvalue weight in millis.
* Advances p to after the parsed substring.
* Returns a negative value if parsing fails.
*/
int32_t parseWeight(const char *&p, const char *limit) {
p = skipSpaces(p, limit);
char c;
if (p == limit || ((c = *p) != '0' && c != '1')) { return -1; }
int32_t weight = (c - '0') * 1000;
if (++p == limit || *p != '.') { return weight; }
int32_t multiplier = 100;
while (++p != limit && '0' <= (c = *p) && c <= '9') {
c -= '0';
if (multiplier > 0) {
weight += c * multiplier;
multiplier /= 10;
} else if (multiplier == 0) {
// round up
if (c >= 5) { ++weight; }
multiplier = -1;
} // else ignore further fraction digits
}
return weight <= WEIGHT_ONE ? weight : -1; // bad if > 1.0
}
} // namespace
/**
* Nothing but a wrapper over a MaybeStackArray of LocaleAndWeight.
*
* This wrapper exists (and is not in an anonymous namespace)
* so that we can forward-declare it in the header file and
* don't have to expose the MaybeStackArray specialization and
* the LocaleAndWeight to code (like the test) that #includes localeprioritylist.h.
* Also, otherwise we would have to do a platform-specific
* template export declaration of some kind for the MaybeStackArray specialization
* to be properly exported from the common DLL.
*/
struct LocaleAndWeightArray : public UMemory {
MaybeStackArray<LocaleAndWeight, 20> array;
};
LocalePriorityList::LocalePriorityList(StringPiece s, UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) { return; }
list = new LocaleAndWeightArray();
if (list == nullptr) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
const char *p = s.data();
const char *limit = p + s.length();
while ((p = skipSpaces(p, limit)) != limit) {
if (*p == ',') { // empty range field
++p;
continue;
}
int32_t tagLength = findTagLength(p, limit);
if (tagLength == 0) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
CharString tag(p, tagLength, errorCode);
if (U_FAILURE(errorCode)) { return; }
Locale locale = Locale(tag.data());
if (locale.isBogus()) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
int32_t weight = WEIGHT_ONE;
if ((p = skipSpaces(p + tagLength, limit)) != limit && *p == ';') {
if ((p = skipSpaces(p + 1, limit)) == limit || *p != 'q' ||
(p = skipSpaces(p + 1, limit)) == limit || *p != '=' ||
(++p, (weight = parseWeight(p, limit)) < 0)) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
p = skipSpaces(p, limit);
}
if (p != limit && *p != ',') { // trailing junk
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
add(locale, weight, errorCode);
if (p == limit) { break; }
++p;
}
sort(errorCode);
}
LocalePriorityList::~LocalePriorityList() {
if (list != nullptr) {
for (int32_t i = 0; i < listLength; ++i) {
delete list->array[i].locale;
}
delete list;
}
uhash_close(map);
}
const Locale *LocalePriorityList::localeAt(int32_t i) const {
return list->array[i].locale;
}
Locale *LocalePriorityList::orphanLocaleAt(int32_t i) {
if (list == nullptr) { return nullptr; }
LocaleAndWeight &lw = list->array[i];
Locale *l = lw.locale;
lw.locale = nullptr;
return l;
}
bool LocalePriorityList::add(const Locale &locale, int32_t weight, UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) { return false; }
if (map == nullptr) {
if (weight <= 0) { return true; } // do not add q=0
map = uhash_open(hashLocale, compareLocales, uhash_compareLong, &errorCode);
if (U_FAILURE(errorCode)) { return false; }
}
LocalPointer<Locale> clone;
int32_t index = uhash_geti(map, &locale);
if (index != 0) {
// Duplicate: Remove the old item and append it anew.
LocaleAndWeight &lw = list->array[index - 1];
clone.adoptInstead(lw.locale);
lw.locale = nullptr;
lw.weight = 0;
++numRemoved;
}
if (weight <= 0) { // do not add q=0
if (index != 0) {
// Not strictly necessary but cleaner.
uhash_removei(map, &locale);
}
return true;
}
if (clone.isNull()) {
clone.adoptInstead(locale.clone());
if (clone.isNull() || (clone->isBogus() && !locale.isBogus())) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return false;
}
}
if (listLength == list->array.getCapacity()) {
int32_t newCapacity = listLength < 50 ? 100 : 4 * listLength;
if (list->array.resize(newCapacity, listLength) == nullptr) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return false;
}
}
uhash_puti(map, clone.getAlias(), listLength + 1, &errorCode);
if (U_FAILURE(errorCode)) { return false; }
LocaleAndWeight &lw = list->array[listLength];
lw.locale = clone.orphan();
lw.weight = weight;
lw.index = listLength++;
if (weight < WEIGHT_ONE) { hasWeights = true; }
U_ASSERT(uhash_count(map) == getLength());
return true;
}
void LocalePriorityList::sort(UErrorCode &errorCode) {
// Sort by descending weights if there is a mix of weights.
// The comparator forces a stable sort via the item index.
if (U_FAILURE(errorCode) || getLength() <= 1 || !hasWeights) { return; }
uprv_sortArray(list->array.getAlias(), listLength, sizeof(LocaleAndWeight),
compareLocaleAndWeight, nullptr, FALSE, &errorCode);
}
U_NAMESPACE_END
+115
View File
@@ -0,0 +1,115 @@
// © 2019 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
// localeprioritylist.h
// created: 2019jul11 Markus W. Scherer
#ifndef __LOCALEPRIORITYLIST_H__
#define __LOCALEPRIORITYLIST_H__
#include "unicode/utypes.h"
#include "unicode/locid.h"
#include "unicode/stringpiece.h"
#include "unicode/uobject.h"
struct UHashtable;
U_NAMESPACE_BEGIN
struct LocaleAndWeightArray;
/**
* Parses a list of locales from an accept-language string.
* We are a bit more lenient than the spec:
* We accept extra whitespace in more places, empty range fields,
* and any number of qvalue fraction digits.
*
* https://tools.ietf.org/html/rfc2616#section-14.4
* 14.4 Accept-Language
*
* Accept-Language = "Accept-Language" ":"
* 1#( language-range [ ";" "q" "=" qvalue ] )
* language-range = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" )
*
* Each language-range MAY be given an associated quality value which
* represents an estimate of the user's preference for the languages
* specified by that range. The quality value defaults to "q=1". For
* example,
*
* Accept-Language: da, en-gb;q=0.8, en;q=0.7
*
* https://tools.ietf.org/html/rfc2616#section-3.9
* 3.9 Quality Values
*
* HTTP content negotiation (section 12) uses short "floating point"
* numbers to indicate the relative importance ("weight") of various
* negotiable parameters. A weight is normalized to a real number in
* the range 0 through 1, where 0 is the minimum and 1 the maximum
* value. If a parameter has a quality value of 0, then content with
* this parameter is `not acceptable' for the client. HTTP/1.1
* applications MUST NOT generate more than three digits after the
* decimal point. User configuration of these values SHOULD also be
* limited in this fashion.
*
* qvalue = ( "0" [ "." 0*3DIGIT ] )
* | ( "1" [ "." 0*3("0") ] )
*/
class U_COMMON_API LocalePriorityList : public UMemory {
public:
class Iterator : public Locale::Iterator {
public:
UBool hasNext() const override { return count < length; }
const Locale &next() override {
for(;;) {
const Locale *locale = list.localeAt(index++);
if (locale != nullptr) {
++count;
return *locale;
}
}
}
private:
friend class LocalePriorityList;
Iterator(const LocalePriorityList &list) : list(list), length(list.getLength()) {}
const LocalePriorityList &list;
int32_t index = 0;
int32_t count = 0;
const int32_t length;
};
LocalePriorityList(StringPiece s, UErrorCode &errorCode);
~LocalePriorityList();
int32_t getLength() const { return listLength - numRemoved; }
int32_t getLengthIncludingRemoved() const { return listLength; }
Iterator iterator() const { return Iterator(*this); }
const Locale *localeAt(int32_t i) const;
Locale *orphanLocaleAt(int32_t i);
private:
LocalePriorityList(const LocalePriorityList &) = delete;
LocalePriorityList &operator=(const LocalePriorityList &) = delete;
bool add(const Locale &locale, int32_t weight, UErrorCode &errorCode);
void sort(UErrorCode &errorCode);
LocaleAndWeightArray *list = nullptr;
int32_t listLength = 0;
int32_t numRemoved = 0;
bool hasWeights = false; // other than 1.0
UHashtable *map = nullptr;
};
U_NAMESPACE_END
#endif // __LOCALEPRIORITYLIST_H__
+151 -59
View File
@@ -19,11 +19,13 @@
* that then do not depend on resource bundle code and res_index bundles.
*/
#include "unicode/errorcode.h"
#include "unicode/utypes.h"
#include "unicode/locid.h"
#include "unicode/uloc.h"
#include "unicode/ures.h"
#include "cmemory.h"
#include "cstring.h"
#include "ucln_cmn.h"
#include "uassert.h"
#include "umutex.h"
@@ -95,84 +97,174 @@ U_NAMESPACE_USE
/* ### Constants **************************************************/
/* These strings describe the resources we attempt to load from
the locale ResourceBundle data file.*/
static const char _kIndexLocaleName[] = "res_index";
static const char _kIndexTag[] = "InstalledLocales";
namespace {
static char** _installedLocales = NULL;
static int32_t _installedLocalesCount = 0;
static icu::UInitOnce _installedLocalesInitOnce;
// Enough capacity for the two lists in the res_index.res file
const char** gAvailableLocaleNames[2] = {};
int32_t gAvailableLocaleCounts[2] = {};
icu::UInitOnce ginstalledLocalesInitOnce = U_INITONCE_INITIALIZER;
class AvailableLocalesSink : public ResourceSink {
public:
void put(const char *key, ResourceValue &value, UBool /*noFallback*/, UErrorCode &status) U_OVERRIDE {
ResourceTable resIndexTable = value.getTable(status);
if (U_FAILURE(status)) {
return;
}
for (int32_t i = 0; resIndexTable.getKeyAndValue(i, key, value); ++i) {
ULocAvailableType type;
if (uprv_strcmp(key, "InstalledLocales") == 0) {
type = ULOC_AVAILABLE_DEFAULT;
} else if (uprv_strcmp(key, "AliasLocales") == 0) {
type = ULOC_AVAILABLE_ONLY_LEGACY_ALIASES;
} else {
// CLDRVersion, etc.
continue;
}
ResourceTable availableLocalesTable = value.getTable(status);
if (U_FAILURE(status)) {
return;
}
gAvailableLocaleCounts[type] = availableLocalesTable.getSize();
gAvailableLocaleNames[type] = static_cast<const char**>(
uprv_malloc(gAvailableLocaleCounts[type] * sizeof(const char*)));
if (gAvailableLocaleNames[type] == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
for (int32_t j = 0; availableLocalesTable.getKeyAndValue(j, key, value); ++j) {
gAvailableLocaleNames[type][j] = key;
}
}
}
};
class AvailableLocalesStringEnumeration : public StringEnumeration {
public:
AvailableLocalesStringEnumeration(ULocAvailableType type) : fType(type) {
}
const char* next(int32_t *resultLength, UErrorCode&) override {
ULocAvailableType actualType = fType;
int32_t actualIndex = fIndex++;
// If the "combined" list was requested, resolve that now
if (fType == ULOC_AVAILABLE_WITH_LEGACY_ALIASES) {
int32_t defaultLocalesCount = gAvailableLocaleCounts[ULOC_AVAILABLE_DEFAULT];
if (actualIndex < defaultLocalesCount) {
actualType = ULOC_AVAILABLE_DEFAULT;
} else {
actualIndex -= defaultLocalesCount;
actualType = ULOC_AVAILABLE_ONLY_LEGACY_ALIASES;
}
}
// Return the requested string
int32_t count = gAvailableLocaleCounts[actualType];
const char* result;
if (actualIndex < count) {
result = gAvailableLocaleNames[actualType][actualIndex];
if (resultLength != nullptr) {
*resultLength = static_cast<int32_t>(uprv_strlen(result));
}
} else {
result = nullptr;
if (resultLength != nullptr) {
*resultLength = 0;
}
}
return result;
}
void reset(UErrorCode&) override {
fIndex = 0;
}
int32_t count(UErrorCode&) const override {
if (fType == ULOC_AVAILABLE_WITH_LEGACY_ALIASES) {
return gAvailableLocaleCounts[ULOC_AVAILABLE_DEFAULT]
+ gAvailableLocaleCounts[ULOC_AVAILABLE_ONLY_LEGACY_ALIASES];
} else {
return gAvailableLocaleCounts[fType];
}
}
private:
ULocAvailableType fType;
int32_t fIndex = 0;
};
/* ### Get available **************************************************/
static UBool U_CALLCONV uloc_cleanup(void) {
char ** temp;
if (_installedLocales) {
temp = _installedLocales;
_installedLocales = NULL;
_installedLocalesCount = 0;
_installedLocalesInitOnce.reset();
uprv_free(temp);
for (int32_t i = 0; i < UPRV_LENGTHOF(gAvailableLocaleNames); i++) {
uprv_free(gAvailableLocaleNames[i]);
gAvailableLocaleNames[i] = nullptr;
gAvailableLocaleCounts[i] = 0;
}
ginstalledLocalesInitOnce.reset();
return TRUE;
}
// Load Installed Locales. This function will be called exactly once
// via the initOnce mechanism.
static void U_CALLCONV loadInstalledLocales() {
UErrorCode status = U_ZERO_ERROR;
int32_t i = 0;
int32_t localeCount;
static void U_CALLCONV loadInstalledLocales(UErrorCode& status) {
ucln_common_registerCleanup(UCLN_COMMON_ULOC, uloc_cleanup);
U_ASSERT(_installedLocales == NULL);
U_ASSERT(_installedLocalesCount == 0);
_installedLocalesCount = 0;
icu::LocalUResourceBundlePointer indexLocale(ures_openDirect(NULL, _kIndexLocaleName, &status));
icu::StackUResourceBundle installed;
ures_getByKey(indexLocale.getAlias(), _kIndexTag, installed.getAlias(), &status);
if(U_SUCCESS(status)) {
localeCount = ures_getSize(installed.getAlias());
_installedLocales = (char **) uprv_malloc(sizeof(char*) * (localeCount+1));
if (_installedLocales != NULL) {
ures_resetIterator(installed.getAlias());
while(ures_hasNext(installed.getAlias())) {
ures_getNextString(installed.getAlias(), NULL, (const char **)&_installedLocales[i++], &status);
}
_installedLocales[i] = NULL;
_installedLocalesCount = localeCount;
ucln_common_registerCleanup(UCLN_COMMON_ULOC, uloc_cleanup);
}
}
icu::LocalUResourceBundlePointer rb(ures_openDirect(NULL, "res_index", &status));
AvailableLocalesSink sink;
ures_getAllItemsWithFallback(rb.getAlias(), "", sink, status);
}
static void _load_installedLocales()
{
umtx_initOnce(_installedLocalesInitOnce, &loadInstalledLocales);
void _load_installedLocales(UErrorCode& status) {
umtx_initOnce(ginstalledLocalesInitOnce, &loadInstalledLocales, status);
}
} // namespace
U_CAPI const char* U_EXPORT2
uloc_getAvailable(int32_t offset)
{
_load_installedLocales();
if (offset > _installedLocalesCount)
return NULL;
return _installedLocales[offset];
uloc_getAvailable(int32_t offset) {
icu::ErrorCode status;
_load_installedLocales(status);
if (status.isFailure()) {
return nullptr;
}
if (offset > gAvailableLocaleCounts[0]) {
// *status = U_ILLEGAL_ARGUMENT_ERROR;
return nullptr;
}
return gAvailableLocaleNames[0][offset];
}
U_CAPI int32_t U_EXPORT2
uloc_countAvailable()
{
_load_installedLocales();
return _installedLocalesCount;
uloc_countAvailable() {
icu::ErrorCode status;
_load_installedLocales(status);
if (status.isFailure()) {
return 0;
}
return gAvailableLocaleCounts[0];
}
U_CAPI UEnumeration* U_EXPORT2
uloc_openAvailableByType(ULocAvailableType type, UErrorCode* status) {
if (U_FAILURE(*status)) {
return nullptr;
}
if (type < 0 || type >= ULOC_AVAILABLE_COUNT) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return nullptr;
}
_load_installedLocales(*status);
if (U_FAILURE(*status)) {
return nullptr;
}
LocalPointer<AvailableLocalesStringEnumeration> result(
new AvailableLocalesStringEnumeration(type), *status);
if (U_FAILURE(*status)) {
return nullptr;
}
return uenum_openFromStringEnumeration(result.orphan(), status);
}
+1 -1
View File
@@ -22,7 +22,7 @@
* `actualLocale' of size ULOC_FULLNAME_CAPACITY
*/
#define U_LOCALE_BASED(varname, objname) \
LocaleBased varname((objname).validLocale, (objname).actualLocale);
LocaleBased varname((objname).validLocale, (objname).actualLocale)
U_NAMESPACE_BEGIN
+364
View File
@@ -0,0 +1,364 @@
// © 2019 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
// locdistance.cpp
// created: 2019may08 Markus W. Scherer
#include "unicode/utypes.h"
#include "unicode/bytestrie.h"
#include "unicode/localematcher.h"
#include "unicode/locid.h"
#include "unicode/uobject.h"
#include "unicode/ures.h"
#include "cstring.h"
#include "locdistance.h"
#include "loclikelysubtags.h"
#include "uassert.h"
#include "ucln_cmn.h"
#include "uinvchar.h"
#include "umutex.h"
U_NAMESPACE_BEGIN
namespace {
/**
* Bit flag used on the last character of a subtag in the trie.
* Must be set consistently by the builder and the lookup code.
*/
constexpr int32_t END_OF_SUBTAG = 0x80;
/** Distance value bit flag, set by the builder. */
constexpr int32_t DISTANCE_SKIP_SCRIPT = 0x80;
/** Distance value bit flag, set by trieNext(). */
constexpr int32_t DISTANCE_IS_FINAL = 0x100;
constexpr int32_t DISTANCE_IS_FINAL_OR_SKIP_SCRIPT = DISTANCE_IS_FINAL | DISTANCE_SKIP_SCRIPT;
constexpr int32_t ABOVE_THRESHOLD = 100;
// Indexes into array of distances.
enum {
IX_DEF_LANG_DISTANCE,
IX_DEF_SCRIPT_DISTANCE,
IX_DEF_REGION_DISTANCE,
IX_MIN_REGION_DISTANCE,
IX_LIMIT
};
LocaleDistance *gLocaleDistance = nullptr;
UInitOnce gInitOnce = U_INITONCE_INITIALIZER;
UBool U_CALLCONV cleanup() {
delete gLocaleDistance;
gLocaleDistance = nullptr;
gInitOnce.reset();
return TRUE;
}
} // namespace
void U_CALLCONV LocaleDistance::initLocaleDistance(UErrorCode &errorCode) {
// This function is invoked only via umtx_initOnce().
U_ASSERT(gLocaleDistance == nullptr);
const XLikelySubtags &likely = *XLikelySubtags::getSingleton(errorCode);
if (U_FAILURE(errorCode)) { return; }
const LocaleDistanceData &data = likely.getDistanceData();
if (data.distanceTrieBytes == nullptr ||
data.regionToPartitions == nullptr || data.partitions == nullptr ||
// ok if no paradigms
data.distances == nullptr) {
errorCode = U_MISSING_RESOURCE_ERROR;
return;
}
gLocaleDistance = new LocaleDistance(data);
if (gLocaleDistance == nullptr) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
ucln_common_registerCleanup(UCLN_COMMON_LOCALE_DISTANCE, cleanup);
}
const LocaleDistance *LocaleDistance::getSingleton(UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) { return nullptr; }
umtx_initOnce(gInitOnce, &LocaleDistance::initLocaleDistance, errorCode);
return gLocaleDistance;
}
LocaleDistance::LocaleDistance(const LocaleDistanceData &data) :
trie(data.distanceTrieBytes),
regionToPartitionsIndex(data.regionToPartitions), partitionArrays(data.partitions),
paradigmLSRs(data.paradigms), paradigmLSRsLength(data.paradigmsLength),
defaultLanguageDistance(data.distances[IX_DEF_LANG_DISTANCE]),
defaultScriptDistance(data.distances[IX_DEF_SCRIPT_DISTANCE]),
defaultRegionDistance(data.distances[IX_DEF_REGION_DISTANCE]),
minRegionDistance(data.distances[IX_MIN_REGION_DISTANCE]) {
// For the default demotion value, use the
// default region distance between unrelated Englishes.
// Thus, unless demotion is turned off,
// 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");
const LSR *p_enGB = &enGB;
defaultDemotionPerDesiredLocale = getBestIndexAndDistance(en, &p_enGB, 1,
50, ULOCMATCH_FAVOR_LANGUAGE) & 0xff;
}
int32_t LocaleDistance::getBestIndexAndDistance(
const LSR &desired,
const LSR **supportedLSRs, int32_t supportedLSRsLength,
int32_t threshold, ULocMatchFavorSubtag favorSubtag) 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.
// Note: The data builder verifies that there are no <*, supported> or <desired, *> rules.
int32_t desLangDistance = trieNext(iter, desired.language, false);
uint64_t desLangState = desLangDistance >= 0 && supportedLSRsLength > 1 ? iter.getState64() : 0;
// Index of the supported LSR with the lowest distance.
int32_t bestIndex = -1;
for (int32_t slIndex = 0; slIndex < supportedLSRsLength; ++slIndex) {
const LSR &supported = *supportedLSRs[slIndex];
bool star = false;
int32_t distance = desLangDistance;
if (distance >= 0) {
U_ASSERT((distance & DISTANCE_IS_FINAL) == 0);
if (slIndex != 0) {
iter.resetToState64(desLangState);
}
distance = trieNext(iter, supported.language, true);
}
// Note: The data builder verifies that there are no rules with "any" (*) language and
// real (non *) script or region subtags.
// This means that if the lookup for either language fails we can use
// the default distances without further lookups.
int32_t flags;
if (distance >= 0) {
flags = distance & DISTANCE_IS_FINAL_OR_SKIP_SCRIPT;
distance &= ~DISTANCE_IS_FINAL_OR_SKIP_SCRIPT;
} else { // <*, *>
if (uprv_strcmp(desired.language, supported.language) == 0) {
distance = 0;
} else {
distance = defaultLanguageDistance;
}
flags = 0;
star = true;
}
U_ASSERT(0 <= distance && distance <= 100);
// 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.
// For example, given a default language distance of 80, we reduce it to 20,
// which is below the default threshold of 50, which is the default script distance.
if (favorSubtag == ULOCMATCH_FAVOR_SCRIPT) {
distance >>= 2;
}
if (distance >= threshold) {
continue;
}
int32_t scriptDistance;
if (star || flags != 0) {
if (uprv_strcmp(desired.script, supported.script) == 0) {
scriptDistance = 0;
} else {
scriptDistance = defaultScriptDistance;
}
} else {
scriptDistance = getDesSuppScriptDistance(iter, iter.getState64(),
desired.script, supported.script);
flags = scriptDistance & DISTANCE_IS_FINAL;
scriptDistance &= ~DISTANCE_IS_FINAL;
}
distance += scriptDistance;
if (distance >= threshold) {
continue;
}
if (uprv_strcmp(desired.region, supported.region) == 0) {
// regionDistance = 0
} else if (star || (flags & DISTANCE_IS_FINAL) != 0) {
distance += defaultRegionDistance;
} else {
int32_t remainingThreshold = threshold - distance;
if (minRegionDistance >= remainingThreshold) {
continue;
}
// From here on we know the regions are not equal.
// Map each region to zero or more partitions. (zero = one non-matching string)
// (Each array of single-character partition strings is encoded as one string.)
// If either side has more than one, then we find the maximum distance.
// This could be optimized by adding some more structure, but probably not worth it.
distance += getRegionPartitionsDistance(
iter, iter.getState64(),
partitionsForRegion(desired),
partitionsForRegion(supported),
remainingThreshold);
}
if (distance < threshold) {
if (distance == 0) {
return slIndex << 8;
}
bestIndex = slIndex;
threshold = distance;
}
}
return bestIndex >= 0 ? (bestIndex << 8) | threshold : 0xffffff00 | ABOVE_THRESHOLD;
}
int32_t LocaleDistance::getDesSuppScriptDistance(
BytesTrie &iter, uint64_t startState, const char *desired, const char *supported) {
// Note: The data builder verifies that there are no <*, supported> or <desired, *> rules.
int32_t distance = trieNext(iter, desired, false);
if (distance >= 0) {
distance = trieNext(iter, supported, true);
}
if (distance < 0) {
UStringTrieResult result = iter.resetToState64(startState).next(u'*'); // <*, *>
U_ASSERT(USTRINGTRIE_HAS_VALUE(result));
if (uprv_strcmp(desired, supported) == 0) {
distance = 0; // same script
} else {
distance = iter.getValue();
U_ASSERT(distance >= 0);
}
if (result == USTRINGTRIE_FINAL_VALUE) {
distance |= DISTANCE_IS_FINAL;
}
}
return distance;
}
int32_t LocaleDistance::getRegionPartitionsDistance(
BytesTrie &iter, uint64_t startState,
const char *desiredPartitions, const char *supportedPartitions, int32_t threshold) {
char desired = *desiredPartitions++;
char supported = *supportedPartitions++;
U_ASSERT(desired != 0 && supported != 0);
// See if we have single desired/supported partitions, from NUL-terminated
// partition strings without explicit length.
bool suppLengthGt1 = *supportedPartitions != 0; // gt1: more than 1 character
// equivalent to: if (desLength == 1 && suppLength == 1)
if (*desiredPartitions == 0 && !suppLengthGt1) {
// Fastpath for single desired/supported partitions.
UStringTrieResult result = iter.next(uprv_invCharToAscii(desired) | END_OF_SUBTAG);
if (USTRINGTRIE_HAS_NEXT(result)) {
result = iter.next(uprv_invCharToAscii(supported) | END_OF_SUBTAG);
if (USTRINGTRIE_HAS_VALUE(result)) {
return iter.getValue();
}
}
return getFallbackRegionDistance(iter, startState);
}
const char *supportedStart = supportedPartitions - 1; // for restart of inner loop
int32_t regionDistance = 0;
// Fall back to * only once, not for each pair of partition strings.
bool star = false;
for (;;) {
// Look up each desired-partition string only once,
// not for each (desired, supported) pair.
UStringTrieResult result = iter.next(uprv_invCharToAscii(desired) | END_OF_SUBTAG);
if (USTRINGTRIE_HAS_NEXT(result)) {
uint64_t desState = suppLengthGt1 ? iter.getState64() : 0;
for (;;) {
result = iter.next(uprv_invCharToAscii(supported) | END_OF_SUBTAG);
int32_t d;
if (USTRINGTRIE_HAS_VALUE(result)) {
d = iter.getValue();
} else if (star) {
d = 0;
} else {
d = getFallbackRegionDistance(iter, startState);
star = true;
}
if (d >= threshold) {
return d;
} else if (regionDistance < d) {
regionDistance = d;
}
if ((supported = *supportedPartitions++) != 0) {
iter.resetToState64(desState);
} else {
break;
}
}
} else if (!star) {
int32_t d = getFallbackRegionDistance(iter, startState);
if (d >= threshold) {
return d;
} else if (regionDistance < d) {
regionDistance = d;
}
star = true;
}
if ((desired = *desiredPartitions++) != 0) {
iter.resetToState64(startState);
supportedPartitions = supportedStart;
supported = *supportedPartitions++;
} else {
break;
}
}
return regionDistance;
}
int32_t LocaleDistance::getFallbackRegionDistance(BytesTrie &iter, uint64_t startState) {
#if U_DEBUG
UStringTrieResult result =
#endif
iter.resetToState64(startState).next(u'*'); // <*, *>
U_ASSERT(USTRINGTRIE_HAS_VALUE(result));
int32_t distance = iter.getValue();
U_ASSERT(distance >= 0);
return distance;
}
int32_t LocaleDistance::trieNext(BytesTrie &iter, const char *s, bool wantValue) {
uint8_t c;
if ((c = *s) == 0) {
return -1; // no empty subtags in the distance data
}
for (;;) {
c = uprv_invCharToAscii(c);
// EBCDIC: If *s is not an invariant character,
// then c is now 0 and will simply not match anything, which is harmless.
uint8_t next = *++s;
if (next != 0) {
if (!USTRINGTRIE_HAS_NEXT(iter.next(c))) {
return -1;
}
} else {
// last character of this subtag
UStringTrieResult result = iter.next(c | END_OF_SUBTAG);
if (wantValue) {
if (USTRINGTRIE_HAS_VALUE(result)) {
int32_t value = iter.getValue();
if (result == USTRINGTRIE_FINAL_VALUE) {
value |= DISTANCE_IS_FINAL;
}
return value;
}
} else {
if (USTRINGTRIE_HAS_NEXT(result)) {
return 0;
}
}
return -1;
}
c = next;
}
}
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.
U_ASSERT(paradigmLSRsLength <= 15);
for (int32_t i = 0; i < paradigmLSRsLength; ++i) {
if (lsr == paradigmLSRs[i]) { return true; }
}
return false;
}
U_NAMESPACE_END
+109
View File
@@ -0,0 +1,109 @@
// © 2019 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
// locdistance.h
// created: 2019may08 Markus W. Scherer
#ifndef __LOCDISTANCE_H__
#define __LOCDISTANCE_H__
#include "unicode/utypes.h"
#include "unicode/bytestrie.h"
#include "unicode/localematcher.h"
#include "unicode/locid.h"
#include "unicode/uobject.h"
#include "lsr.h"
U_NAMESPACE_BEGIN
struct LocaleDistanceData;
/**
* Offline-built data for LocaleMatcher.
* Mostly but not only the data for mapping locales to their maximized forms.
*/
class LocaleDistance final : public UMemory {
public:
static const LocaleDistance *getSingleton(UErrorCode &errorCode);
/**
* 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
* (negative if none has a distance below the threshold),
* and its distance (0..ABOVE_THRESHOLD) in bits 7..0.
*/
int32_t getBestIndexAndDistance(const LSR &desired,
const LSR **supportedLSRs, int32_t supportedLSRsLength,
int32_t threshold, ULocMatchFavorSubtag favorSubtag) const;
int32_t getParadigmLSRsLength() const { return paradigmLSRsLength; }
UBool isParadigmLSR(const LSR &lsr) const;
int32_t getDefaultScriptDistance() const {
return defaultScriptDistance;
}
int32_t getDefaultDemotionPerDesiredLocale() const {
return defaultDemotionPerDesiredLocale;
}
private:
LocaleDistance(const LocaleDistanceData &data);
LocaleDistance(const LocaleDistance &other) = delete;
LocaleDistance &operator=(const LocaleDistance &other) = delete;
static void initLocaleDistance(UErrorCode &errorCode);
static int32_t getDesSuppScriptDistance(BytesTrie &iter, uint64_t startState,
const char *desired, const char *supported);
static int32_t getRegionPartitionsDistance(
BytesTrie &iter, uint64_t startState,
const char *desiredPartitions, const char *supportedPartitions,
int32_t threshold);
static int32_t getFallbackRegionDistance(BytesTrie &iter, uint64_t startState);
static int32_t trieNext(BytesTrie &iter, const char *s, bool wantValue);
const char *partitionsForRegion(const LSR &lsr) const {
// ill-formed region -> one non-matching string
int32_t pIndex = regionToPartitionsIndex[lsr.regionIndex];
return partitionArrays[pIndex];
}
int32_t getDefaultRegionDistance() const {
return defaultRegionDistance;
}
// 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.
// One '*' is used for a (desired, supported) pair of "und", "Zzzz"/"", or "ZZ"/"".
BytesTrie trie;
/**
* Maps each region to zero or more single-character partitions.
*/
const uint8_t *regionToPartitionsIndex;
const char **partitionArrays;
/**
* Used to get the paradigm region for a cluster, if there is one.
*/
const LSR *paradigmLSRs;
int32_t paradigmLSRsLength;
int32_t defaultLanguageDistance;
int32_t defaultScriptDistance;
int32_t defaultRegionDistance;
int32_t minRegionDistance;
int32_t defaultDemotionPerDesiredLocale;
};
U_NAMESPACE_END
#endif // __LOCDISTANCE_H__
+77 -23
View File
@@ -291,6 +291,7 @@ class LocaleDisplayNamesImpl : public LocaleDisplayNames {
UnicodeString formatCloseParen;
UnicodeString formatReplaceCloseParen;
UDisplayContext nameLength;
UDisplayContext substitute;
// Constants for capitalization context usage types.
enum CapContextUsage {
@@ -337,7 +338,7 @@ public:
UnicodeString& result) const;
private:
UnicodeString& localeIdName(const char* localeId,
UnicodeString& result) const;
UnicodeString& result, bool substitute) const;
UnicodeString& appendWithSep(UnicodeString& buffer, const UnicodeString& src) const;
UnicodeString& adjustForUsageAndContext(CapContextUsage usage, UnicodeString& result) const;
UnicodeString& scriptDisplayName(const char* script, UnicodeString& result, UBool skipAdjust) const;
@@ -359,6 +360,7 @@ LocaleDisplayNamesImpl::LocaleDisplayNamesImpl(const Locale& locale,
, capitalizationContext(UDISPCTX_CAPITALIZATION_NONE)
, capitalizationBrkIter(NULL)
, nameLength(UDISPCTX_LENGTH_FULL)
, substitute(UDISPCTX_SUBSTITUTE)
{
initialize();
}
@@ -371,6 +373,7 @@ LocaleDisplayNamesImpl::LocaleDisplayNamesImpl(const Locale& locale,
, capitalizationContext(UDISPCTX_CAPITALIZATION_NONE)
, capitalizationBrkIter(NULL)
, nameLength(UDISPCTX_LENGTH_FULL)
, substitute(UDISPCTX_SUBSTITUTE)
{
while (length-- > 0) {
UDisplayContext value = *contexts++;
@@ -385,6 +388,9 @@ LocaleDisplayNamesImpl::LocaleDisplayNamesImpl(const Locale& locale,
case UDISPCTX_TYPE_DISPLAY_LENGTH:
nameLength = value;
break;
case UDISPCTX_TYPE_SUBSTITUTE_HANDLING:
substitute = value;
break;
default:
break;
}
@@ -535,6 +541,8 @@ LocaleDisplayNamesImpl::getContext(UDisplayContextType type) const {
return capitalizationContext;
case UDISPCTX_TYPE_DISPLAY_LENGTH:
return nameLength;
case UDISPCTX_TYPE_SUBSTITUTE_HANDLING:
return substitute;
default:
break;
}
@@ -549,7 +557,7 @@ LocaleDisplayNamesImpl::adjustForUsageAndContext(CapContextUsage usage,
if ( result.length() > 0 && u_islower(result.char32At(0)) && capitalizationBrkIter!= NULL &&
( capitalizationContext==UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE || fCapitalization[usage] ) ) {
// note fCapitalization[usage] won't be set unless capitalizationContext is UI_LIST_OR_MENU or STANDALONE
static UMutex capitalizationBrkIterLock = U_MUTEX_INITIALIZER;
static UMutex capitalizationBrkIterLock;
Mutex lock(&capitalizationBrkIterLock);
result.toTitle(capitalizationBrkIter, locale, U_TITLECASE_NO_LOWERCASE | U_TITLECASE_NO_BREAK_ADJUSTMENT);
}
@@ -583,7 +591,7 @@ LocaleDisplayNamesImpl::localeDisplayName(const Locale& loc,
do { // loop construct is so we can break early out of search
if (hasScript && hasCountry) {
ncat(buffer, ULOC_FULLNAME_CAPACITY, lang, "_", script, "_", country, (char *)0);
localeIdName(buffer, resultName);
localeIdName(buffer, resultName, false);
if (!resultName.isBogus()) {
hasScript = FALSE;
hasCountry = FALSE;
@@ -592,7 +600,7 @@ LocaleDisplayNamesImpl::localeDisplayName(const Locale& loc,
}
if (hasScript) {
ncat(buffer, ULOC_FULLNAME_CAPACITY, lang, "_", script, (char *)0);
localeIdName(buffer, resultName);
localeIdName(buffer, resultName, false);
if (!resultName.isBogus()) {
hasScript = FALSE;
break;
@@ -600,7 +608,7 @@ LocaleDisplayNamesImpl::localeDisplayName(const Locale& loc,
}
if (hasCountry) {
ncat(buffer, ULOC_FULLNAME_CAPACITY, lang, "_", country, (char*)0);
localeIdName(buffer, resultName);
localeIdName(buffer, resultName, false);
if (!resultName.isBogus()) {
hasCountry = FALSE;
break;
@@ -609,7 +617,11 @@ LocaleDisplayNamesImpl::localeDisplayName(const Locale& loc,
} while (FALSE);
}
if (resultName.isBogus() || resultName.isEmpty()) {
localeIdName(lang, resultName);
localeIdName(lang, resultName, substitute == UDISPCTX_SUBSTITUTE);
if (resultName.isBogus()) {
result.setToBogus();
return result;
}
}
UnicodeString resultRemainder;
@@ -617,13 +629,28 @@ LocaleDisplayNamesImpl::localeDisplayName(const Locale& loc,
UErrorCode status = U_ZERO_ERROR;
if (hasScript) {
resultRemainder.append(scriptDisplayName(script, temp, TRUE));
UnicodeString script_str = scriptDisplayName(script, temp, TRUE);
if (script_str.isBogus()) {
result.setToBogus();
return result;
}
resultRemainder.append(script_str);
}
if (hasCountry) {
appendWithSep(resultRemainder, regionDisplayName(country, temp, TRUE));
UnicodeString region_str = regionDisplayName(country, temp, TRUE);
if (region_str.isBogus()) {
result.setToBogus();
return result;
}
appendWithSep(resultRemainder, region_str);
}
if (hasVariant) {
appendWithSep(resultRemainder, variantDisplayName(variant, temp, TRUE));
UnicodeString variant_str = variantDisplayName(variant, temp, TRUE);
if (variant_str.isBogus()) {
result.setToBogus();
return result;
}
appendWithSep(resultRemainder, variant_str);
}
resultRemainder.findAndReplace(formatOpenParen, formatReplaceOpenParen);
resultRemainder.findAndReplace(formatCloseParen, formatReplaceCloseParen);
@@ -689,14 +716,18 @@ LocaleDisplayNamesImpl::localeDisplayName(const char* localeId,
// private
UnicodeString&
LocaleDisplayNamesImpl::localeIdName(const char* localeId,
UnicodeString& result) const {
UnicodeString& result, bool substitute) const {
if (nameLength == UDISPCTX_LENGTH_SHORT) {
langData.getNoFallback("Languages%short", localeId, result);
if (!result.isBogus()) {
return result;
}
}
return langData.getNoFallback("Languages", localeId, result);
if (substitute) {
return langData.get("Languages", localeId, result);
} else {
return langData.getNoFallback("Languages", localeId, result);
}
}
UnicodeString&
@@ -706,12 +737,16 @@ LocaleDisplayNamesImpl::languageDisplayName(const char* lang,
return result = UnicodeString(lang, -1, US_INV);
}
if (nameLength == UDISPCTX_LENGTH_SHORT) {
langData.get("Languages%short", lang, result);
langData.getNoFallback("Languages%short", lang, result);
if (!result.isBogus()) {
return adjustForUsageAndContext(kCapContextUsageLanguage, result);
}
}
langData.get("Languages", lang, result);
if (substitute == UDISPCTX_SUBSTITUTE) {
langData.get("Languages", lang, result);
} else {
langData.getNoFallback("Languages", lang, result);
}
return adjustForUsageAndContext(kCapContextUsageLanguage, result);
}
@@ -720,12 +755,16 @@ LocaleDisplayNamesImpl::scriptDisplayName(const char* script,
UnicodeString& result,
UBool skipAdjust) const {
if (nameLength == UDISPCTX_LENGTH_SHORT) {
langData.get("Scripts%short", script, result);
langData.getNoFallback("Scripts%short", script, result);
if (!result.isBogus()) {
return skipAdjust? result: adjustForUsageAndContext(kCapContextUsageScript, result);
}
}
langData.get("Scripts", script, result);
if (substitute == UDISPCTX_SUBSTITUTE) {
langData.get("Scripts", script, result);
} else {
langData.getNoFallback("Scripts", script, result);
}
return skipAdjust? result: adjustForUsageAndContext(kCapContextUsageScript, result);
}
@@ -746,12 +785,16 @@ LocaleDisplayNamesImpl::regionDisplayName(const char* region,
UnicodeString& result,
UBool skipAdjust) const {
if (nameLength == UDISPCTX_LENGTH_SHORT) {
regionData.get("Countries%short", region, result);
regionData.getNoFallback("Countries%short", region, result);
if (!result.isBogus()) {
return skipAdjust? result: adjustForUsageAndContext(kCapContextUsageTerritory, result);
}
}
regionData.get("Countries", region, result);
if (substitute == UDISPCTX_SUBSTITUTE) {
regionData.get("Countries", region, result);
} else {
regionData.getNoFallback("Countries", region, result);
}
return skipAdjust? result: adjustForUsageAndContext(kCapContextUsageTerritory, result);
}
@@ -767,7 +810,11 @@ LocaleDisplayNamesImpl::variantDisplayName(const char* variant,
UnicodeString& result,
UBool skipAdjust) const {
// don't have a resource for short variant names
langData.get("Variants", variant, result);
if (substitute == UDISPCTX_SUBSTITUTE) {
langData.get("Variants", variant, result);
} else {
langData.getNoFallback("Variants", variant, result);
}
return skipAdjust? result: adjustForUsageAndContext(kCapContextUsageVariant, result);
}
@@ -782,7 +829,11 @@ LocaleDisplayNamesImpl::keyDisplayName(const char* key,
UnicodeString& result,
UBool skipAdjust) const {
// don't have a resource for short key names
langData.get("Keys", key, result);
if (substitute == UDISPCTX_SUBSTITUTE) {
langData.get("Keys", key, result);
} else {
langData.getNoFallback("Keys", key, result);
}
return skipAdjust? result: adjustForUsageAndContext(kCapContextUsageKey, result);
}
@@ -802,9 +853,8 @@ LocaleDisplayNamesImpl::keyValueDisplayName(const char* key,
UErrorCode sts = U_ZERO_ERROR;
UnicodeString ustrValue(value, -1, US_INV);
int32_t len;
UBool isChoice = FALSE;
const UChar *currencyName = ucurr_getName(ustrValue.getTerminatedBuffer(),
locale.getBaseName(), UCURR_LONG_NAME, &isChoice, &len, &sts);
locale.getBaseName(), UCURR_LONG_NAME, nullptr /* isChoiceFormat */, &len, &sts);
if (U_FAILURE(sts)) {
// Return the value as is on failure
result = ustrValue;
@@ -815,12 +865,16 @@ LocaleDisplayNamesImpl::keyValueDisplayName(const char* key,
}
if (nameLength == UDISPCTX_LENGTH_SHORT) {
langData.get("Types%short", key, value, result);
langData.getNoFallback("Types%short", key, value, result);
if (!result.isBogus()) {
return skipAdjust? result: adjustForUsageAndContext(kCapContextUsageKeyValue, result);
}
}
langData.get("Types", key, value, result);
if (substitute == UDISPCTX_SUBSTITUTE) {
langData.get("Types", key, value, result);
} else {
langData.getNoFallback("Types", key, value, result);
}
return skipAdjust? result: adjustForUsageAndContext(kCapContextUsageKeyValue, result);
}
+12 -13
View File
@@ -38,19 +38,19 @@
#include "unicode/strenum.h"
#include "unicode/stringpiece.h"
#include "unicode/uloc.h"
#include "putilimp.h"
#include "mutex.h"
#include "umutex.h"
#include "uassert.h"
#include "bytesinkutil.h"
#include "charstr.h"
#include "cmemory.h"
#include "cstring.h"
#include "mutex.h"
#include "putilimp.h"
#include "uassert.h"
#include "ucln_cmn.h"
#include "uhash.h"
#include "ulocimp.h"
#include "ucln_cmn.h"
#include "umutex.h"
#include "ustr_imp.h"
#include "charstr.h"
#include "bytesinkutil.h"
U_CDECL_BEGIN
static UBool U_CALLCONV locale_cleanup(void);
@@ -62,10 +62,7 @@ static Locale *gLocaleCache = NULL;
static UInitOnce gLocaleCacheInitOnce = U_INITONCE_INITIALIZER;
// gDefaultLocaleMutex protects all access to gDefaultLocalesHashT and gDefaultLocale.
static UMutex *gDefaultLocaleMutex() {
static UMutex m = U_MUTEX_INITIALIZER;
return &m;
}
static UMutex gDefaultLocaleMutex;
static UHashtable *gDefaultLocalesHashT = NULL;
static Locale *gDefaultLocale = NULL;
@@ -174,7 +171,7 @@ U_NAMESPACE_BEGIN
Locale *locale_set_default_internal(const char *id, UErrorCode& status) {
// Synchronize this entire function.
Mutex lock(gDefaultLocaleMutex());
Mutex lock(&gDefaultLocaleMutex);
UBool canonicalize = FALSE;
@@ -711,7 +708,7 @@ const Locale& U_EXPORT2
Locale::getDefault()
{
{
Mutex lock(gDefaultLocaleMutex());
Mutex lock(&gDefaultLocaleMutex);
if (gDefaultLocale != NULL) {
return *gDefaultLocale;
}
@@ -1399,5 +1396,7 @@ Locale::getBaseName() const {
return baseName;
}
Locale::Iterator::~Iterator() = default;
//eof
U_NAMESPACE_END
+15 -15
View File
@@ -807,24 +807,24 @@ error:
return FALSE;
}
#define CHECK_TRAILING_VARIANT_SIZE(trailing, trailingLength) \
{ int32_t count = 0; \
int32_t i; \
for (i = 0; i < trailingLength; i++) { \
if (trailing[i] == '-' || trailing[i] == '_') { \
count = 0; \
if (count > 8) { \
goto error; \
} \
} else if (trailing[i] == '@') { \
break; \
} else if (count > 8) { \
#define CHECK_TRAILING_VARIANT_SIZE(trailing, trailingLength) UPRV_BLOCK_MACRO_BEGIN { \
int32_t count = 0; \
int32_t i; \
for (i = 0; i < trailingLength; i++) { \
if (trailing[i] == '-' || trailing[i] == '_') { \
count = 0; \
if (count > 8) { \
goto error; \
} else { \
count++; \
} \
} else if (trailing[i] == '@') { \
break; \
} else if (count > 8) { \
goto error; \
} else { \
count++; \
} \
}
} \
} UPRV_BLOCK_MACRO_END
static void
_uloc_addLikelySubtags(const char* localeID,
+638
View File
@@ -0,0 +1,638 @@
// © 2019 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
// loclikelysubtags.cpp
// created: 2019may08 Markus W. Scherer
#include <utility>
#include "unicode/utypes.h"
#include "unicode/bytestrie.h"
#include "unicode/localpointer.h"
#include "unicode/locid.h"
#include "unicode/uobject.h"
#include "unicode/ures.h"
#include "charstr.h"
#include "cstring.h"
#include "loclikelysubtags.h"
#include "lsr.h"
#include "uassert.h"
#include "ucln_cmn.h"
#include "uhash.h"
#include "uinvchar.h"
#include "umutex.h"
#include "uresdata.h"
#include "uresimp.h"
U_NAMESPACE_BEGIN
namespace {
constexpr char PSEUDO_ACCENTS_PREFIX = '\''; // -XA, -PSACCENT
constexpr char PSEUDO_BIDI_PREFIX = '+'; // -XB, -PSBIDI
constexpr char PSEUDO_CRACKED_PREFIX = ','; // -XC, -PSCRACK
/**
* Stores NUL-terminated strings with duplicate elimination.
* Checks for unique UTF-16 string pointers and converts to invariant characters.
*/
class UniqueCharStrings {
public:
UniqueCharStrings(UErrorCode &errorCode) : strings(nullptr) {
uhash_init(&map, uhash_hashUChars, uhash_compareUChars, uhash_compareLong, &errorCode);
if (U_FAILURE(errorCode)) { return; }
strings = new CharString();
if (strings == nullptr) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
}
}
~UniqueCharStrings() {
uhash_close(&map);
delete strings;
}
/** Returns/orphans the CharString that contains all strings. */
CharString *orphanCharStrings() {
CharString *result = strings;
strings = nullptr;
return result;
}
/** Adds a string and returns a unique number for it. */
int32_t add(const UnicodeString &s, UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) { return 0; }
if (isFrozen) {
errorCode = U_NO_WRITE_PERMISSION;
return 0;
}
// The string points into the resource bundle.
const char16_t *p = s.getBuffer();
int32_t oldIndex = uhash_geti(&map, p);
if (oldIndex != 0) { // found duplicate
return oldIndex;
}
// Explicit NUL terminator for the previous string.
// The strings object is also terminated with one implicit NUL.
strings->append(0, errorCode);
int32_t newIndex = strings->length();
strings->appendInvariantChars(s, errorCode);
uhash_puti(&map, const_cast<char16_t *>(p), newIndex, &errorCode);
return newIndex;
}
void freeze() { isFrozen = true; }
/**
* Returns a string pointer for its unique number, if this object is frozen.
* Otherwise nullptr.
*/
const char *get(int32_t i) const {
U_ASSERT(isFrozen);
return isFrozen && i > 0 ? strings->data() + i : nullptr;
}
private:
UHashtable map;
CharString *strings;
bool isFrozen = false;
};
} // namespace
LocaleDistanceData::LocaleDistanceData(LocaleDistanceData &&data) :
distanceTrieBytes(data.distanceTrieBytes),
regionToPartitions(data.regionToPartitions),
partitions(data.partitions),
paradigms(data.paradigms), paradigmsLength(data.paradigmsLength),
distances(data.distances) {
data.partitions = nullptr;
data.paradigms = nullptr;
}
LocaleDistanceData::~LocaleDistanceData() {
uprv_free(partitions);
delete[] paradigms;
}
// TODO(ICU-20777): Rename to just LikelySubtagsData.
struct XLikelySubtagsData {
UResourceBundle *langInfoBundle = nullptr;
UniqueCharStrings strings;
CharStringMap languageAliases;
CharStringMap regionAliases;
const uint8_t *trieBytes = nullptr;
LSR *lsrs = nullptr;
int32_t lsrsLength = 0;
LocaleDistanceData distanceData;
XLikelySubtagsData(UErrorCode &errorCode) : strings(errorCode) {}
~XLikelySubtagsData() {
ures_close(langInfoBundle);
delete[] lsrs;
}
void load(UErrorCode &errorCode) {
langInfoBundle = ures_openDirect(nullptr, "langInfo", &errorCode);
if (U_FAILURE(errorCode)) { return; }
StackUResourceBundle stackTempBundle;
ResourceDataValue value;
ures_getValueWithFallback(langInfoBundle, "likely", stackTempBundle.getAlias(),
value, errorCode);
ResourceTable likelyTable = value.getTable(errorCode);
if (U_FAILURE(errorCode)) { return; }
// Read all strings in the resource bundle and convert them to invariant char *.
LocalMemory<int32_t> languageIndexes, regionIndexes, lsrSubtagIndexes;
int32_t languagesLength = 0, regionsLength = 0, lsrSubtagsLength = 0;
if (!readStrings(likelyTable, "languageAliases", value,
languageIndexes, languagesLength, errorCode) ||
!readStrings(likelyTable, "regionAliases", value,
regionIndexes, regionsLength, errorCode) ||
!readStrings(likelyTable, "lsrs", value,
lsrSubtagIndexes,lsrSubtagsLength, errorCode)) {
return;
}
if ((languagesLength & 1) != 0 ||
(regionsLength & 1) != 0 ||
(lsrSubtagsLength % 3) != 0) {
errorCode = U_INVALID_FORMAT_ERROR;
return;
}
if (lsrSubtagsLength == 0) {
errorCode = U_MISSING_RESOURCE_ERROR;
return;
}
if (!likelyTable.findValue("trie", value)) {
errorCode = U_MISSING_RESOURCE_ERROR;
return;
}
int32_t length;
trieBytes = value.getBinary(length, errorCode);
if (U_FAILURE(errorCode)) { return; }
// Also read distance/matcher data if available,
// to open & keep only one resource bundle pointer
// and to use one single UniqueCharStrings.
UErrorCode matchErrorCode = U_ZERO_ERROR;
ures_getValueWithFallback(langInfoBundle, "match", stackTempBundle.getAlias(),
value, matchErrorCode);
LocalMemory<int32_t> partitionIndexes, paradigmSubtagIndexes;
int32_t partitionsLength = 0, paradigmSubtagsLength = 0;
if (U_SUCCESS(matchErrorCode)) {
ResourceTable matchTable = value.getTable(errorCode);
if (U_FAILURE(errorCode)) { return; }
if (matchTable.findValue("trie", value)) {
distanceData.distanceTrieBytes = value.getBinary(length, errorCode);
if (U_FAILURE(errorCode)) { return; }
}
if (matchTable.findValue("regionToPartitions", value)) {
distanceData.regionToPartitions = value.getBinary(length, errorCode);
if (U_FAILURE(errorCode)) { return; }
if (length < LSR::REGION_INDEX_LIMIT) {
errorCode = U_INVALID_FORMAT_ERROR;
return;
}
}
if (!readStrings(matchTable, "partitions", value,
partitionIndexes, partitionsLength, errorCode) ||
!readStrings(matchTable, "paradigms", value,
paradigmSubtagIndexes, paradigmSubtagsLength, errorCode)) {
return;
}
if ((paradigmSubtagsLength % 3) != 0) {
errorCode = U_INVALID_FORMAT_ERROR;
return;
}
if (matchTable.findValue("distances", value)) {
distanceData.distances = value.getIntVector(length, errorCode);
if (U_FAILURE(errorCode)) { return; }
if (length < 4) { // LocaleDistance IX_LIMIT
errorCode = U_INVALID_FORMAT_ERROR;
return;
}
}
} else if (matchErrorCode == U_MISSING_RESOURCE_ERROR) {
// ok for likely subtags
} else { // error other than missing resource
errorCode = matchErrorCode;
return;
}
// Fetch & store invariant-character versions of strings
// only after we have collected and de-duplicated all of them.
strings.freeze();
languageAliases = CharStringMap(languagesLength / 2, errorCode);
for (int32_t i = 0; i < languagesLength; i += 2) {
languageAliases.put(strings.get(languageIndexes[i]),
strings.get(languageIndexes[i + 1]), errorCode);
}
regionAliases = CharStringMap(regionsLength / 2, errorCode);
for (int32_t i = 0; i < regionsLength; i += 2) {
regionAliases.put(strings.get(regionIndexes[i]),
strings.get(regionIndexes[i + 1]), errorCode);
}
if (U_FAILURE(errorCode)) { return; }
lsrsLength = lsrSubtagsLength / 3;
lsrs = new LSR[lsrsLength];
if (lsrs == nullptr) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
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]));
}
if (partitionsLength > 0) {
distanceData.partitions = static_cast<const char **>(
uprv_malloc(partitionsLength * sizeof(const char *)));
if (distanceData.partitions == nullptr) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
for (int32_t i = 0; i < partitionsLength; ++i) {
distanceData.partitions[i] = strings.get(partitionIndexes[i]);
}
}
if (paradigmSubtagsLength > 0) {
distanceData.paradigmsLength = paradigmSubtagsLength / 3;
LSR *paradigms = new LSR[distanceData.paradigmsLength];
if (paradigms == nullptr) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
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]));
}
distanceData.paradigms = paradigms;
}
}
private:
bool readStrings(const ResourceTable &table, const char *key, ResourceValue &value,
LocalMemory<int32_t> &indexes, int32_t &length, UErrorCode &errorCode) {
if (table.findValue(key, value)) {
ResourceArray stringArray = value.getArray(errorCode);
if (U_FAILURE(errorCode)) { return false; }
length = stringArray.getSize();
if (length == 0) { return true; }
int32_t *rawIndexes = indexes.allocateInsteadAndCopy(length);
if (rawIndexes == nullptr) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return false;
}
for (int i = 0; i < length; ++i) {
stringArray.getValue(i, value); // returns TRUE because i < length
rawIndexes[i] = strings.add(value.getUnicodeString(errorCode), errorCode);
if (U_FAILURE(errorCode)) { return false; }
}
}
return true;
}
};
namespace {
XLikelySubtags *gLikelySubtags = nullptr;
UInitOnce gInitOnce = U_INITONCE_INITIALIZER;
UBool U_CALLCONV cleanup() {
delete gLikelySubtags;
gLikelySubtags = nullptr;
gInitOnce.reset();
return TRUE;
}
} // namespace
void U_CALLCONV XLikelySubtags::initLikelySubtags(UErrorCode &errorCode) {
// This function is invoked only via umtx_initOnce().
U_ASSERT(gLikelySubtags == nullptr);
XLikelySubtagsData data(errorCode);
data.load(errorCode);
if (U_FAILURE(errorCode)) { return; }
gLikelySubtags = new XLikelySubtags(data);
if (gLikelySubtags == nullptr) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
ucln_common_registerCleanup(UCLN_COMMON_LIKELY_SUBTAGS, cleanup);
}
const XLikelySubtags *XLikelySubtags::getSingleton(UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) { return nullptr; }
umtx_initOnce(gInitOnce, &XLikelySubtags::initLikelySubtags, errorCode);
return gLikelySubtags;
}
XLikelySubtags::XLikelySubtags(XLikelySubtagsData &data) :
langInfoBundle(data.langInfoBundle),
strings(data.strings.orphanCharStrings()),
languageAliases(std::move(data.languageAliases)),
regionAliases(std::move(data.regionAliases)),
trie(data.trieBytes),
lsrs(data.lsrs),
#if U_DEBUG
lsrsLength(data.lsrsLength),
#endif
distanceData(std::move(data.distanceData)) {
data.langInfoBundle = nullptr;
data.lsrs = nullptr;
// Cache the result of looking up language="und" encoded as "*", and "und-Zzzz" ("**").
UStringTrieResult result = trie.next(u'*');
U_ASSERT(USTRINGTRIE_HAS_NEXT(result));
trieUndState = trie.getState64();
result = trie.next(u'*');
U_ASSERT(USTRINGTRIE_HAS_NEXT(result));
trieUndZzzzState = trie.getState64();
result = trie.next(u'*');
U_ASSERT(USTRINGTRIE_HAS_VALUE(result));
defaultLsrIndex = trie.getValue();
trie.reset();
for (char16_t c = u'a'; c <= u'z'; ++c) {
result = trie.next(c);
if (result == USTRINGTRIE_NO_VALUE) {
trieFirstLetterStates[c - u'a'] = trie.getState64();
}
trie.reset();
}
}
XLikelySubtags::~XLikelySubtags() {
ures_close(langInfoBundle);
delete strings;
delete[] lsrs;
}
LSR XLikelySubtags::makeMaximizedLsrFrom(const Locale &locale, UErrorCode &errorCode) const {
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 makeMaximizedLsr(locale.getLanguage(), locale.getScript(), locale.getCountry(),
locale.getVariant(), errorCode);
}
namespace {
const char *getCanonical(const CharStringMap &aliases, const char *alias) {
const char *canonical = aliases.get(alias);
return canonical == nullptr ? alias : canonical;
}
} // namespace
LSR XLikelySubtags::makeMaximizedLsr(const char *language, const char *script, const char *region,
const char *variant, UErrorCode &errorCode) const {
// Handle pseudolocales like en-XA, ar-XB, fr-PSCRACK.
// They should match only themselves,
// not other locales with what looks like the same language and script subtags.
char c1;
if (region[0] == 'X' && (c1 = region[1]) != 0 && region[2] == 0) {
switch (c1) {
case 'A':
return LSR(PSEUDO_ACCENTS_PREFIX, language, script, region, errorCode);
case 'B':
return LSR(PSEUDO_BIDI_PREFIX, language, script, region, errorCode);
case 'C':
return LSR(PSEUDO_CRACKED_PREFIX, language, script, region, errorCode);
default: // normal locale
break;
}
}
if (variant[0] == 'P' && variant[1] == 'S') {
if (uprv_strcmp(variant, "PSACCENT") == 0) {
return LSR(PSEUDO_ACCENTS_PREFIX, language, script,
*region == 0 ? "XA" : region, errorCode);
} else if (uprv_strcmp(variant, "PSBIDI") == 0) {
return LSR(PSEUDO_BIDI_PREFIX, language, script,
*region == 0 ? "XB" : region, errorCode);
} else if (uprv_strcmp(variant, "PSCRACK") == 0) {
return LSR(PSEUDO_CRACKED_PREFIX, language, script,
*region == 0 ? "XC" : region, errorCode);
}
// else normal locale
}
language = getCanonical(languageAliases, language);
// (We have no script mappings.)
region = getCanonical(regionAliases, region);
return maximize(language, script, region);
}
LSR XLikelySubtags::maximize(const char *language, const char *script, const char *region) const {
if (uprv_strcmp(language, "und") == 0) {
language = "";
}
if (uprv_strcmp(script, "Zzzz") == 0) {
script = "";
}
if (uprv_strcmp(region, "ZZ") == 0) {
region = "";
}
if (*script != 0 && *region != 0 && *language != 0) {
return LSR(language, script, region); // already maximized
}
uint32_t retainOldMask = 0;
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) {
if (*language != 0) {
retainOldMask |= 4;
}
state = iter.getState64();
} else {
retainOldMask |= 4;
iter.resetToState64(trieUndState); // "und" ("*")
state = 0;
}
if (value > 0) {
// Intermediate or final value from just language.
if (value == SKIP_SCRIPT) {
value = 0;
}
if (*script != 0) {
retainOldMask |= 2;
}
} else {
value = trieNext(iter, script, 0);
if (value >= 0) {
if (*script != 0) {
retainOldMask |= 2;
}
state = iter.getState64();
} else {
retainOldMask |= 2;
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.
if (*region != 0) {
retainOldMask |= 1;
}
} else {
value = trieNext(iter, region, 0);
if (value >= 0) {
if (*region != 0) {
retainOldMask |= 1;
}
} else {
retainOldMask |= 1;
if (state == 0) {
value = defaultLsrIndex;
} else {
iter.resetToState64(state);
value = trieNext(iter, "", 0);
U_ASSERT(value > 0);
}
}
}
U_ASSERT(value < lsrsLength);
const LSR &result = lsrs[value];
if (*language == 0) {
language = "und";
}
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);
}
if ((retainOldMask & 4) == 0) {
language = result.language;
}
if ((retainOldMask & 2) == 0) {
script = result.script;
}
if ((retainOldMask & 1) == 0) {
region = result.region;
}
return LSR(language, script, region);
}
int32_t XLikelySubtags::trieNext(BytesTrie &iter, const char *s, int32_t i) {
UStringTrieResult result;
uint8_t c;
if ((c = s[i]) == 0) {
result = iter.next(u'*');
} else {
for (;;) {
c = uprv_invCharToAscii(c);
// EBCDIC: If s[i] is not an invariant character,
// then c is now 0 and will simply not match anything, which is harmless.
uint8_t next = s[++i];
if (next != 0) {
if (!USTRINGTRIE_HAS_NEXT(iter.next(c))) {
return -1;
}
} else {
// last character of this subtag
result = iter.next(c | 0x80);
break;
}
c = next;
}
}
switch (result) {
case USTRINGTRIE_NO_MATCH: return -1;
case USTRINGTRIE_NO_VALUE: return 0;
case USTRINGTRIE_INTERMEDIATE_VALUE:
U_ASSERT(iter.getValue() == SKIP_SCRIPT);
return SKIP_SCRIPT;
case USTRINGTRIE_FINAL_VALUE: return iter.getValue();
default: return -1;
}
}
// 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.
#if 0
LSR XLikelySubtags::minimizeSubtags(const char *languageIn, const char *scriptIn,
const char *regionIn, ULocale.Minimize fieldToFavor,
UErrorCode &errorCode) const {
LSR result = maximize(languageIn, scriptIn, regionIn);
// We could try just a series of checks, like:
// LSR result2 = addLikelySubtags(languageIn, "", "");
// if result.equals(result2) return result2;
// However, we can optimize 2 of the cases:
// (languageIn, "", "")
// (languageIn, "", regionIn)
// value00 = lookup(result.language, "", "")
BytesTrie iter = new BytesTrie(trie);
int value = trieNext(iter, result.language, 0);
U_ASSERT(value >= 0);
if (value == 0) {
value = trieNext(iter, "", 0);
U_ASSERT(value >= 0);
if (value == 0) {
value = trieNext(iter, "", 0);
}
}
U_ASSERT(value > 0);
LSR value00 = lsrs[value];
boolean favorRegionOk = false;
if (result.script.equals(value00.script)) { //script is default
if (result.region.equals(value00.region)) {
return new LSR(result.language, "", "");
} else if (fieldToFavor == ULocale.Minimize.FAVOR_REGION) {
return new LSR(result.language, "", result.region);
} else {
favorRegionOk = true;
}
}
// The last case is not as easy to optimize.
// 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, "");
} else if (favorRegionOk) {
return new LSR(result.language, "", result.region);
}
return result;
}
#endif
U_NAMESPACE_END
+143
View File
@@ -0,0 +1,143 @@
// © 2019 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
// loclikelysubtags.h
// created: 2019may08 Markus W. Scherer
#ifndef __LOCLIKELYSUBTAGS_H__
#define __LOCLIKELYSUBTAGS_H__
#include <utility>
#include "unicode/utypes.h"
#include "unicode/bytestrie.h"
#include "unicode/locid.h"
#include "unicode/uobject.h"
#include "unicode/ures.h"
#include "lsr.h"
#include "uhash.h"
U_NAMESPACE_BEGIN
struct XLikelySubtagsData;
/**
* Map of const char * keys & values.
* Stores pointers as is: Does not own/copy/adopt/release strings.
*/
class CharStringMap final : public UMemory {
public:
/** Constructs an unusable non-map. */
CharStringMap() : map(nullptr) {}
CharStringMap(int32_t size, UErrorCode &errorCode) {
map = uhash_openSize(uhash_hashChars, uhash_compareChars, uhash_compareChars,
size, &errorCode);
}
CharStringMap(CharStringMap &&other) U_NOEXCEPT : map(other.map) {
other.map = nullptr;
}
CharStringMap(const CharStringMap &other) = delete;
~CharStringMap() {
uhash_close(map);
}
CharStringMap &operator=(CharStringMap &&other) U_NOEXCEPT {
map = other.map;
other.map = nullptr;
return *this;
}
CharStringMap &operator=(const CharStringMap &other) = delete;
const char *get(const char *key) const { return static_cast<const char *>(uhash_get(map, key)); }
void put(const char *key, const char *value, UErrorCode &errorCode) {
uhash_put(map, const_cast<char *>(key), const_cast<char *>(value), &errorCode);
}
private:
UHashtable *map;
};
struct LocaleDistanceData {
LocaleDistanceData() = default;
LocaleDistanceData(LocaleDistanceData &&data);
~LocaleDistanceData();
const uint8_t *distanceTrieBytes = nullptr;
const uint8_t *regionToPartitions = nullptr;
const char **partitions = nullptr;
const LSR *paradigms = nullptr;
int32_t paradigmsLength = 0;
const int32_t *distances = nullptr;
private:
LocaleDistanceData &operator=(const LocaleDistanceData &) = delete;
};
// TODO(ICU-20777): Rename to just LikelySubtags.
class XLikelySubtags final : public UMemory {
public:
~XLikelySubtags();
static constexpr int32_t SKIP_SCRIPT = 1;
// VisibleForTesting
static const XLikelySubtags *getSingleton(UErrorCode &errorCode);
// VisibleForTesting
LSR makeMaximizedLsrFrom(const Locale &locale, UErrorCode &errorCode) 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.
#if 0
LSR minimizeSubtags(const char *languageIn, const char *scriptIn, const char *regionIn,
ULocale.Minimize fieldToFavor, UErrorCode &errorCode) const;
#endif
// visible for LocaleDistance
const LocaleDistanceData &getDistanceData() const { return distanceData; }
private:
XLikelySubtags(XLikelySubtagsData &data);
XLikelySubtags(const XLikelySubtags &other) = delete;
XLikelySubtags &operator=(const XLikelySubtags &other) = delete;
static void initLikelySubtags(UErrorCode &errorCode);
LSR makeMaximizedLsr(const char *language, const char *script, const char *region,
const char *variant, UErrorCode &errorCode) const;
/**
* Raw access to addLikelySubtags. Input must be in canonical format, eg "en", not "eng" or "EN".
*/
LSR maximize(const char *language, const char *script, const char *region) const;
static int32_t trieNext(BytesTrie &iter, const char *s, int32_t i);
UResourceBundle *langInfoBundle;
// We could store the strings by value, except that if there were few enough strings,
// moving the contents could copy it to a different array,
// invalidating the pointers stored in the maps.
CharString *strings;
CharStringMap languageAliases;
CharStringMap regionAliases;
// The trie maps each lang+script+region (encoded in ASCII) to an index into lsrs.
// There is also a trie value for each intermediate lang and lang+script.
// '*' is used instead of "und", "Zzzz"/"" and "ZZ"/"".
BytesTrie trie;
uint64_t trieUndState;
uint64_t trieUndZzzzState;
int32_t defaultLsrIndex;
uint64_t trieFirstLetterStates[26];
const LSR *lsrs;
#if U_DEBUG
int32_t lsrsLength;
#endif
// distance/matcher data: see comment in XLikelySubtagsData::load()
LocaleDistanceData distanceData;
};
U_NAMESPACE_END
#endif // __LOCLIKELYSUBTAGS_H__
+101
View File
@@ -0,0 +1,101 @@
// © 2019 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
// lsr.cpp
// created: 2019may08 Markus W. Scherer
#include "unicode/utypes.h"
#include "charstr.h"
#include "cmemory.h"
#include "cstring.h"
#include "lsr.h"
#include "uinvchar.h"
#include "ustr_imp.h"
U_NAMESPACE_BEGIN
LSR::LSR(char prefix, const char *lang, const char *scr, const char *r, UErrorCode &errorCode) :
language(nullptr), script(nullptr), region(r),
regionIndex(indexForRegion(region)) {
if (U_SUCCESS(errorCode)) {
CharString langScript;
langScript.append(prefix, errorCode).append(lang, errorCode).append('\0', errorCode);
int32_t scriptOffset = langScript.length();
langScript.append(prefix, errorCode).append(scr, errorCode);
owned = langScript.cloneData(errorCode);
if (U_SUCCESS(errorCode)) {
language = owned;
script = owned + scriptOffset;
}
}
}
LSR::LSR(LSR &&other) U_NOEXCEPT :
language(other.language), script(other.script), region(other.region), owned(other.owned),
regionIndex(other.regionIndex), hashCode(other.hashCode) {
if (owned != nullptr) {
other.language = other.script = "";
other.owned = nullptr;
other.hashCode = 0;
}
}
void LSR::deleteOwned() {
uprv_free(owned);
}
LSR &LSR::operator=(LSR &&other) U_NOEXCEPT {
this->~LSR();
language = other.language;
script = other.script;
region = other.region;
regionIndex = other.regionIndex;
owned = other.owned;
hashCode = other.hashCode;
if (owned != nullptr) {
other.language = other.script = "";
other.owned = nullptr;
other.hashCode = 0;
}
return *this;
}
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);
}
int32_t LSR::indexForRegion(const char *region) {
int32_t c = region[0];
int32_t a = c - '0';
if (0 <= a && a <= 9) { // digits: "419"
int32_t b = region[1] - '0';
if (b < 0 || 9 < b) { return 0; }
c = region[2] - '0';
if (c < 0 || 9 < c || region[3] != 0) { return 0; }
return (10 * a + b) * 10 + c + 1;
} else { // letters: "DE"
a = uprv_upperOrdinal(c);
if (a < 0 || 25 < a) { return 0; }
int32_t b = uprv_upperOrdinal(region[1]);
if (b < 0 || 25 < b || region[2] != 0) { return 0; }
return 26 * a + b + 1001;
}
return 0;
}
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;
}
return *this;
}
U_NAMESPACE_END
+72
View File
@@ -0,0 +1,72 @@
// © 2019 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
// lsr.h
// created: 2019may08 Markus W. Scherer
#ifndef __LSR_H__
#define __LSR_H__
#include "unicode/utypes.h"
#include "unicode/uobject.h"
#include "cstring.h"
U_NAMESPACE_BEGIN
struct LSR final : public UMemory {
static constexpr int32_t REGION_INDEX_LIMIT = 1001 + 26 * 26;
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;
/** 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) :
language(lang), script(scr), region(r),
regionIndex(indexForRegion(region)) {}
/**
* 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(LSR &&other) U_NOEXCEPT;
LSR(const LSR &other) = delete;
inline ~LSR() {
// Pure inline code for almost all instances.
if (owned != nullptr) {
deleteOwned();
}
}
LSR &operator=(LSR &&other) U_NOEXCEPT;
LSR &operator=(const LSR &other) = delete;
/**
* Returns a positive index (>0) for a well-formed region code.
* Do not rely on a particular region->index mapping; it may change.
* Returns 0 for ill-formed strings.
*/
static int32_t indexForRegion(const char *region);
UBool operator==(const LSR &other) const;
inline UBool operator!=(const LSR &other) const {
return !operator==(other);
}
LSR &setHashCode();
private:
void deleteOwned();
};
U_NAMESPACE_END
#endif // __LSR_H__
+35 -37
View File
@@ -28,50 +28,48 @@
U_NAMESPACE_BEGIN
//----------------------------------------------------------------------------
// Code within that accesses shared static or global data should
// should instantiate a Mutex object while doing so. You should make your own
// private mutex where possible.
// For example:
//
// UMutex myMutex = U_MUTEX_INITIALIZER;
//
// void Function(int arg1, int arg2)
// {
// static Object* foo; // Shared read-write object
// Mutex mutex(&myMutex); // or no args for the global lock
// foo->Method();
// // When 'mutex' goes out of scope and gets destroyed here, the lock is released
// }
//
// Note: Do NOT use the form 'Mutex mutex();' as that merely forward-declares a function
// returning a Mutex. This is a common mistake which silently slips through the
// compiler!!
//
/**
* Mutex is a helper class for convenient locking and unlocking of a UMutex.
*
* Creating a local scope Mutex will lock a UMutex, holding the lock until the Mutex
* goes out of scope.
*
* If no UMutex is specified, the ICU global mutex is implied.
*
* For example:
*
* static UMutex myMutex;
*
* void Function(int arg1, int arg2)
* {
* static Object* foo; // Shared read-write object
* Mutex mutex(&myMutex); // or no args for the global lock
* foo->Method();
* // When 'mutex' goes out of scope and gets destroyed here, the lock is released
* }
*
* Note: Do NOT use the form 'Mutex mutex();' as that merely forward-declares a function
* returning a Mutex. This is a common mistake which silently slips through the
* compiler!!
*/
class U_COMMON_API Mutex : public UMemory {
public:
inline Mutex(UMutex *mutex = NULL);
inline ~Mutex();
Mutex(UMutex *mutex = nullptr) : fMutex(mutex) {
umtx_lock(fMutex);
}
~Mutex() {
umtx_unlock(fMutex);
}
Mutex(const Mutex &other) = delete; // forbid assigning of this class
Mutex &operator=(const Mutex &other) = delete; // forbid copying of this class
void *operator new(size_t s) = delete; // forbid heap allocation. Locals only.
private:
UMutex *fMutex;
Mutex(const Mutex &other); // forbid copying of this class
Mutex &operator=(const Mutex &other); // forbid copying of this class
UMutex *fMutex;
};
inline Mutex::Mutex(UMutex *mutex)
: fMutex(mutex)
{
umtx_lock(fMutex);
}
inline Mutex::~Mutex()
{
umtx_unlock(fMutex);
}
U_NAMESPACE_END
+2 -4
View File
@@ -245,9 +245,7 @@ private:
*/
class U_COMMON_API Normalizer2Impl : public UObject {
public:
Normalizer2Impl() : normTrie(NULL), fCanonIterData(NULL) {
fCanonIterDataInitOnce.reset();
}
Normalizer2Impl() : normTrie(NULL), fCanonIterData(NULL) { }
virtual ~Normalizer2Impl();
void init(const int32_t *inIndexes, const UCPTrie *inTrie,
@@ -723,7 +721,7 @@ private:
const uint16_t *extraData; // mappings and/or compositions for yesYes, yesNo & noNo characters
const uint8_t *smallFCD; // [0x100] one bit per 32 BMP code points, set if any FCD!=0
UInitOnce fCanonIterDataInitOnce;
UInitOnce fCanonIterDataInitOnce = U_INITONCE_INITIALIZER;
CanonIterData *fCanonIterData;
};
+30 -16
View File
@@ -249,7 +249,7 @@ static UDate getUTCtime_real() {
}
static UDate getUTCtime_fake() {
static UMutex fakeClockMutex = U_MUTEX_INTIALIZER;
static UMutex fakeClockMutex;
umtx_lock(&fakeClockMutex);
if(!fakeClock_set) {
UDate real = getUTCtime_real();
@@ -1315,11 +1315,10 @@ uprv_pathIsAbsolute(const char *path)
# endif
#endif
#if U_PLATFORM_HAS_WINUWP_API != 0
#if defined(ICU_DATA_DIR_WINDOWS)
// Helper function to get the ICU Data Directory under the Windows directory location.
static BOOL U_CALLCONV getIcuDataDirectoryUnderWindowsDirectory(char* directoryBuffer, UINT bufferLength)
{
#if defined(ICU_DATA_DIR_WINDOWS)
wchar_t windowsPath[MAX_PATH];
char windowsPathUtf8[MAX_PATH];
@@ -1346,7 +1345,6 @@ static BOOL U_CALLCONV getIcuDataDirectoryUnderWindowsDirectory(char* directoryB
}
}
}
#endif
return FALSE;
}
@@ -1380,9 +1378,9 @@ static void U_CALLCONV dataDirectoryInitFn() {
*/
# if !defined(ICU_NO_USER_DATA_OVERRIDE) && !UCONFIG_NO_FILE_IO
/* First try to get the environment variable */
# if U_PLATFORM_HAS_WINUWP_API == 0 // Windows UWP does not support getenv
# if U_PLATFORM_HAS_WINUWP_API == 0 // Windows UWP does not support getenv
path=getenv("ICU_DATA");
# endif
# endif
# endif
/* ICU_DATA_DIR may be set as a compile option.
@@ -1411,7 +1409,7 @@ static void U_CALLCONV dataDirectoryInitFn() {
}
#endif
#if U_PLATFORM_HAS_WINUWP_API != 0 && defined(ICU_DATA_DIR_WINDOWS)
#if defined(ICU_DATA_DIR_WINDOWS)
char datadir_path_buffer[MAX_PATH];
if (getIcuDataDirectoryUnderWindowsDirectory(datadir_path_buffer, UPRV_LENGTHOF(datadir_path_buffer))) {
path = datadir_path_buffer;
@@ -1461,12 +1459,17 @@ static void U_CALLCONV TimeZoneDataDirInitFn(UErrorCode &status) {
const char *dir = "";
#if U_PLATFORM_HAS_WINUWP_API != 0
// The UWP version does not support the environment variable setting, but can possibly pick them up from the Windows directory.
#if U_PLATFORM_HAS_WINUWP_API == 1
// The UWP version does not support the environment variable setting.
# if defined(ICU_DATA_DIR_WINDOWS)
// When using the Windows system data, we can possibly pick up time zone data from the Windows directory.
char datadir_path_buffer[MAX_PATH];
if (getIcuDataDirectoryUnderWindowsDirectory(datadir_path_buffer, UPRV_LENGTHOF(datadir_path_buffer))) {
dir = datadir_path_buffer;
}
# endif
#else
dir = getenv("ICU_TIMEZONE_FILES_DIR");
#endif // U_PLATFORM_HAS_WINUWP_API
@@ -1560,6 +1563,10 @@ static const char *uprv_getPOSIXIDForCategory(int category)
{
/* Nothing worked. Give it a nice POSIX default value. */
posixID = "en_US_POSIX";
// Note: this test will not catch 'C.UTF-8',
// that will be handled in uprv_getDefaultLocaleID().
// Leave this mapping here for the uprv_getPOSIXIDForDefaultCodepage()
// caller which expects to see "en_US_POSIX" in many branches.
}
return posixID;
}
@@ -1631,8 +1638,8 @@ The leftmost codepage (.xxx) wins.
}
// Copy the ID into owned memory.
// Over-allocate in case we replace "@" with "__".
char *correctedPOSIXLocale = static_cast<char *>(uprv_malloc(uprv_strlen(posixID) + 1 + 1));
// Over-allocate in case we replace "C" with "en_US_POSIX" (+10), + null termination
char *correctedPOSIXLocale = static_cast<char *>(uprv_malloc(uprv_strlen(posixID) + 10 + 1));
if (correctedPOSIXLocale == nullptr) {
return nullptr;
}
@@ -1641,9 +1648,16 @@ The leftmost codepage (.xxx) wins.
char *limit;
if ((limit = uprv_strchr(correctedPOSIXLocale, '.')) != nullptr) {
*limit = 0;
if ((limit = uprv_strchr(correctedPOSIXLocale, '@')) != nullptr) {
*limit = 0;
}
}
if ((limit = uprv_strchr(correctedPOSIXLocale, '@')) != nullptr) {
*limit = 0;
}
if ((uprv_strcmp("C", correctedPOSIXLocale) == 0) // no @ variant
|| (uprv_strcmp("POSIX", correctedPOSIXLocale) == 0)) {
// Raw input was C.* or POSIX.*, Give it a nice POSIX default value.
// (The "C"/"POSIX" case is handled in uprv_getPOSIXIDForCategory())
uprv_strcpy(correctedPOSIXLocale, "en_US_POSIX");
}
/* Note that we scan the *uncorrected* ID. */
@@ -1668,7 +1682,7 @@ The leftmost codepage (.xxx) wins.
if ((q = uprv_strchr(p, '.')) != nullptr) {
/* How big will the resulting string be? */
int32_t len = (int32_t)(uprv_strlen(correctedPOSIXLocale) + (q-p));
uprv_strncat(correctedPOSIXLocale, p, q-p);
uprv_strncat(correctedPOSIXLocale, p, q-p); // do not include charset
correctedPOSIXLocale[len] = 0;
}
else {
@@ -2053,7 +2067,7 @@ int_getDefaultCodepage()
static char codepage[64];
DWORD codepageNumber = 0;
#if U_PLATFORM_HAS_WINUWP_API > 0
#if U_PLATFORM_HAS_WINUWP_API == 1
// UWP doesn't have a direct API to get the default ACP as Microsoft would rather
// have folks use Unicode than a "system" code page, however this is the same
// codepage as the system default locale codepage. (FWIW, the system locale is
-70
View File
@@ -178,76 +178,6 @@ typedef size_t uintptr_t;
/** @} */
/*===========================================================================*/
/** @{ GCC built in functions for atomic memory operations */
/*===========================================================================*/
/**
* \def U_HAVE_GCC_ATOMICS
* @internal
*/
#ifdef U_HAVE_GCC_ATOMICS
/* Use the predefined value. */
#elif U_PLATFORM == U_PF_MINGW
#define U_HAVE_GCC_ATOMICS 0
#elif U_GCC_MAJOR_MINOR >= 404 || defined(__clang__)
/* TODO: Intel icc and IBM xlc on AIX also support gcc atomics. (Intel originated them.)
* Add them for these compilers.
* Note: Clang sets __GNUC__ defines for version 4.2, so misses the 4.4 test here.
*/
# define U_HAVE_GCC_ATOMICS 1
#else
# define U_HAVE_GCC_ATOMICS 0
#endif
/** @} */
/**
* \def U_HAVE_STD_ATOMICS
* Defines whether to use the C++11 std::atomic functions.
* If false, ICU will fall back to compiler or platform specific alternatives.
* Note: support for these fall back options for atomics will be removed in a future version
* of ICU, and the use of C++ 11 atomics will be required.
* @internal
*/
#ifdef U_HAVE_STD_ATOMICS
/* Use the predefined value. */
#else
# define U_HAVE_STD_ATOMICS 1
#endif
/**
* \def U_HAVE_CLANG_ATOMICS
* Defines whether Clang c11 style built-in atomics are available.
* These are used in preference to gcc atomics when both are available.
*/
#ifdef U_HAVE_CLANG_ATOMICS
/* Use the predefined value. */
#elif __has_builtin(__c11_atomic_load) && \
__has_builtin(__c11_atomic_store) && \
__has_builtin(__c11_atomic_fetch_add) && \
__has_builtin(__c11_atomic_fetch_sub)
# define U_HAVE_CLANG_ATOMICS 1
#else
# define U_HAVE_CLANG_ATOMICS 0
#endif
/**
* \def U_HAVE_STD_MUTEX
* Defines whether to use the C++11 std::mutex functions.
* If false, ICU will fall back to compiler or platform specific alternatives.
* std::mutex is preferred, and used by default unless this setting is overridden.
* Note: support for other options for mutexes will be removed in a future version
* of ICU, and the use of std::mutex will be required.
* @internal
*/
#ifdef U_HAVE_STD_MUTEX
/* Use the predefined value. */
#else
# define U_HAVE_STD_MUTEX 1
#endif
/*===========================================================================*/
/** @{ Programs used by ICU code */
/*===========================================================================*/
+5 -7
View File
@@ -323,8 +323,8 @@ void RuleBasedBreakIterator::init(UErrorCode &status) {
// Virtual function: does the right thing with subclasses.
//
//-----------------------------------------------------------------------------
BreakIterator*
RuleBasedBreakIterator::clone(void) const {
RuleBasedBreakIterator*
RuleBasedBreakIterator::clone() const {
return new RuleBasedBreakIterator(*this);
}
@@ -352,7 +352,7 @@ RuleBasedBreakIterator::operator==(const BreakIterator& that) const {
// or have a different iteration position.
// Note that fText's position is always the same as the break iterator's position.
return FALSE;
};
}
if (!(fPosition == that2.fPosition &&
fRuleStatusIndex == that2.fRuleStatusIndex &&
@@ -1079,10 +1079,8 @@ const uint8_t *RuleBasedBreakIterator::getBinaryRules(uint32_t &length) {
}
BreakIterator * RuleBasedBreakIterator::createBufferClone(void * /*stackBuffer*/,
int32_t &bufferSize,
UErrorCode &status)
{
RuleBasedBreakIterator *RuleBasedBreakIterator::createBufferClone(
void * /*stackBuffer*/, int32_t &bufferSize, UErrorCode &status) {
if (U_FAILURE(status)){
return NULL;
}
+1 -1
View File
@@ -519,7 +519,7 @@ UBool RuleBasedBreakIterator::BreakCache::populatePreceding(UErrorCode &status)
// The initial handleNext() only advanced by a single code point. Go again.
position = fBI->handleNext(); // Safe rules identify safe pairs.
}
};
}
positionStatusIdx = fBI->fRuleStatusIndex;
}
} while (position >= fromPosition);
+2 -1
View File
@@ -51,6 +51,7 @@
#include "unicode/utypes.h"
#include "unicode/resbund.h"
#include "cmemory.h"
#include "mutex.h"
#include "uassert.h"
#include "umutex.h"
@@ -377,7 +378,7 @@ void ResourceBundle::getVersion(UVersionInfo versionInfo) const {
}
const Locale &ResourceBundle::getLocale(void) const {
static UMutex gLocaleLock = U_MUTEX_INITIALIZER;
static UMutex gLocaleLock;
Mutex lock(&gLocaleLock);
if (fLocale != NULL) {
return *fLocale;
+19 -5
View File
@@ -28,6 +28,7 @@
#include "unicode/utypes.h"
#include "unicode/unistr.h"
#include "unicode/ures.h"
#include "restrace.h"
struct ResourceData;
@@ -47,8 +48,10 @@ public:
ResourceArray() : items16(NULL), items32(NULL), length(0) {}
/** Only for implementation use. @internal */
ResourceArray(const uint16_t *i16, const uint32_t *i32, int32_t len) :
items16(i16), items32(i32), length(len) {}
ResourceArray(const uint16_t *i16, const uint32_t *i32, int32_t len,
const ResourceTracer& traceInfo) :
items16(i16), items32(i32), length(len),
fTraceInfo(traceInfo) {}
/**
* @return The number of items in the array resource.
@@ -68,6 +71,7 @@ private:
const uint16_t *items16;
const uint32_t *items32;
int32_t length;
ResourceTracer fTraceInfo;
};
/**
@@ -80,27 +84,37 @@ public:
/** Only for implementation use. @internal */
ResourceTable(const uint16_t *k16, const int32_t *k32,
const uint16_t *i16, const uint32_t *i32, int32_t len) :
keys16(k16), keys32(k32), items16(i16), items32(i32), length(len) {}
const uint16_t *i16, const uint32_t *i32, int32_t len,
const ResourceTracer& traceInfo) :
keys16(k16), keys32(k32), items16(i16), items32(i32), length(len),
fTraceInfo(traceInfo) {}
/**
* @return The number of items in the array resource.
*/
int32_t getSize() const { return length; }
/**
* @param i Array item index.
* @param i Table item index.
* @param key Output-only, receives the key of the i'th item.
* @param value Output-only, receives the value of the i'th item.
* @return TRUE if i is non-negative and less than getSize().
*/
UBool getKeyAndValue(int32_t i, const char *&key, ResourceValue &value) const;
/**
* @param key Key string to find in the table.
* @param value Output-only, receives the value of the item with that key.
* @return TRUE if the table contains the key.
*/
UBool findValue(const char *key, ResourceValue &value) const;
private:
const uint16_t *keys16;
const int32_t *keys32;
const uint16_t *items16;
const uint32_t *items32;
int32_t length;
ResourceTracer fTraceInfo;
};
/**
+130
View File
@@ -0,0 +1,130 @@
// © 2019 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#include "unicode/utypes.h"
#if U_ENABLE_TRACING
#include "restrace.h"
#include "charstr.h"
#include "cstring.h"
#include "utracimp.h"
#include "uresimp.h"
#include "uassert.h"
#include "util.h"
U_NAMESPACE_BEGIN
ResourceTracer::~ResourceTracer() = default;
void ResourceTracer::trace(const char* resType) const {
U_ASSERT(fResB || fParent);
UTRACE_ENTRY(UTRACE_UDATA_RESOURCE);
UErrorCode status = U_ZERO_ERROR;
CharString filePath;
getFilePath(filePath, status);
CharString resPath;
getResPath(resPath, status);
// The longest type ("intvector") is 9 chars
const char kSpaces[] = " ";
CharString format;
format.append(kSpaces, sizeof(kSpaces) - 1 - uprv_strlen(resType), status);
format.append("(%s) %s @ %s", status);
UTRACE_DATA3(UTRACE_VERBOSE,
format.data(),
resType,
filePath.data(),
resPath.data());
UTRACE_EXIT_STATUS(status);
}
void ResourceTracer::traceOpen() const {
U_ASSERT(fResB);
UTRACE_ENTRY(UTRACE_UDATA_BUNDLE);
UErrorCode status = U_ZERO_ERROR;
CharString filePath;
UTRACE_DATA1(UTRACE_VERBOSE, "%s", getFilePath(filePath, status).data());
UTRACE_EXIT_STATUS(status);
}
CharString& ResourceTracer::getFilePath(CharString& output, UErrorCode& status) const {
if (fResB) {
output.append(fResB->fData->fPath, status);
output.append('/', status);
output.append(fResB->fData->fName, status);
output.append(".res", status);
} else {
fParent->getFilePath(output, status);
}
return output;
}
CharString& ResourceTracer::getResPath(CharString& output, UErrorCode& status) const {
if (fResB) {
output.append('/', status);
output.append(fResB->fResPath, status);
// removing the trailing /
U_ASSERT(output[output.length()-1] == '/');
output.truncate(output.length()-1);
} else {
fParent->getResPath(output, status);
}
if (fKey) {
output.append('/', status);
output.append(fKey, status);
}
if (fIndex != -1) {
output.append('[', status);
UnicodeString indexString;
ICU_Utility::appendNumber(indexString, fIndex);
output.appendInvariantChars(indexString, status);
output.append(']', status);
}
return output;
}
void FileTracer::traceOpen(const char* path, const char* type, const char* name) {
if (uprv_strcmp(type, "res") == 0) {
traceOpenResFile(path, name);
} else {
traceOpenDataFile(path, type, name);
}
}
void FileTracer::traceOpenDataFile(const char* path, const char* type, const char* name) {
UTRACE_ENTRY(UTRACE_UDATA_DATA_FILE);
UErrorCode status = U_ZERO_ERROR;
CharString filePath;
filePath.append(path, status);
filePath.append('/', status);
filePath.append(name, status);
filePath.append('.', status);
filePath.append(type, status);
UTRACE_DATA1(UTRACE_VERBOSE, "%s", filePath.data());
UTRACE_EXIT_STATUS(status);
}
void FileTracer::traceOpenResFile(const char* path, const char* name) {
UTRACE_ENTRY(UTRACE_UDATA_RES_FILE);
UErrorCode status = U_ZERO_ERROR;
CharString filePath;
filePath.append(path, status);
filePath.append('/', status);
filePath.append(name, status);
filePath.append(".res", status);
UTRACE_DATA1(UTRACE_VERBOSE, "%s", filePath.data());
UTRACE_EXIT_STATUS(status);
}
U_NAMESPACE_END
#endif // U_ENABLE_TRACING
+147
View File
@@ -0,0 +1,147 @@
// © 2019 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#ifndef __RESTRACE_H__
#define __RESTRACE_H__
#include "unicode/utypes.h"
#if U_ENABLE_TRACING
struct UResourceBundle;
U_NAMESPACE_BEGIN
class CharString;
/**
* Instances of this class store information used to trace reads from resource
* bundles when ICU is built with --enable-tracing.
*
* All arguments of type const UResourceBundle*, const char*, and
* const ResourceTracer& are stored as pointers. The caller must retain
* ownership for the lifetime of this ResourceTracer.
*
* Exported as U_COMMON_API for Windows because it is a value field
* in other exported types.
*/
class U_COMMON_API ResourceTracer {
public:
ResourceTracer() :
fResB(nullptr),
fParent(nullptr),
fKey(nullptr),
fIndex(-1) {}
ResourceTracer(const UResourceBundle* resB) :
fResB(resB),
fParent(nullptr),
fKey(nullptr),
fIndex(-1) {}
ResourceTracer(const UResourceBundle* resB, const char* key) :
fResB(resB),
fParent(nullptr),
fKey(key),
fIndex(-1) {}
ResourceTracer(const UResourceBundle* resB, int32_t index) :
fResB(resB),
fParent(nullptr),
fKey(nullptr),
fIndex(index) {}
ResourceTracer(const ResourceTracer& parent, const char* key) :
fResB(nullptr),
fParent(&parent),
fKey(key),
fIndex(-1) {}
ResourceTracer(const ResourceTracer& parent, int32_t index) :
fResB(nullptr),
fParent(&parent),
fKey(nullptr),
fIndex(index) {}
~ResourceTracer();
void trace(const char* type) const;
void traceOpen() const;
/**
* Calls trace() if the resB or parent provided to the constructor was
* non-null; otherwise, does nothing.
*/
void maybeTrace(const char* type) const {
if (fResB || fParent) {
trace(type);
}
}
private:
const UResourceBundle* fResB;
const ResourceTracer* fParent;
const char* fKey;
int32_t fIndex;
CharString& getFilePath(CharString& output, UErrorCode& status) const;
CharString& getResPath(CharString& output, UErrorCode& status) const;
};
/**
* This class provides methods to trace data file reads when ICU is built
* with --enable-tracing.
*/
class FileTracer {
public:
static void traceOpen(const char* path, const char* type, const char* name);
private:
static void traceOpenDataFile(const char* path, const char* type, const char* name);
static void traceOpenResFile(const char* path, const char* name);
};
U_NAMESPACE_END
#else // U_ENABLE_TRACING
U_NAMESPACE_BEGIN
/**
* Default trivial implementation when --enable-tracing is not used.
*/
class U_COMMON_API ResourceTracer {
public:
ResourceTracer() {}
ResourceTracer(const void*) {}
ResourceTracer(const void*, const char*) {}
ResourceTracer(const void*, int32_t) {}
ResourceTracer(const ResourceTracer&, const char*) {}
ResourceTracer(const ResourceTracer&, int32_t) {}
void trace(const char*) const {}
void traceOpen() const {}
void maybeTrace(const char*) const {}
};
/**
* Default trivial implementation when --enable-tracing is not used.
*/
class FileTracer {
public:
static void traceOpen(const char*, const char*, const char*) {}
};
U_NAMESPACE_END
#endif // U_ENABLE_TRACING
#endif //__RESTRACE_H__
+1 -1
View File
@@ -101,7 +101,7 @@ StringCharacterIterator::operator==(const ForwardCharacterIterator& that) const
&& end == realThat.end;
}
CharacterIterator*
StringCharacterIterator*
StringCharacterIterator::clone() const {
return new StringCharacterIterator(*this);
}
+9 -12
View File
@@ -333,10 +333,7 @@ U_CDECL_END
******************************************************************
*/
static UMutex *lock() {
static UMutex m = U_MUTEX_INITIALIZER;
return &m;
}
static UMutex lock;
ICUService::ICUService()
: name()
@@ -361,7 +358,7 @@ ICUService::ICUService(const UnicodeString& newName)
ICUService::~ICUService()
{
{
Mutex mutex(lock());
Mutex mutex(&lock);
clearCaches();
delete factories;
factories = NULL;
@@ -452,7 +449,7 @@ ICUService::getKey(ICUServiceKey& key, UnicodeString* actualReturn, const ICUSer
// if factory is not null, we're calling from within the mutex,
// and since some unix machines don't have reentrant mutexes we
// need to make sure not to try to lock it again.
XMutex mutex(lock(), factory != NULL);
XMutex mutex(&lock, factory != NULL);
if (serviceCache == NULL) {
ncthis->serviceCache = new Hashtable(status);
@@ -618,7 +615,7 @@ ICUService::getVisibleIDs(UVector& result, const UnicodeString* matchID, UErrorC
}
{
Mutex mutex(lock());
Mutex mutex(&lock);
const Hashtable* map = getVisibleIDMap(status);
if (map != NULL) {
ICUServiceKey* fallbackKey = createKey(matchID, status);
@@ -695,7 +692,7 @@ ICUService::getDisplayName(const UnicodeString& id, UnicodeString& result, const
{
{
UErrorCode status = U_ZERO_ERROR;
Mutex mutex(lock());
Mutex mutex(&lock);
const Hashtable* map = getVisibleIDMap(status);
if (map != NULL) {
ICUServiceFactory* f = (ICUServiceFactory*)map->get(id);
@@ -747,7 +744,7 @@ ICUService::getDisplayNames(UVector& result,
result.setDeleter(userv_deleteStringPair);
if (U_SUCCESS(status)) {
ICUService* ncthis = (ICUService*)this; // cast away semantic const
Mutex mutex(lock());
Mutex mutex(&lock);
if (dnCache != NULL && dnCache->locale != locale) {
delete dnCache;
@@ -852,7 +849,7 @@ URegistryKey
ICUService::registerFactory(ICUServiceFactory* factoryToAdopt, UErrorCode& status)
{
if (U_SUCCESS(status) && factoryToAdopt != NULL) {
Mutex mutex(lock());
Mutex mutex(&lock);
if (factories == NULL) {
factories = new UVector(deleteUObject, NULL, status);
@@ -883,7 +880,7 @@ ICUService::unregister(URegistryKey rkey, UErrorCode& status)
ICUServiceFactory *factory = (ICUServiceFactory*)rkey;
UBool result = FALSE;
if (factory != NULL && factories != NULL) {
Mutex mutex(lock());
Mutex mutex(&lock);
if (factories->removeElement(factory)) {
clearCaches();
@@ -903,7 +900,7 @@ void
ICUService::reset()
{
{
Mutex mutex(lock());
Mutex mutex(&lock);
reInitializeFactories();
clearCaches();
}
+1 -1
View File
@@ -263,7 +263,7 @@ ICULocaleService::validateFallbackLocale() const
{
const Locale& loc = Locale::getDefault();
ICULocaleService* ncThis = (ICULocaleService*)this;
static UMutex llock = U_MUTEX_INITIALIZER;
static UMutex llock;
{
Mutex mutex(&llock);
if (loc != fallbackLocale) {
+5 -8
View File
@@ -21,10 +21,7 @@ U_NAMESPACE_BEGIN
EventListener::~EventListener() {}
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(EventListener)
static UMutex *notifyLock() {
static UMutex m = U_MUTEX_INITIALIZER;
return &m;
}
static UMutex notifyLock;
ICUNotifier::ICUNotifier(void)
: listeners(NULL)
@@ -33,7 +30,7 @@ ICUNotifier::ICUNotifier(void)
ICUNotifier::~ICUNotifier(void) {
{
Mutex lmx(notifyLock());
Mutex lmx(&notifyLock);
delete listeners;
listeners = NULL;
}
@@ -50,7 +47,7 @@ ICUNotifier::addListener(const EventListener* l, UErrorCode& status)
}
if (acceptsListener(*l)) {
Mutex lmx(notifyLock());
Mutex lmx(&notifyLock);
if (listeners == NULL) {
listeners = new UVector(5, status);
} else {
@@ -83,7 +80,7 @@ ICUNotifier::removeListener(const EventListener *l, UErrorCode& status)
}
{
Mutex lmx(notifyLock());
Mutex lmx(&notifyLock);
if (listeners != NULL) {
// identity equality check
for (int i = 0, e = listeners->size(); i < e; ++i) {
@@ -106,7 +103,7 @@ void
ICUNotifier::notifyChanged(void)
{
if (listeners != NULL) {
Mutex lmx(notifyLock());
Mutex lmx(&notifyLock);
if (listeners != NULL) {
for (int i = 0, e = listeners->size(); i < e; ++i) {
EventListener* el = (EventListener*)listeners->elementAt(i);
+17 -33
View File
@@ -34,6 +34,10 @@ enum {
STACK_ITEM_SIZE=200
};
static constexpr int32_t sizeInMaxAlignTs(int32_t sizeInBytes) {
return (sizeInBytes + sizeof(max_align_t) - 1) / sizeof(max_align_t);
}
/* UComparator convenience implementations ---------------------------------- */
U_CAPI int32_t U_EXPORT2
@@ -134,25 +138,15 @@ doInsertionSort(char *array, int32_t length, int32_t itemSize,
static void
insertionSort(char *array, int32_t length, int32_t itemSize,
UComparator *cmp, const void *context, UErrorCode *pErrorCode) {
UAlignedMemory v[STACK_ITEM_SIZE/sizeof(UAlignedMemory)+1];
void *pv;
/* allocate an intermediate item variable (v) */
if(itemSize<=STACK_ITEM_SIZE) {
pv=v;
} else {
pv=uprv_malloc(itemSize);
if(pv==NULL) {
*pErrorCode=U_MEMORY_ALLOCATION_ERROR;
return;
}
icu::MaybeStackArray<max_align_t, sizeInMaxAlignTs(STACK_ITEM_SIZE)> v;
if (sizeInMaxAlignTs(itemSize) > v.getCapacity() &&
v.resize(sizeInMaxAlignTs(itemSize)) == nullptr) {
*pErrorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
doInsertionSort(array, length, itemSize, cmp, context, pv);
if(pv!=v) {
uprv_free(pv);
}
doInsertionSort(array, length, itemSize, cmp, context, v.getAlias());
}
/* QuickSort ---------------------------------------------------------------- */
@@ -238,26 +232,16 @@ subQuickSort(char *array, int32_t start, int32_t limit, int32_t itemSize,
static void
quickSort(char *array, int32_t length, int32_t itemSize,
UComparator *cmp, const void *context, UErrorCode *pErrorCode) {
UAlignedMemory xw[(2*STACK_ITEM_SIZE)/sizeof(UAlignedMemory)+1];
void *p;
/* allocate two intermediate item variables (x and w) */
if(itemSize<=STACK_ITEM_SIZE) {
p=xw;
} else {
p=uprv_malloc(2*itemSize);
if(p==NULL) {
*pErrorCode=U_MEMORY_ALLOCATION_ERROR;
return;
}
icu::MaybeStackArray<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;
return;
}
subQuickSort(array, 0, length, itemSize,
cmp, context, p, (char *)p+itemSize);
if(p!=xw) {
uprv_free(p);
}
subQuickSort(array, 0, length, itemSize, cmp, context,
xw.getAlias(), xw.getAlias() + sizeInMaxAlignTs(itemSize));
}
/* uprv_sortArray() API ----------------------------------------------------- */
+44 -36
View File
@@ -198,8 +198,8 @@ typedef struct Run {
/* in a Run, logicalStart will get this bit set if the run level is odd */
#define INDEX_ODD_BIT (1UL<<31)
#define MAKE_INDEX_ODD_PAIR(index, level) ((index)|((int32_t)(level)<<31))
#define ADD_ODD_BIT_FROM_LEVEL(x, level) ((x)|=((int32_t)(level)<<31))
#define MAKE_INDEX_ODD_PAIR(index, level) ((index)|((int32_t)((level)&1)<<31))
#define ADD_ODD_BIT_FROM_LEVEL(x, level) ((x)|=((int32_t)((level)&1)<<31))
#define REMOVE_ODD_BIT(x) ((x)&=~INDEX_ODD_BIT)
#define GET_INDEX(x) ((x)&~INDEX_ODD_BIT)
@@ -387,41 +387,49 @@ typedef union {
} BidiMemoryForAllocation;
/* Macros for initial checks at function entry */
#define RETURN_IF_NULL_OR_FAILING_ERRCODE(pErrcode, retvalue) \
if((pErrcode)==NULL || U_FAILURE(*pErrcode)) return retvalue
#define RETURN_IF_NOT_VALID_PARA(bidi, errcode, retvalue) \
if(!IS_VALID_PARA(bidi)) { \
errcode=U_INVALID_STATE_ERROR; \
return retvalue; \
}
#define RETURN_IF_NOT_VALID_PARA_OR_LINE(bidi, errcode, retvalue) \
if(!IS_VALID_PARA_OR_LINE(bidi)) { \
errcode=U_INVALID_STATE_ERROR; \
return retvalue; \
}
#define RETURN_IF_BAD_RANGE(arg, start, limit, errcode, retvalue) \
if((arg)<(start) || (arg)>=(limit)) { \
(errcode)=U_ILLEGAL_ARGUMENT_ERROR; \
return retvalue; \
}
#define RETURN_IF_NULL_OR_FAILING_ERRCODE(pErrcode, retvalue) UPRV_BLOCK_MACRO_BEGIN { \
if((pErrcode)==NULL || U_FAILURE(*pErrcode)) return retvalue; \
} UPRV_BLOCK_MACRO_END
#define RETURN_IF_NOT_VALID_PARA(bidi, errcode, retvalue) UPRV_BLOCK_MACRO_BEGIN { \
if(!IS_VALID_PARA(bidi)) { \
errcode=U_INVALID_STATE_ERROR; \
return retvalue; \
} \
} UPRV_BLOCK_MACRO_END
#define RETURN_IF_NOT_VALID_PARA_OR_LINE(bidi, errcode, retvalue) UPRV_BLOCK_MACRO_BEGIN { \
if(!IS_VALID_PARA_OR_LINE(bidi)) { \
errcode=U_INVALID_STATE_ERROR; \
return retvalue; \
} \
} UPRV_BLOCK_MACRO_END
#define RETURN_IF_BAD_RANGE(arg, start, limit, errcode, retvalue) UPRV_BLOCK_MACRO_BEGIN { \
if((arg)<(start) || (arg)>=(limit)) { \
(errcode)=U_ILLEGAL_ARGUMENT_ERROR; \
return retvalue; \
} \
} UPRV_BLOCK_MACRO_END
#define RETURN_VOID_IF_NULL_OR_FAILING_ERRCODE(pErrcode) \
if((pErrcode)==NULL || U_FAILURE(*pErrcode)) return
#define RETURN_VOID_IF_NOT_VALID_PARA(bidi, errcode) \
if(!IS_VALID_PARA(bidi)) { \
errcode=U_INVALID_STATE_ERROR; \
return; \
}
#define RETURN_VOID_IF_NOT_VALID_PARA_OR_LINE(bidi, errcode) \
if(!IS_VALID_PARA_OR_LINE(bidi)) { \
errcode=U_INVALID_STATE_ERROR; \
return; \
}
#define RETURN_VOID_IF_BAD_RANGE(arg, start, limit, errcode) \
if((arg)<(start) || (arg)>=(limit)) { \
(errcode)=U_ILLEGAL_ARGUMENT_ERROR; \
return; \
}
#define RETURN_VOID_IF_NULL_OR_FAILING_ERRCODE(pErrcode) UPRV_BLOCK_MACRO_BEGIN { \
if((pErrcode)==NULL || U_FAILURE(*pErrcode)) return; \
} UPRV_BLOCK_MACRO_END
#define RETURN_VOID_IF_NOT_VALID_PARA(bidi, errcode) UPRV_BLOCK_MACRO_BEGIN { \
if(!IS_VALID_PARA(bidi)) { \
errcode=U_INVALID_STATE_ERROR; \
return; \
} \
} UPRV_BLOCK_MACRO_END
#define RETURN_VOID_IF_NOT_VALID_PARA_OR_LINE(bidi, errcode) UPRV_BLOCK_MACRO_BEGIN { \
if(!IS_VALID_PARA_OR_LINE(bidi)) { \
errcode=U_INVALID_STATE_ERROR; \
return; \
} \
} UPRV_BLOCK_MACRO_END
#define RETURN_VOID_IF_BAD_RANGE(arg, start, limit, errcode) UPRV_BLOCK_MACRO_BEGIN { \
if((arg)<(start) || (arg)>=(limit)) { \
(errcode)=U_ILLEGAL_ARGUMENT_ERROR; \
return; \
} \
} UPRV_BLOCK_MACRO_END
/* helper function to (re)allocate memory if allowed */
U_CFUNC UBool
+5 -5
View File
@@ -31,11 +31,11 @@
#define SHAPE_LOGICAL U_SHAPE_TEXT_DIRECTION_LOGICAL
#define SHAPE_VISUAL U_SHAPE_TEXT_DIRECTION_VISUAL_LTR
#define CHECK_LEN(STR, LEN, ERROR) { \
if (LEN == 0) return 0; \
if (LEN < -1) { *(ERROR) = U_ILLEGAL_ARGUMENT_ERROR; return 0; } \
if (LEN == -1) LEN = u_strlen(STR); \
}
#define CHECK_LEN(STR, LEN, ERROR) UPRV_BLOCK_MACRO_BEGIN { \
if (LEN == 0) return 0; \
if (LEN < -1) { *(ERROR) = U_ILLEGAL_ARGUMENT_ERROR; return 0; } \
if (LEN == -1) LEN = u_strlen(STR); \
} UPRV_BLOCK_MACRO_END
#define MAX_ACTIONS 7
+3 -2
View File
@@ -116,7 +116,7 @@ static const uint8_t flagsOffset[256]={
* moved to the last uint16_t of the value, use +1 for beginning of next slot
* @param value (out) int32_t or uint32_t output if hasSlot, otherwise not modified
*/
#define GET_SLOT_VALUE(excWord, idx, pExc16, value) \
#define GET_SLOT_VALUE(excWord, idx, pExc16, value) UPRV_BLOCK_MACRO_BEGIN { \
if(((excWord)&UCASE_EXC_DOUBLE_SLOTS)==0) { \
(pExc16)+=SLOT_OFFSET(excWord, idx); \
(value)=*pExc16; \
@@ -124,7 +124,8 @@ static const uint8_t flagsOffset[256]={
(pExc16)+=2*SLOT_OFFSET(excWord, idx); \
(value)=*pExc16++; \
(value)=((value)<<16)|*pExc16; \
}
} \
} UPRV_BLOCK_MACRO_END
/* simple case mappings ----------------------------------------------------- */
+1 -1
View File
@@ -40,7 +40,7 @@
/* constants and macros for access to the data ------------------------------ */
/* getting a uint32_t properties word from the data */
#define GET_PROPS(c, result) ((result)=UTRIE2_GET16(&propsTrie, c));
#define GET_PROPS(c, result) ((result)=UTRIE2_GET16(&propsTrie, c))
/* API functions ------------------------------------------------------------ */
+1 -1
View File
@@ -89,7 +89,7 @@ UCharCharacterIterator::hashCode() const {
return ustr_hashUCharsN(text, textLength) ^ pos ^ begin ^ end;
}
CharacterIterator*
UCharCharacterIterator*
UCharCharacterIterator::clone() const {
return new UCharCharacterIterator(*this);
}
+13 -2
View File
@@ -65,9 +65,20 @@ U_CFUNC void
ucln_common_registerCleanup(ECleanupCommonType type,
cleanupFunc *func)
{
// Thread safety messiness: From ticket 10295, calls to registerCleanup() may occur
// concurrently. Although such cases should be storing the same value, they raise errors
// from the thread sanity checker. Doing the store within a mutex avoids those.
// BUT that can trigger a recursive entry into std::call_once() in umutex.cpp when this code,
// running from the call_once function, tries to grab the ICU global mutex, which
// re-enters the mutex init path. So, work-around by special casing UCLN_COMMON_MUTEX, not
// using the ICU global mutex for it.
//
// No other point in ICU uses std::call_once().
U_ASSERT(UCLN_COMMON_START < type && type < UCLN_COMMON_COUNT);
if (UCLN_COMMON_START < type && type < UCLN_COMMON_COUNT)
{
if (type == UCLN_COMMON_MUTEX) {
gCommonCleanupFunctions[type] = func;
} else if (UCLN_COMMON_START < type && type < UCLN_COMMON_COUNT) {
icu::Mutex m; // See ticket 10295 for discussion.
gCommonCleanupFunctions[type] = func;
}
+3 -2
View File
@@ -22,8 +22,6 @@
/* These are the cleanup functions for various APIs. */
/* @return true if cleanup complete successfully.*/
U_CFUNC UBool umtx_cleanup(void);
U_CFUNC UBool utrace_cleanup(void);
U_CFUNC UBool ucln_lib_cleanup(void);
@@ -41,6 +39,8 @@ typedef enum ECleanupCommonType {
UCLN_COMMON_LOCALE_KEY_TYPE,
UCLN_COMMON_LOCALE,
UCLN_COMMON_LOCALE_AVAILABLE,
UCLN_COMMON_LIKELY_SUBTAGS,
UCLN_COMMON_LOCALE_DISTANCE,
UCLN_COMMON_ULOC,
UCLN_COMMON_CURRENCY,
UCLN_COMMON_LOADED_NORMALIZER2,
@@ -62,6 +62,7 @@ typedef enum ECleanupCommonType {
*/
UCLN_COMMON_UNIFIED_CACHE,
UCLN_COMMON_URES,
UCLN_COMMON_MUTEX, // Mutexes should be the last to be cleaned up.
UCLN_COMMON_COUNT /* This must be last */
} ECleanupCommonType;
+12 -12
View File
@@ -25,6 +25,8 @@
#if !UCONFIG_NO_CONVERSION
#include <memory>
#include "unicode/ustring.h"
#include "unicode/ucnv.h"
#include "unicode/ucnv_err.h"
@@ -158,7 +160,6 @@ ucnv_safeClone(const UConverter* cnv, void *stackBuffer, int32_t *pBufferSize, U
UConverter *localConverter, *allocatedConverter;
int32_t stackBufferSize;
int32_t bufferSizeNeeded;
char *stackBufferChars = (char *)stackBuffer;
UErrorCode cbErr;
UConverterToUnicodeArgs toUArgs = {
sizeof(UConverterToUnicodeArgs),
@@ -224,23 +225,22 @@ ucnv_safeClone(const UConverter* cnv, void *stackBuffer, int32_t *pBufferSize, U
}
}
/* Pointers on 64-bit platforms need to be aligned
* on a 64-bit boundary in memory.
/* Adjust (if necessary) the stackBuffer pointer to be aligned correctly for a UConverter.
* TODO(Jira ICU-20736) Redo this using std::align() once g++4.9 compatibility is no longer needed.
*/
if (U_ALIGNMENT_OFFSET(stackBuffer) != 0) {
int32_t offsetUp = (int32_t)U_ALIGNMENT_OFFSET_UP(stackBufferChars);
if(stackBufferSize > offsetUp) {
stackBufferSize -= offsetUp;
stackBufferChars += offsetUp;
if (stackBuffer) {
uintptr_t p = reinterpret_cast<uintptr_t>(stackBuffer);
uintptr_t aligned_p = (p + alignof(UConverter) - 1) & ~(alignof(UConverter) - 1);
ptrdiff_t pointerAdjustment = aligned_p - p;
if (bufferSizeNeeded + pointerAdjustment <= stackBufferSize) {
stackBuffer = reinterpret_cast<void *>(aligned_p);
stackBufferSize -= pointerAdjustment;
} else {
/* prevent using the stack buffer but keep the size > 0 so that we do not just preflight */
stackBufferSize = 1;
}
}
stackBuffer = (void *)stackBufferChars;
/* Now, see if we must allocate any memory */
if (stackBufferSize < bufferSizeNeeded || stackBuffer == NULL)
{
@@ -475,7 +475,7 @@ ucnv_setSubstString(UConverter *cnv,
const UChar *s,
int32_t length,
UErrorCode *err) {
UAlignedMemory cloneBuffer[U_CNV_SAFECLONE_BUFFERSIZE / sizeof(UAlignedMemory) + 1];
alignas(UConverter) char cloneBuffer[U_CNV_SAFECLONE_BUFFERSIZE];
char chars[UCNV_ERROR_BUFFER_LENGTH];
UConverter *clone;
+5 -10
View File
@@ -3571,20 +3571,11 @@ _ISO_2022_WriteSub(UConverterFromUnicodeArgs *args, int32_t offsetIndex, UErrorC
/*
* Structure for cloning an ISO 2022 converter into a single memory block.
* ucnv_safeClone() of the converter will align the entire cloneStruct,
* and then ucnv_safeClone() of the sub-converter may additionally align
* currentConverter inside the cloneStruct, for which we need the deadSpace
* after currentConverter.
* This is because UAlignedMemory may be larger than the actually
* necessary alignment size for the platform.
* The other cloneStruct fields will not be moved around,
* and are aligned properly with cloneStruct's alignment.
*/
struct cloneStruct
{
UConverter cnv;
UConverter currentConverter;
UAlignedMemory deadSpace;
UConverterDataISO2022 mydata;
};
@@ -3602,6 +3593,10 @@ _ISO_2022_SafeClone(
UConverterDataISO2022 *cnvData;
int32_t i, size;
if (U_FAILURE(*status)){
return nullptr;
}
if (*pBufferSize == 0) { /* 'preflighting' request - set needed size into *pBufferSize */
*pBufferSize = (int32_t)sizeof(struct cloneStruct);
return NULL;
@@ -3619,7 +3614,7 @@ _ISO_2022_SafeClone(
/* share the subconverters */
if(cnvData->currentConverter != NULL) {
size = (int32_t)(sizeof(UConverter) + sizeof(UAlignedMemory)); /* include size of padding */
size = (int32_t)sizeof(UConverter);
localClone->mydata.currentConverter =
ucnv_safeClone(cnvData->currentConverter,
&localClone->currentConverter,
+12 -15
View File
@@ -194,10 +194,7 @@ static struct {
/*initializes some global variables */
static UHashtable *SHARED_DATA_HASHTABLE = NULL;
static icu::UMutex *cnvCacheMutex() { /* Mutex for synchronizing cnv cache access. */
static icu::UMutex m = U_MUTEX_INITIALIZER;
return &m;
}
static icu::UMutex cnvCacheMutex;
/* Note: the global mutex is used for */
/* reference count updates. */
@@ -602,9 +599,9 @@ U_CFUNC void
ucnv_unloadSharedDataIfReady(UConverterSharedData *sharedData)
{
if(sharedData != NULL && sharedData->isReferenceCounted) {
umtx_lock(cnvCacheMutex());
umtx_lock(&cnvCacheMutex);
ucnv_unload(sharedData);
umtx_unlock(cnvCacheMutex());
umtx_unlock(&cnvCacheMutex);
}
}
@@ -612,9 +609,9 @@ U_CFUNC void
ucnv_incrementRefCount(UConverterSharedData *sharedData)
{
if(sharedData != NULL && sharedData->isReferenceCounted) {
umtx_lock(cnvCacheMutex());
umtx_lock(&cnvCacheMutex);
sharedData->referenceCounter++;
umtx_unlock(cnvCacheMutex());
umtx_unlock(&cnvCacheMutex);
}
}
@@ -815,9 +812,9 @@ ucnv_loadSharedData(const char *converterName,
pArgs->nestedLoads=1;
pArgs->pkg=NULL;
umtx_lock(cnvCacheMutex());
umtx_lock(&cnvCacheMutex);
mySharedConverterData = ucnv_load(pArgs, err);
umtx_unlock(cnvCacheMutex());
umtx_unlock(&cnvCacheMutex);
if (U_FAILURE (*err) || (mySharedConverterData == NULL))
{
return NULL;
@@ -1064,7 +1061,7 @@ ucnv_flushCache ()
* because the sequence of looking up in the cache + incrementing
* is protected by cnvCacheMutex.
*/
umtx_lock(cnvCacheMutex());
umtx_lock(&cnvCacheMutex);
/*
* double loop: A delta/extension-only converter has a pointer to its base table's
* shared data; the first iteration of the outer loop may see the delta converter
@@ -1093,7 +1090,7 @@ ucnv_flushCache ()
}
}
} while(++i == 1 && remaining > 0);
umtx_unlock(cnvCacheMutex());
umtx_unlock(&cnvCacheMutex);
UTRACE_DATA1(UTRACE_INFO, "ucnv_flushCache() exits with %d converters remaining", remaining);
@@ -1199,7 +1196,7 @@ internalSetName(const char *name, UErrorCode *status) {
}
algorithmicSharedData = getAlgorithmicTypeFromName(stackArgs.name);
umtx_lock(cnvCacheMutex());
umtx_lock(&cnvCacheMutex);
gDefaultAlgorithmicSharedData = algorithmicSharedData;
gDefaultConverterContainsOption = containsOption;
@@ -1215,7 +1212,7 @@ internalSetName(const char *name, UErrorCode *status) {
ucnv_enableCleanup();
umtx_unlock(cnvCacheMutex());
umtx_unlock(&cnvCacheMutex);
}
#endif
@@ -1240,7 +1237,7 @@ ucnv_getDefaultName() {
but ucnv_setDefaultName is not thread safe.
*/
{
icu::Mutex lock(cnvCacheMutex());
icu::Mutex lock(&cnvCacheMutex);
name = gDefaultConverterName;
}
if(name==NULL) {
+7 -5
View File
@@ -1107,11 +1107,13 @@ GetUniFromLMBCSUni(char const ** ppLMBCSin) /* Called with LMBCS-style Unicode
all input as required by ICU converter semantics.
*/
#define CHECK_SOURCE_LIMIT(index) \
if (args->source+index > args->sourceLimit){\
*err = U_TRUNCATED_CHAR_FOUND;\
args->source = args->sourceLimit;\
return 0xffff;}
#define CHECK_SOURCE_LIMIT(index) UPRV_BLOCK_MACRO_BEGIN { \
if (args->source+index > args->sourceLimit) { \
*err = U_TRUNCATED_CHAR_FOUND; \
args->source = args->sourceLimit; \
return 0xffff; \
} \
} UPRV_BLOCK_MACRO_END
/* Return the Unicode representation for the current LMBCS character */
+2 -2
View File
@@ -202,14 +202,14 @@ bocu1TrailToByte[BOCU1_TRAIL_CONTROLS_COUNT]={
* @param d Divisor.
* @param m Output variable for the rest (modulo result).
*/
#define NEGDIVMOD(n, d, m) { \
#define NEGDIVMOD(n, d, m) UPRV_BLOCK_MACRO_BEGIN { \
(m)=(n)%(d); \
(n)/=(d); \
if((m)<0) { \
--(n); \
(m)+=(d); \
} \
}
} UPRV_BLOCK_MACRO_END
/* Faster versions of packDiff() for single-byte-encoded diff values. */
+5 -13
View File
@@ -38,7 +38,7 @@
#define ESC_LEN 2
#define CONCAT_ESCAPE_MACRO( args, targetIndex,targetLength,strToAppend, err, len,sourceIndex){ \
#define CONCAT_ESCAPE_MACRO(args, targetIndex,targetLength,strToAppend, err, len,sourceIndex) UPRV_BLOCK_MACRO_BEGIN { \
while(len-->0){ \
if(targetIndex < targetLength){ \
args->target[targetIndex] = (unsigned char) *strToAppend; \
@@ -53,7 +53,7 @@
} \
strToAppend++; \
} \
}
} UPRV_BLOCK_MACRO_END
typedef struct{
@@ -518,19 +518,11 @@ _HZ_WriteSub(UConverterFromUnicodeArgs *args, int32_t offsetIndex, UErrorCode *e
/*
* Structure for cloning an HZ converter into a single memory block.
* ucnv_safeClone() of the HZ converter will align the entire cloneHZStruct,
* and then ucnv_safeClone() of the sub-converter may additionally align
* subCnv inside the cloneHZStruct, for which we need the deadSpace after
* subCnv. This is because UAlignedMemory may be larger than the actually
* necessary alignment size for the platform.
* The other cloneHZStruct fields will not be moved around,
* and are aligned properly with cloneHZStruct's alignment.
*/
struct cloneHZStruct
{
UConverter cnv;
UConverter subCnv;
UAlignedMemory deadSpace;
UConverterDataHZ mydata;
};
@@ -545,12 +537,12 @@ _HZ_SafeClone(const UConverter *cnv,
int32_t size, bufferSizeNeeded = sizeof(struct cloneHZStruct);
if (U_FAILURE(*status)){
return 0;
return nullptr;
}
if (*pBufferSize == 0){ /* 'preflighting' request - set needed size into *pBufferSize */
*pBufferSize = bufferSizeNeeded;
return 0;
return nullptr;
}
localClone = (struct cloneHZStruct *)stackBuffer;
@@ -561,7 +553,7 @@ _HZ_SafeClone(const UConverter *cnv,
localClone->cnv.isExtraLocal = TRUE;
/* deep-clone the sub-converter */
size = (int32_t)(sizeof(UConverter) + sizeof(UAlignedMemory)); /* include size of padding */
size = (int32_t)sizeof(UConverter);
((UConverterDataHZ*)localClone->cnv.extraInfo)->gbConverter =
ucnv_safeClone(((UConverterDataHZ*)cnv->extraInfo)->gbConverter, &localClone->subCnv, &size, status);
+6 -6
View File
@@ -831,7 +831,7 @@ static const uint16_t nuktaSpecialCases[][2]={
};
#define WRITE_TO_TARGET_FROM_U(args,offsets,source,target,targetLimit,targetByteUnit,err){ \
#define WRITE_TO_TARGET_FROM_U(args,offsets,source,target,targetLimit,targetByteUnit,err) UPRV_BLOCK_MACRO_BEGIN { \
int32_t offset = (int32_t)(source - args->source-1); \
/* write the targetUniChar to target */ \
if(target < targetLimit){ \
@@ -884,7 +884,7 @@ static const uint16_t nuktaSpecialCases[][2]={
(uint8_t) (targetByteUnit); \
*err = U_BUFFER_OVERFLOW_ERROR; \
} \
}
} UPRV_BLOCK_MACRO_END
/* Rules:
* Explicit Halant :
@@ -1119,7 +1119,7 @@ static const uint16_t lookupTable[][2]={
{ GURMUKHI, PNJ_MASK }
};
#define WRITE_TO_TARGET_TO_U(args,source,target,offsets,offset,targetUniChar,delta, err){\
#define WRITE_TO_TARGET_TO_U(args,source,target,offsets,offset,targetUniChar,delta, err) UPRV_BLOCK_MACRO_BEGIN { \
/* add offset to current Indic Block */ \
if(targetUniChar>ASCII_END && \
targetUniChar != ZWJ && \
@@ -1140,9 +1140,9 @@ static const uint16_t lookupTable[][2]={
(UChar)targetUniChar; \
*err = U_BUFFER_OVERFLOW_ERROR; \
} \
}
} UPRV_BLOCK_MACRO_END
#define GET_MAPPING(sourceChar,targetUniChar,data){ \
#define GET_MAPPING(sourceChar,targetUniChar,data) UPRV_BLOCK_MACRO_BEGIN { \
targetUniChar = toUnicodeTable[(sourceChar)] ; \
/* is the code point valid in current script? */ \
if(sourceChar> ASCII_END && \
@@ -1153,7 +1153,7 @@ static const uint16_t lookupTable[][2]={
targetUniChar=missingCharMarker; \
} \
} \
}
} UPRV_BLOCK_MACRO_END
/***********
* Rules for ISCII to Unicode converter
+18 -18
View File
@@ -691,36 +691,36 @@ static int16_t countOnes(uint32_t* mask, int32_t len) {
/* internal function! */
static UEnumeration *selectForMask(const UConverterSelector* sel,
uint32_t *mask, UErrorCode *status) {
uint32_t *theMask, UErrorCode *status) {
LocalMemory<uint32_t> mask(theMask);
// this is the context we will use. Store a table of indices to which
// encodings are legit.
struct Enumerator* result = (Enumerator*)uprv_malloc(sizeof(Enumerator));
if (result == NULL) {
uprv_free(mask);
LocalMemory<Enumerator> result(static_cast<Enumerator *>(uprv_malloc(sizeof(Enumerator))));
if (result.isNull()) {
*status = U_MEMORY_ALLOCATION_ERROR;
return NULL;
return nullptr;
}
result->index = NULL; // this will be allocated later!
result->index = nullptr; // this will be allocated later!
result->length = result->cur = 0;
result->sel = sel;
UEnumeration *en = (UEnumeration *)uprv_malloc(sizeof(UEnumeration));
if (en == NULL) {
LocalMemory<UEnumeration> en(static_cast<UEnumeration *>(uprv_malloc(sizeof(UEnumeration))));
if (en.isNull()) {
// TODO(markus): Combine Enumerator and UEnumeration into one struct.
uprv_free(mask);
uprv_free(result);
*status = U_MEMORY_ALLOCATION_ERROR;
return NULL;
return nullptr;
}
memcpy(en, &defaultEncodings, sizeof(UEnumeration));
en->context = result;
memcpy(en.getAlias(), &defaultEncodings, sizeof(UEnumeration));
int32_t columns = (sel->encodingsCount+31)/32;
int16_t numOnes = countOnes(mask, columns);
int16_t numOnes = countOnes(mask.getAlias(), columns);
// now, we know the exact space we need for index
if (numOnes > 0) {
result->index = (int16_t*) uprv_malloc(numOnes * sizeof(int16_t));
result->index = static_cast<int16_t*>(uprv_malloc(numOnes * sizeof(int16_t)));
if (result->index == nullptr) {
*status = U_MEMORY_ALLOCATION_ERROR;
return nullptr;
}
int32_t i, j;
int16_t k = 0;
for (j = 0 ; j < columns; j++) {
@@ -734,8 +734,8 @@ static UEnumeration *selectForMask(const UConverterSelector* sel,
}
} //otherwise, index will remain NULL (and will never be touched by
//the enumerator code anyway)
uprv_free(mask);
return en;
en->context = result.orphan();
return en.orphan();
}
/* check a string against the selector - UTF16 version */
+1 -1
View File
@@ -280,7 +280,7 @@ UChar32 getRange(const void *t, UChar32 start,
int32_t prevI3Block = -1;
int32_t prevBlock = -1;
UChar32 c = start;
uint32_t trieValue, value;
uint32_t trieValue, value = nullValue;
bool haveValue = false;
do {
int32_t i3Block;
+18 -23
View File
@@ -365,10 +365,7 @@ U_CDECL_END
#if !UCONFIG_NO_SERVICE
struct CReg;
static UMutex *gCRegLock() {
static UMutex m = U_MUTEX_INITIALIZER;
return &m;
}
static UMutex gCRegLock;
static CReg* gCRegHead = 0;
struct CReg : public icu::UMemory {
@@ -394,14 +391,14 @@ struct CReg : public icu::UMemory {
if (status && U_SUCCESS(*status) && _iso && _id) {
CReg* n = new CReg(_iso, _id);
if (n) {
umtx_lock(gCRegLock());
umtx_lock(&gCRegLock);
if (!gCRegHead) {
/* register for the first time */
ucln_common_registerCleanup(UCLN_COMMON_CURRENCY, currency_cleanup);
}
n->next = gCRegHead;
gCRegHead = n;
umtx_unlock(gCRegLock());
umtx_unlock(&gCRegLock);
return n;
}
*status = U_MEMORY_ALLOCATION_ERROR;
@@ -411,7 +408,7 @@ struct CReg : public icu::UMemory {
static UBool unreg(UCurrRegistryKey key) {
UBool found = FALSE;
umtx_lock(gCRegLock());
umtx_lock(&gCRegLock);
CReg** p = &gCRegHead;
while (*p) {
@@ -424,13 +421,13 @@ struct CReg : public icu::UMemory {
p = &((*p)->next);
}
umtx_unlock(gCRegLock());
umtx_unlock(&gCRegLock);
return found;
}
static const UChar* get(const char* id) {
const UChar* result = NULL;
umtx_lock(gCRegLock());
umtx_lock(&gCRegLock);
CReg* p = gCRegHead;
/* register cleanup of the mutex */
@@ -442,7 +439,7 @@ struct CReg : public icu::UMemory {
}
p = p->next;
}
umtx_unlock(gCRegLock());
umtx_unlock(&gCRegLock);
return result;
}
@@ -716,7 +713,9 @@ ucurr_getName(const UChar* currency,
// We no longer support choice format data in names. Data should not contain
// choice patterns.
*isChoiceFormat = FALSE;
if (isChoiceFormat != NULL) {
*isChoiceFormat = FALSE;
}
if (U_SUCCESS(ec2)) {
U_ASSERT(s != NULL);
return s;
@@ -1356,10 +1355,7 @@ static CurrencyNameCacheEntry* currCache[CURRENCY_NAME_CACHE_NUM] = {NULL};
// It is a simple round-robin replacement strategy.
static int8_t currentCacheEntryIndex = 0;
static UMutex *gCurrencyCacheMutex() {
static UMutex m = U_MUTEX_INITIALIZER;
return &m;
}
static UMutex gCurrencyCacheMutex;
// Cache deletion
static void
@@ -1408,7 +1404,7 @@ getCacheEntry(const char* locale, UErrorCode& ec) {
CurrencyNameStruct* currencySymbols = NULL;
CurrencyNameCacheEntry* cacheEntry = NULL;
umtx_lock(gCurrencyCacheMutex());
umtx_lock(&gCurrencyCacheMutex);
// in order to handle racing correctly,
// not putting 'search' in a separate function.
int8_t found = -1;
@@ -1423,13 +1419,13 @@ getCacheEntry(const char* locale, UErrorCode& ec) {
cacheEntry = currCache[found];
++(cacheEntry->refCount);
}
umtx_unlock(gCurrencyCacheMutex());
umtx_unlock(&gCurrencyCacheMutex);
if (found == -1) {
collectCurrencyNames(locale, &currencyNames, &total_currency_name_count, &currencySymbols, &total_currency_symbol_count, ec);
if (U_FAILURE(ec)) {
return NULL;
}
umtx_lock(gCurrencyCacheMutex());
umtx_lock(&gCurrencyCacheMutex);
// check again.
for (int8_t i = 0; i < CURRENCY_NAME_CACHE_NUM; ++i) {
if (currCache[i]!= NULL &&
@@ -1468,19 +1464,19 @@ getCacheEntry(const char* locale, UErrorCode& ec) {
cacheEntry = currCache[found];
++(cacheEntry->refCount);
}
umtx_unlock(gCurrencyCacheMutex());
umtx_unlock(&gCurrencyCacheMutex);
}
return cacheEntry;
}
static void releaseCacheEntry(CurrencyNameCacheEntry* cacheEntry) {
umtx_lock(gCurrencyCacheMutex());
umtx_lock(&gCurrencyCacheMutex);
--(cacheEntry->refCount);
if (cacheEntry->refCount == 0) { // remove
deleteCacheEntry(cacheEntry);
}
umtx_unlock(gCurrencyCacheMutex());
umtx_unlock(&gCurrencyCacheMutex);
}
U_CAPI void
@@ -1601,10 +1597,9 @@ uprv_getStaticCurrencyName(const UChar* iso, const char* loc,
{
U_NAMESPACE_USE
UBool isChoiceFormat;
int32_t len;
const UChar* currname = ucurr_getName(iso, loc, UCURR_SYMBOL_NAME,
&isChoiceFormat, &len, &ec);
nullptr /* isChoiceFormat */, &len, &ec);
if (U_SUCCESS(ec)) {
result.setTo(currname, len);
}
+26 -19
View File
@@ -33,6 +33,7 @@ might have to #include some other header
#include "cstring.h"
#include "mutex.h"
#include "putilimp.h"
#include "restrace.h"
#include "uassert.h"
#include "ucln_cmn.h"
#include "ucmndata.h"
@@ -110,11 +111,12 @@ static u_atomic_int32_t gHaveTriedToLoadCommonData = ATOMIC_INT32_T_INITIALIZER(
static UHashtable *gCommonDataCache = NULL; /* Global hash table of opened ICU data files. */
static icu::UInitOnce gCommonDataCacheInitOnce = U_INITONCE_INITIALIZER;
#if U_PLATFORM_HAS_WINUWP_API == 0
#if !defined(ICU_DATA_DIR_WINDOWS)
static UDataFileAccess gDataFileAccess = UDATA_DEFAULT_ACCESS; // Access not synchronized.
// Modifying is documented as thread-unsafe.
#else
static UDataFileAccess gDataFileAccess = UDATA_NO_FILES; // Windows UWP looks in one spot explicitly
// If we are using the Windows data directory, then look in one spot only.
static UDataFileAccess gDataFileAccess = UDATA_NO_FILES;
#endif
static UBool U_CALLCONV
@@ -206,7 +208,7 @@ setCommonICUData(UDataMemory *pData, /* The new common data. Belongs to ca
return didUpdate;
}
#if U_PLATFORM_HAS_WINUWP_API == 0
#if !defined(ICU_DATA_DIR_WINDOWS)
static UBool
setCommonICUDataPointer(const void *pData, UBool /*warn*/, UErrorCode *pErrorCode) {
@@ -320,7 +322,7 @@ static UDataMemory *udata_findCachedData(const char *path, UErrorCode &err)
retVal = el->item;
}
#ifdef UDATA_DEBUG
fprintf(stderr, "Cache: [%s] -> %p\n", baseName, retVal);
fprintf(stderr, "Cache: [%s] -> %p\n", baseName, (void*) retVal);
#endif
return retVal;
}
@@ -383,7 +385,7 @@ static UDataMemory *udata_cacheDataItem(const char *path, UDataMemory *item, UEr
#ifdef UDATA_DEBUG
fprintf(stderr, "Cache: [%s] <<< %p : %s. vFunc=%p\n", newElement->name,
newElement->item, u_errorName(subErr), newElement->item->vFuncs);
(void*) newElement->item, u_errorName(subErr), (void*) newElement->item->vFuncs);
#endif
if (subErr == U_USING_DEFAULT_WARNING || U_FAILURE(subErr)) {
@@ -477,7 +479,7 @@ UDataPathIterator::UDataPathIterator(const char *inPath, const char *pkg,
nextPath = itemPath.data();
}
#ifdef UDATA_DEBUG
fprintf(stderr, "SUFFIX=%s [%p]\n", inSuffix, inSuffix);
fprintf(stderr, "SUFFIX=%s [%p]\n", inSuffix, (void*) inSuffix);
#endif
/** Suffix **/
@@ -492,12 +494,11 @@ UDataPathIterator::UDataPathIterator(const char *inPath, const char *pkg,
/* pathBuffer will hold the output path strings returned by this iterator */
#ifdef UDATA_DEBUG
fprintf(stderr, "%p: init %s -> [path=%s], [base=%s], [suff=%s], [itempath=%s], [nextpath=%s], [checklast4=%s]\n",
iter,
fprintf(stderr, "0: init %s -> [path=%s], [base=%s], [suff=%s], [itempath=%s], [nextpath=%s], [checklast4=%s]\n",
item,
path,
basename,
suffix,
suffix.data(),
itemPath.data(),
nextPath,
checkLastFour?"TRUE":"false");
@@ -553,7 +554,7 @@ const char *UDataPathIterator::next(UErrorCode *pErrorCode)
fprintf(stderr, "rest of path (IDD) = %s\n", currentPath);
fprintf(stderr, " ");
{
uint32_t qqq;
int32_t qqq;
for(qqq=0;qqq<pathLen;qqq++)
{
fprintf(stderr, " ");
@@ -574,7 +575,7 @@ const char *UDataPathIterator::next(UErrorCode *pErrorCode)
uprv_strlen(pathBasename)==(basenameLen+4)) { /* base+suffix = full len */
#ifdef UDATA_DEBUG
fprintf(stderr, "Have %s file on the path: %s\n", suffix, pathBuffer.data());
fprintf(stderr, "Have %s file on the path: %s\n", suffix.data(), pathBuffer.data());
#endif
/* do nothing */
}
@@ -640,7 +641,8 @@ U_NAMESPACE_END
* our common data. *
* *
*----------------------------------------------------------------------*/
#if U_PLATFORM_HAS_WINUWP_API == 0 // Windows UWP Platform does not support dll icu data at this time
#if !defined(ICU_DATA_DIR_WINDOWS)
// When using the Windows system data, we expect only a single data file.
extern "C" const DataHeader U_DATA_API U_ICUDATA_ENTRY_POINT;
#endif
@@ -690,7 +692,8 @@ openCommonData(const char *path, /* Path from OpenChoice? */
if(gCommonICUDataArray[commonDataIndex] != NULL) {
return gCommonICUDataArray[commonDataIndex];
}
#if U_PLATFORM_HAS_WINUWP_API == 0 // Windows UWP Platform does not support dll icu data at this time
#if !defined(ICU_DATA_DIR_WINDOWS)
// When using the Windows system data, we expect only a single data file.
int32_t i;
for(i = 0; i < commonDataIndex; ++i) {
if(gCommonICUDataArray[i]->pHeader == &U_ICUDATA_ENTRY_POINT) {
@@ -714,7 +717,8 @@ openCommonData(const char *path, /* Path from OpenChoice? */
setCommonICUDataPointer(uprv_getICUData_conversion(), FALSE, pErrorCode);
}
*/
#if U_PLATFORM_HAS_WINUWP_API == 0 // Windows UWP Platform does not support dll icu data at this time
#if !defined(ICU_DATA_DIR_WINDOWS)
// When using the Windows system data, we expect only a single data file.
setCommonICUDataPointer(&U_ICUDATA_ENTRY_POINT, FALSE, pErrorCode);
{
Mutex lock;
@@ -831,7 +835,7 @@ static UBool extendICUData(UErrorCode *pErr)
* Use a specific mutex to avoid nested locks of the global mutex.
*/
#if MAP_IMPLEMENTATION==MAP_STDIO
static UMutex extendICUDataMutex = U_MUTEX_INITIALIZER;
static UMutex extendICUDataMutex;
umtx_lock(&extendICUDataMutex);
#endif
if(!umtx_loadAcquire(gHaveTriedToLoadCommonData)) {
@@ -1070,13 +1074,13 @@ static UDataMemory *doLoadFromCommonData(UBool isICUData, const char * /*pkgName
/* look up the data piece in the common data */
pHeader=pCommonData->vFuncs->Lookup(pCommonData, tocEntryName, &length, subErrorCode);
#ifdef UDATA_DEBUG
fprintf(stderr, "%s: pHeader=%p - %s\n", tocEntryName, pHeader, u_errorName(*subErrorCode));
fprintf(stderr, "%s: pHeader=%p - %s\n", tocEntryName, (void*) pHeader, u_errorName(*subErrorCode));
#endif
if(pHeader!=NULL) {
pEntryData = checkDataItem(pHeader, isAcceptable, context, type, name, subErrorCode, pErrorCode);
#ifdef UDATA_DEBUG
fprintf(stderr, "pEntryData=%p\n", pEntryData);
fprintf(stderr, "pEntryData=%p\n", (void*) pEntryData);
#endif
if (U_FAILURE(*pErrorCode)) {
return NULL;
@@ -1168,6 +1172,9 @@ doOpenChoice(const char *path, const char *type, const char *name,
UBool isICUData = FALSE;
FileTracer::traceOpen(path, type, name);
/* Is this path ICU data? */
if(path == NULL ||
!strcmp(path, U_ICUDATA_ALIAS) || /* "ICUDATA" */
@@ -1276,12 +1283,12 @@ doOpenChoice(const char *path, const char *type, const char *name,
fprintf(stderr, " tocEntryPath = %s\n", tocEntryName.data());
#endif
#if U_PLATFORM_HAS_WINUWP_API == 0 // Windows UWP Platform does not support dll icu data at this time
#if !defined(ICU_DATA_DIR_WINDOWS)
if(path == NULL) {
path = COMMON_DATA_NAME; /* "icudt26e" */
}
#else
// Windows UWP expects only a single data file.
// When using the Windows system data, we expects only a single data file.
path = COMMON_DATA_NAME; /* "icudt26e" */
#endif
+8 -7
View File
@@ -119,13 +119,14 @@ static const float RESIZE_POLICY_RATIO_TABLE[6] = {
/* This macro expects a UHashTok.pointer as its keypointer and
valuepointer parameters */
#define HASH_DELETE_KEY_VALUE(hash, keypointer, valuepointer) \
if (hash->keyDeleter != NULL && keypointer != NULL) { \
(*hash->keyDeleter)(keypointer); \
} \
if (hash->valueDeleter != NULL && valuepointer != NULL) { \
(*hash->valueDeleter)(valuepointer); \
}
#define HASH_DELETE_KEY_VALUE(hash, keypointer, valuepointer) UPRV_BLOCK_MACRO_BEGIN { \
if (hash->keyDeleter != NULL && keypointer != NULL) { \
(*hash->keyDeleter)(keypointer); \
} \
if (hash->valueDeleter != NULL && valuepointer != NULL) { \
(*hash->valueDeleter)(valuepointer); \
} \
} UPRV_BLOCK_MACRO_END
/*
* Constants for hinting whether a key or value is an integer
+3 -4
View File
@@ -57,18 +57,16 @@ toASCIILower(UChar ch){
inline static UBool
startsWithPrefix(const UChar* src , int32_t srcLength){
UBool startsWithPrefix = TRUE;
if(srcLength < ACE_PREFIX_LENGTH){
return FALSE;
}
for(int8_t i=0; i< ACE_PREFIX_LENGTH; i++){
if(toASCIILower(src[i]) != ACE_PREFIX[i]){
startsWithPrefix = FALSE;
return FALSE;
}
}
return startsWithPrefix;
return TRUE;
}
@@ -441,6 +439,7 @@ _internal_toUnicode(const UChar* src, int32_t srcLength,
for(int32_t j=0; j<srcLength; j++){
if(src[j]> 0x7f){
srcIsASCII = FALSE;
break;
}/*else if(isLDHChar(src[j])==FALSE){
// here we do not assemble surrogates
// since we know that LDH code points
+14 -1
View File
@@ -207,7 +207,8 @@ u_UCharsToChars(const UChar *us, char *cs, int32_t length) {
while(length>0) {
u=*us++;
if(!UCHAR_IS_INVARIANT(u)) {
UPRV_UNREACHABLE; /* Variant characters were used. These are not portable in ICU. */
U_ASSERT(FALSE); /* Variant characters were used. These are not portable in ICU. */
u=0;
}
*cs++=(char)UCHAR_TO_CHAR(u);
--length;
@@ -445,6 +446,13 @@ uprv_copyEbcdic(const UDataSwapper *ds,
return length;
}
U_CFUNC UBool
uprv_isEbcdicAtSign(char c) {
static const uint8_t ebcdicAtSigns[] = {
0x7C, 0x44, 0x66, 0x80, 0xAC, 0xAE, 0xAF, 0xB5, 0xEC, 0xEF, 0x00 };
return c != 0 && uprv_strchr((const char *)ebcdicAtSigns, c) != nullptr;
}
/* compare invariant strings; variant characters compare less than others and unlike each other */
U_CFUNC int32_t
uprv_compareInvAscii(const UDataSwapper *ds,
@@ -561,6 +569,11 @@ uprv_compareInvEbcdicAsAscii(const char *s1, const char *s2) {
}
}
U_CAPI char U_EXPORT2
uprv_ebcdicToAscii(char c) {
return (char)asciiFromEbcdic[(uint8_t)c];
}
U_CAPI char U_EXPORT2
uprv_ebcdicToLowercaseAscii(char c) {
return (char)lowercaseAsciiFromEbcdic[(uint8_t)c];
+89
View File
@@ -68,6 +68,75 @@ uprv_isInvariantUString(const UChar *s, int32_t length);
# error Unknown charset family!
#endif
#ifdef __cplusplus
U_NAMESPACE_BEGIN
/**
* Like U_UPPER_ORDINAL(x) but with validation.
* Returns 0..25 for A..Z else a value outside 0..25.
*/
inline int32_t uprv_upperOrdinal(int32_t c) {
#if U_CHARSET_FAMILY==U_ASCII_FAMILY
return c - 'A';
#elif U_CHARSET_FAMILY==U_EBCDIC_FAMILY
// EBCDIC: A-Z (26 letters) is split into three ranges A-I (9 letters), J-R (9), S-Z (8).
// https://en.wikipedia.org/wiki/EBCDIC_037#Codepage_layout
if (c <= 'I') { return c - 'A'; } // A-I --> 0-8
if (c < 'J') { return -1; }
if (c <= 'R') { return c - 'J' + 9; } // J-R --> 9..17
if (c < 'S') { return -1; }
return c - 'S' + 18; // S-Z --> 18..25
#else
# error Unknown charset family!
#endif
}
// Like U_UPPER_ORDINAL(x) but for lowercase and with validation.
// Returns 0..25 for a..z else a value outside 0..25.
inline int32_t uprv_lowerOrdinal(int32_t c) {
#if U_CHARSET_FAMILY==U_ASCII_FAMILY
return c - 'a';
#elif U_CHARSET_FAMILY==U_EBCDIC_FAMILY
// EBCDIC: a-z (26 letters) is split into three ranges a-i (9 letters), j-r (9), s-z (8).
// https://en.wikipedia.org/wiki/EBCDIC_037#Codepage_layout
if (c <= 'i') { return c - 'a'; } // a-i --> 0-8
if (c < 'j') { return -1; }
if (c <= 'r') { return c - 'j' + 9; } // j-r --> 9..17
if (c < 's') { return -1; }
return c - 's' + 18; // s-z --> 18..25
#else
# error Unknown charset family!
#endif
}
U_NAMESPACE_END
#endif
/**
* Returns true if c == '@' is possible.
* The @ sign is variant, and the @ sign used on one
* EBCDIC machine won't be compiled the same way on other EBCDIC based machines.
* @internal
*/
U_CFUNC UBool
uprv_isEbcdicAtSign(char c);
/**
* \def uprv_isAtSign
* Returns true if c == '@' is possible.
* For ASCII, checks for exactly '@'. For EBCDIC, calls uprv_isEbcdicAtSign().
* @internal
*/
#if U_CHARSET_FAMILY==U_ASCII_FAMILY
# define uprv_isAtSign(c) ((c)=='@')
#elif U_CHARSET_FAMILY==U_EBCDIC_FAMILY
# define uprv_isAtSign(c) uprv_isEbcdicAtSign(c)
#else
# error Unknown charset family!
#endif
/**
* Compare two EBCDIC invariant-character strings in ASCII order.
* @internal
@@ -88,6 +157,26 @@ uprv_compareInvEbcdicAsAscii(const char *s1, const char *s2);
# error Unknown charset family!
#endif
/**
* Converts an EBCDIC invariant character to ASCII.
* @internal
*/
U_INTERNAL char U_EXPORT2
uprv_ebcdicToAscii(char c);
/**
* \def uprv_invCharToAscii
* Converts an invariant character to ASCII.
* @internal
*/
#if U_CHARSET_FAMILY==U_ASCII_FAMILY
# define uprv_invCharToAscii(c) (c)
#elif U_CHARSET_FAMILY==U_EBCDIC_FAMILY
# define uprv_invCharToAscii(c) uprv_ebcdicToAscii(c)
#else
# error Unknown charset family!
#endif
/**
* Converts an EBCDIC invariant character to lowercase ASCII.
* @internal
+27 -26
View File
@@ -148,7 +148,8 @@ static const char * const LANGUAGES[] = {
"mad", "maf", "mag", "mai", "mak", "man", "mas", "mde",
"mdf", "mdh", "mdr", "men", "mer", "mfe", "mg", "mga",
"mgh", "mgo", "mh", "mi", "mic", "min", "mis", "mk",
"ml", "mn", "mnc", "mni", "moh", "mos", "mr", "mrj",
"ml", "mn", "mnc", "mni", "mo",
"moh", "mos", "mr", "mrj",
"ms", "mt", "mua", "mul", "mus", "mwl", "mwr", "mwv",
"my", "mye", "myv", "mzn",
"na", "nan", "nap", "naq", "nb", "nd", "nds", "ne",
@@ -264,7 +265,8 @@ static const char * const LANGUAGES_3[] = {
"mad", "maf", "mag", "mai", "mak", "man", "mas", "mde",
"mdf", "mdh", "mdr", "men", "mer", "mfe", "mlg", "mga",
"mgh", "mgo", "mah", "mri", "mic", "min", "mis", "mkd",
"mal", "mon", "mnc", "mni", "moh", "mos", "mar", "mrj",
"mal", "mon", "mnc", "mni", "mol",
"moh", "mos", "mar", "mrj",
"msa", "mlt", "mua", "mul", "mus", "mwl", "mwr", "mwv",
"mya", "mye", "myv", "mzn",
"nau", "nan", "nap", "naq", "nob", "nde", "nds", "nep",
@@ -480,14 +482,15 @@ static const CanonicalizationMap CANONICALIZE_MAP[] = {
/* Test if the locale id has BCP47 u extension and does not have '@' */
#define _hasBCP47Extension(id) (id && uprv_strstr(id, "@") == NULL && getShortestSubtagLength(localeID) == 1)
/* Converts the BCP47 id to Unicode id. Does nothing to id if conversion fails */
#define _ConvertBCP47(finalID, id, buffer, length,err) \
if (uloc_forLanguageTag(id, buffer, length, NULL, err) <= 0 || \
U_FAILURE(*err) || *err == U_STRING_NOT_TERMINATED_WARNING) { \
finalID=id; \
if (*err == U_STRING_NOT_TERMINATED_WARNING) { *err = U_BUFFER_OVERFLOW_ERROR; } \
} else { \
finalID=buffer; \
}
#define _ConvertBCP47(finalID, id, buffer, length,err) UPRV_BLOCK_MACRO_BEGIN { \
if (uloc_forLanguageTag(id, buffer, length, NULL, err) <= 0 || \
U_FAILURE(*err) || *err == U_STRING_NOT_TERMINATED_WARNING) { \
finalID=id; \
if (*err == U_STRING_NOT_TERMINATED_WARNING) { *err = U_BUFFER_OVERFLOW_ERROR; } \
} else { \
finalID=buffer; \
} \
} UPRV_BLOCK_MACRO_END
/* Gets the size of the shortest subtag in the given localeID. */
static int32_t getShortestSubtagLength(const char *localeID) {
int32_t localeIDLength = static_cast<int32_t>(uprv_strlen(localeID));
@@ -1454,31 +1457,29 @@ static const UEnumeration gKeywordsEnum = {
U_CAPI UEnumeration* U_EXPORT2
uloc_openKeywordList(const char *keywordList, int32_t keywordListSize, UErrorCode* status)
{
UKeywordsContext *myContext = NULL;
UEnumeration *result = NULL;
LocalMemory<UKeywordsContext> myContext;
LocalMemory<UEnumeration> result;
if(U_FAILURE(*status)) {
return NULL;
if (U_FAILURE(*status)) {
return nullptr;
}
result = (UEnumeration *)uprv_malloc(sizeof(UEnumeration));
/* Null pointer test */
if (result == NULL) {
myContext.adoptInstead(static_cast<UKeywordsContext *>(uprv_malloc(sizeof(UKeywordsContext))));
result.adoptInstead(static_cast<UEnumeration *>(uprv_malloc(sizeof(UEnumeration))));
if (myContext.isNull() || result.isNull()) {
*status = U_MEMORY_ALLOCATION_ERROR;
return NULL;
return nullptr;
}
uprv_memcpy(result, &gKeywordsEnum, sizeof(UEnumeration));
myContext = static_cast<UKeywordsContext *>(uprv_malloc(sizeof(UKeywordsContext)));
if (myContext == NULL) {
uprv_memcpy(result.getAlias(), &gKeywordsEnum, sizeof(UEnumeration));
myContext->keywords = static_cast<char *>(uprv_malloc(keywordListSize+1));
if (myContext->keywords == nullptr) {
*status = U_MEMORY_ALLOCATION_ERROR;
uprv_free(result);
return NULL;
return nullptr;
}
myContext->keywords = (char *)uprv_malloc(keywordListSize+1);
uprv_memcpy(myContext->keywords, keywordList, keywordListSize);
myContext->keywords[keywordListSize] = 0;
myContext->current = myContext->keywords;
result->context = myContext;
return result;
result->context = myContext.orphan();
return result.orphan();
}
U_CAPI UEnumeration* U_EXPORT2
+2 -4
View File
@@ -1558,10 +1558,8 @@ _appendLDMLExtensionAsKeywords(const char* ldmlext, ExtensionListEntry** appendT
return;
}
if (!_addAttributeToList(&attrFirst, attr)) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
// duplicate attribute is ignored, causes no error.
_addAttributeToList(&attrFirst, attr);
/* next tag */
pTag += len;
+74 -50
View File
@@ -24,6 +24,7 @@
#include "unicode/utypes.h"
#include "uassert.h"
#include "ucln_cmn.h"
#include "cmemory.h"
U_NAMESPACE_BEGIN
@@ -35,24 +36,84 @@ U_NAMESPACE_BEGIN
#error U_USER_MUTEX_CPP not supported
#endif
/*************************************************************************************************
*
* ICU Mutex wrappers.
*
*************************************************************************************************/
// The ICU global mutex. Used when ICU implementation code passes NULL for the mutex pointer.
static UMutex *globalMutex() {
static UMutex m = U_MUTEX_INITIALIZER;
return &m;
namespace {
std::mutex *initMutex;
std::condition_variable *initCondition;
// The ICU global mutex.
// Used when ICU implementation code passes nullptr for the mutex pointer.
UMutex globalMutex;
std::once_flag initFlag;
std::once_flag *pInitFlag = &initFlag;
} // Anonymous namespace
U_CDECL_BEGIN
static UBool U_CALLCONV umtx_cleanup() {
initMutex->~mutex();
initCondition->~condition_variable();
UMutex::cleanup();
// Reset the once_flag, by destructing it and creating a fresh one in its place.
// Do not use this trick anywhere else in ICU; use umtx_initOnce, not std::call_once().
pInitFlag->~once_flag();
pInitFlag = new(&initFlag) std::once_flag();
return true;
}
static void U_CALLCONV umtx_init() {
initMutex = STATIC_NEW(std::mutex);
initCondition = STATIC_NEW(std::condition_variable);
ucln_common_registerCleanup(UCLN_COMMON_MUTEX, umtx_cleanup);
}
U_CDECL_END
std::mutex *UMutex::getMutex() {
std::mutex *retPtr = fMutex.load(std::memory_order_acquire);
if (retPtr == nullptr) {
std::call_once(*pInitFlag, umtx_init);
std::lock_guard<std::mutex> guard(*initMutex);
retPtr = fMutex.load(std::memory_order_acquire);
if (retPtr == nullptr) {
fMutex = new(fStorage) std::mutex();
retPtr = fMutex;
fListLink = gListHead;
gListHead = this;
}
}
U_ASSERT(retPtr != nullptr);
return retPtr;
}
UMutex *UMutex::gListHead = nullptr;
void UMutex::cleanup() {
UMutex *next = nullptr;
for (UMutex *m = gListHead; m != nullptr; m = next) {
(*m->fMutex).~mutex();
m->fMutex = nullptr;
next = m->fListLink;
m->fListLink = nullptr;
}
gListHead = nullptr;
}
U_CAPI void U_EXPORT2
umtx_lock(UMutex *mutex) {
if (mutex == nullptr) {
mutex = globalMutex();
mutex = &globalMutex;
}
mutex->fMutex.lock();
mutex->lock();
}
@@ -60,35 +121,9 @@ U_CAPI void U_EXPORT2
umtx_unlock(UMutex* mutex)
{
if (mutex == nullptr) {
mutex = globalMutex();
mutex = &globalMutex;
}
mutex->fMutex.unlock();
}
UConditionVar::UConditionVar() : fCV() {
}
UConditionVar::~UConditionVar() {
}
U_CAPI void U_EXPORT2
umtx_condWait(UConditionVar *cond, UMutex *mutex) {
if (mutex == nullptr) {
mutex = globalMutex();
}
cond->fCV.wait(mutex->fMutex);
}
U_CAPI void U_EXPORT2
umtx_condBroadcast(UConditionVar *cond) {
cond->fCV.notify_all();
}
U_CAPI void U_EXPORT2
umtx_condSignal(UConditionVar *cond) {
cond->fCV.notify_one();
mutex->unlock();
}
@@ -98,17 +133,6 @@ umtx_condSignal(UConditionVar *cond) {
*
*************************************************************************************************/
static std::mutex &initMutex() {
static std::mutex m;
return m;
}
static std::condition_variable &initCondition() {
static std::condition_variable cv;
return cv;
}
// This function is called when a test of a UInitOnce::fState reveals that
// initialization has not completed, that we either need to call the init
// function on this thread, or wait for some other thread to complete.
@@ -119,8 +143,8 @@ static std::condition_variable &initCondition() {
//
U_COMMON_API UBool U_EXPORT2
umtx_initImplPreInit(UInitOnce &uio) {
std::unique_lock<std::mutex> lock(initMutex());
std::call_once(*pInitFlag, umtx_init);
std::unique_lock<std::mutex> lock(*initMutex);
if (umtx_loadAcquire(uio.fState) == 0) {
umtx_storeRelease(uio.fState, 1);
return true; // Caller will next call the init function.
@@ -128,7 +152,7 @@ umtx_initImplPreInit(UInitOnce &uio) {
while (umtx_loadAcquire(uio.fState) == 1) {
// Another thread is currently running the initialization.
// Wait until it completes.
initCondition().wait(lock);
initCondition->wait(lock);
}
U_ASSERT(uio.fState == 2);
return false;
@@ -145,10 +169,10 @@ umtx_initImplPreInit(UInitOnce &uio) {
U_COMMON_API void U_EXPORT2
umtx_initImplPostInit(UInitOnce &uio) {
{
std::unique_lock<std::mutex> lock(initMutex());
std::unique_lock<std::mutex> lock(*initMutex);
umtx_storeRelease(uio.fState, 2);
}
initCondition().notify_all();
initCondition->notify_all();
}
U_NAMESPACE_END
+67 -58
View File
@@ -23,6 +23,7 @@
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <type_traits>
#include "unicode/utypes.h"
#include "unicode/uclean.h"
@@ -36,10 +37,11 @@
#error U_USER_ATOMICS and U_USER_MUTEX_H are not supported
#endif
// Export an explicit template instantiation of std::atomic<int32_t>.
// When building DLLs for Windows this is required as it is used as a data member of the exported SharedObject class.
// See digitlst.h, pluralaffix.h, datefmt.h, and others for similar examples.
//
// Similar story for std::atomic<std::mutex *>, and the exported UMutex class.
#if U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN && !defined(U_IN_DOXYGEN)
#if defined(__clang__) || defined(_MSC_VER)
#if defined(__clang__)
@@ -48,12 +50,14 @@
#pragma clang diagnostic ignored "-Winstantiation-after-specialization"
#endif
template struct U_COMMON_API std::atomic<int32_t>;
template struct U_COMMON_API std::atomic<std::mutex *>;
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#elif defined(__GNUC__)
// For GCC this class is already exported/visible, so no need for U_COMMON_API.
template struct std::atomic<int32_t>;
template struct std::atomic<std::mutex *>;
#endif
#endif
@@ -180,50 +184,79 @@ template<class T> void umtx_initOnce(UInitOnce &uio, void (U_CALLCONV *fp)(T, UE
}
}
// UMutex should be constexpr-constructible, so that no initialization code
// is run during startup.
// This works on all C++ libraries except MS VS before VS2019.
#if (defined(_CPPLIB_VER) && !defined(_MSVC_STL_VERSION)) || \
(defined(_MSVC_STL_VERSION) && _MSVC_STL_VERSION < 142)
// (VS std lib older than VS2017) || (VS std lib version < VS2019)
# define UMUTEX_CONSTEXPR
#else
# define UMUTEX_CONSTEXPR constexpr
#endif
/*************************************************************************************************
/**
* UMutex - ICU Mutex class.
*
* ICU Mutex wrappers. Originally wrapped operating system mutexes, giving the rest of ICU a
* platform independent set of mutex operations. Now vestigial, wrapping std::mutex only.
* For internal ICU use only.
* This is the preferred Mutex class for use within ICU implementation code.
* It is a thin wrapper over C++ std::mutex, with these additions:
* - Static instances are safe, not triggering static construction or destruction,
* and the associated order of construction or destruction issues.
* - Plumbed into u_cleanup() for destructing the underlying std::mutex,
* which frees any OS level resources they may be holding.
*
*************************************************************************************************/
* Limitations:
* - Static or global instances only. Cannot be heap allocated. Cannot appear as a
* member of another class.
* - No condition variables or other advanced features. If needed, you will need to use
* std::mutex and std::condition_variable directly. For an example, see unifiedcache.cpp
*
* Typical Usage:
* static UMutex myMutex;
*
* {
* Mutex lock(myMutex);
* ... // Do stuff that is protected by myMutex;
* } // myMutex is released when lock goes out of scope.
*/
struct UMutex : public icu::UMemory {
UMutex() = default;
class U_COMMON_API UMutex {
public:
UMUTEX_CONSTEXPR UMutex() {}
~UMutex() = default;
UMutex(const UMutex &other) = delete;
UMutex &operator =(const UMutex &other) = delete;
void *operator new(size_t) = delete;
std::mutex fMutex = {}; // Note: struct - pubic members - because most access is from
// // plain C style functions (umtx_lock(), etc.)
// requirements for C++ BasicLockable, allows UMutex to work with std::lock_guard
void lock() {
std::mutex *m = fMutex.load(std::memory_order_acquire);
if (m == nullptr) { m = getMutex(); }
m->lock();
}
void unlock() { fMutex.load(std::memory_order_relaxed)->unlock(); }
static void cleanup();
private:
alignas(std::mutex) char fStorage[sizeof(std::mutex)] {};
std::atomic<std::mutex *> fMutex { nullptr };
/** All initialized UMutexes are kept in a linked list, so that they can be found,
* and the underlying std::mutex destructed, by u_cleanup().
*/
UMutex *fListLink { nullptr };
static UMutex *gListHead;
/** Out-of-line function to lazily initialize a UMutex on first use.
* Initial fast check is inline, in lock(). The returned value may never
* be nullptr.
*/
std::mutex *getMutex();
};
struct UConditionVar : public icu::UMemory {
U_COMMON_API UConditionVar();
U_COMMON_API ~UConditionVar();
UConditionVar(const UConditionVar &other) = delete;
UConditionVar &operator =(const UConditionVar &other) = delete;
std::condition_variable_any fCV;
};
#define U_MUTEX_INITIALIZER {}
#define U_CONDITION_INITIALIZER {}
// Implementation notes for UConditionVar:
//
// Use an out-of-line constructor to reduce problems with the ICU dependency checker.
// On Linux, the default constructor of std::condition_variable_any
// produces an in-line reference to global operator new(), which the
// dependency checker flags for any file that declares a UConditionVar. With
// an out-of-line constructor, the dependency is constrained to umutex.o
//
// Do not export (U_COMMON_API) the entire class, but only the constructor
// and destructor, to avoid Windows build problems with attempting to export the
// std::condition_variable_any.
/* Lock a mutex.
* @param mutex The given mutex to be locked. Pass NULL to specify
* the global ICU mutex. Recursive locks are an error
@@ -237,30 +270,6 @@ U_INTERNAL void U_EXPORT2 umtx_lock(UMutex* mutex);
*/
U_INTERNAL void U_EXPORT2 umtx_unlock (UMutex* mutex);
/*
* Wait on a condition variable.
* The calling thread will unlock the mutex and wait on the condition variable.
* The mutex must be locked by the calling thread when invoking this function.
*
* @param cond the condition variable to wait on.
* @param mutex the associated mutex.
*/
U_INTERNAL void U_EXPORT2 umtx_condWait(UConditionVar *cond, UMutex *mutex);
/*
* Broadcast wakeup of all threads waiting on a Condition.
*
* @param cond the condition variable.
*/
U_INTERNAL void U_EXPORT2 umtx_condBroadcast(UConditionVar *cond);
/*
* Signal a condition variable, waking up one waiting thread.
*/
U_INTERNAL void U_EXPORT2 umtx_condSignal(UConditionVar *cond);
U_NAMESPACE_END
+2 -2
View File
@@ -212,13 +212,13 @@ isDataLoaded(UErrorCode *pErrorCode) {
return U_SUCCESS(*pErrorCode);
}
#define WRITE_CHAR(buffer, bufferLength, bufferPos, c) { \
#define WRITE_CHAR(buffer, bufferLength, bufferPos, c) UPRV_BLOCK_MACRO_BEGIN { \
if((bufferLength)>0) { \
*(buffer)++=c; \
--(bufferLength); \
} \
++(bufferPos); \
}
} UPRV_BLOCK_MACRO_END
#define U_ISO_COMMENT U_CHAR_NAME_CHOICE_COUNT
+5
View File
@@ -23,6 +23,9 @@
*/
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/uobject.h"
U_NAMESPACE_BEGIN
@@ -231,4 +234,6 @@ private:
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __APPENDABLE_H__
+9 -1
View File
@@ -29,6 +29,10 @@
* \brief C++ API: Break Iterator.
*/
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if UCONFIG_NO_BREAK_ITERATION
U_NAMESPACE_BEGIN
@@ -135,7 +139,7 @@ public:
* method which subclasses implement.
* @stable ICU 2.0
*/
virtual BreakIterator* clone(void) const = 0;
virtual BreakIterator* clone() const = 0;
/**
* Return a polymorphic class ID for this object. Different subclasses
@@ -493,6 +497,7 @@ public:
static UnicodeString& U_EXPORT2 getDisplayName(const Locale& objectLocale,
UnicodeString& name);
#ifndef U_FORCE_HIDE_DEPRECATED_API
/**
* Deprecated functionality. Use clone() instead.
*
@@ -515,6 +520,7 @@ public:
virtual BreakIterator * createBufferClone(void *stackBuffer,
int32_t &BufferSize,
UErrorCode &status) = 0;
#endif // U_FORCE_HIDE_DEPRECATED_API
#ifndef U_HIDE_DEPRECATED_API
@@ -658,5 +664,7 @@ U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_BREAK_ITERATION */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // BRKITER_H
//eof
+5
View File
@@ -38,6 +38,9 @@
*/
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/uobject.h"
#include "unicode/std_string.h"
@@ -267,4 +270,6 @@ class StringByteSink : public ByteSink {
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __BYTESTREAM_H__
+47
View File
@@ -23,6 +23,9 @@
*/
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/stringpiece.h"
#include "unicode/uobject.h"
#include "unicode/ustringtrie.h"
@@ -94,6 +97,41 @@ public:
return *this;
}
#ifndef U_HIDE_DRAFT_API
/**
* Returns the state of this trie as a 64-bit integer.
* The state value is never 0.
*
* @return opaque state value
* @see resetToState64
* @draft ICU 65
*/
uint64_t getState64() const {
return (static_cast<uint64_t>(remainingMatchLength_ + 2) << kState64RemainingShift) |
(uint64_t)(pos_ - bytes_);
}
/**
* Resets this trie to the saved state.
* Unlike resetToState(State), the 64-bit state value
* must be from getState64() from the same trie object or
* from one initialized the exact same way.
* Because of no validation, this method is faster.
*
* @param state The opaque trie state value from getState64().
* @return *this
* @see getState64
* @see resetToState
* @see reset
* @draft ICU 65
*/
BytesTrie &resetToState64(uint64_t state) {
remainingMatchLength_ = static_cast<int32_t>(state >> kState64RemainingShift) - 2;
pos_ = bytes_ + (state & kState64PosMask);
return *this;
}
#endif /* U_HIDE_DRAFT_API */
/**
* BytesTrie state object, for saving a trie's current state
* and resetting the trie back to this state later.
@@ -502,6 +540,13 @@ private:
static const int32_t kMaxTwoByteDelta=((kMinThreeByteDeltaLead-kMinTwoByteDeltaLead)<<8)-1; // 0x2fff
static const int32_t kMaxThreeByteDelta=((kFourByteDeltaLead-kMinThreeByteDeltaLead)<<16)-1; // 0xdffff
// For getState64():
// The remainingMatchLength_ is -1..14=(kMaxLinearMatchLength=0x10)-2
// so we need at least 5 bits for that.
// We add 2 to store it as a positive value 1..16=kMaxLinearMatchLength.
static constexpr int32_t kState64RemainingShift = 59;
static constexpr uint64_t kState64PosMask = (UINT64_C(1) << kState64RemainingShift) - 1;
uint8_t *ownedArray_;
// Fixed value referencing the BytesTrie bytes.
@@ -517,4 +562,6 @@ private:
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __BYTESTRIE_H__
@@ -23,6 +23,9 @@
#define __BYTESTRIEBUILDER_H__
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/bytestrie.h"
#include "unicode/stringpiece.h"
#include "unicode/stringtriebuilder.h"
@@ -179,4 +182,6 @@ private:
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __BYTESTRIEBUILDER_H__
+4
View File
@@ -12,6 +12,8 @@
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_NORMALIZATION
#include "unicode/uobject.h"
@@ -207,4 +209,6 @@ U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_NORMALIZATION */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif
+5
View File
@@ -8,6 +8,9 @@
#define __CASEMAP_H__
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/stringpiece.h"
#include "unicode/uobject.h"
@@ -489,4 +492,6 @@ private:
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __CASEMAP_H__
+6 -1
View File
@@ -7,9 +7,12 @@
#ifndef __CHAR16PTR_H__
#define __CHAR16PTR_H__
#include <cstddef>
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include <cstddef>
/**
* \file
* \brief C++ API: char16_t pointer wrappers with
@@ -305,4 +308,6 @@ inline OldUChar *toOldUCharPtr(char16_t *p) {
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __CHAR16PTR_H__
+7 -1
View File
@@ -13,6 +13,9 @@
#define CHARITER_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/uobject.h"
#include "unicode/unistr.h"
/**
@@ -377,7 +380,7 @@ public:
* @return a pointer to a new CharacterIterator
* @stable ICU 2.0
*/
virtual CharacterIterator* clone(void) const = 0;
virtual CharacterIterator* clone() const = 0;
/**
* Sets the iterator to refer to the first code unit in its
@@ -725,4 +728,7 @@ CharacterIterator::getLength(void) const {
}
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif
+6
View File
@@ -13,6 +13,10 @@
#ifndef DBBI_H
#define DBBI_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/rbbi.h"
#if !UCONFIG_NO_BREAK_ITERATION
@@ -39,4 +43,6 @@ U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_BREAK_ITERATION */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif
+2 -2
View File
@@ -99,7 +99,7 @@
* </tr>
* <tr>
* <td>Codepage Conversion</td>
* <td>ucnv.h, ucnvsel.hb</td>
* <td>ucnv.h, ucnvsel.h</td>
* <td>C API</td>
* </tr>
* <tr>
@@ -115,7 +115,7 @@
* <tr>
* <td>Locales </td>
* <td>uloc.h</a></td>
* <td>icu::Locale, icu::LocaleBuilder</td>
* <td>icu::Locale, icu::LocaleBuilder, icu::LocaleMatcher</td>
* </tr>
* <tr>
* <td>Resource Bundles</td>
+5 -1
View File
@@ -15,6 +15,9 @@
#define __DTINTRV_H__
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/uobject.h"
/**
@@ -22,7 +25,6 @@
* \brief C++ API: Date Interval data type
*/
U_NAMESPACE_BEGIN
@@ -157,4 +159,6 @@ DateInterval::operator!=(const DateInterval& other) const {
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif
+6 -1
View File
@@ -8,6 +8,9 @@
#define __EDITS_H__
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/uobject.h"
/**
@@ -159,7 +162,7 @@ public:
* @return TRUE if U_FAILURE(outErrorCode)
* @stable ICU 59
*/
UBool copyErrorTo(UErrorCode &outErrorCode);
UBool copyErrorTo(UErrorCode &outErrorCode) const;
/**
* How much longer is the new text compared with the old text?
@@ -523,4 +526,6 @@ private:
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __EDITS_H__
+5
View File
@@ -26,6 +26,9 @@
*/
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/uobject.h"
U_NAMESPACE_BEGIN
@@ -136,4 +139,6 @@ protected:
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __ERRORCODE_H__
+7
View File
@@ -11,6 +11,9 @@
#define FILTEREDBRK_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/brkiter.h"
#if !UCONFIG_NO_BREAK_ITERATION && !UCONFIG_NO_FILTERED_BREAK_ITERATION
@@ -101,6 +104,7 @@ class U_COMMON_API FilteredBreakIteratorBuilder : public UObject {
*/
virtual UBool unsuppressBreakAfter(const UnicodeString& string, UErrorCode& status) = 0;
#ifndef U_FORCE_HIDE_DEPRECATED_API
/**
* This function has been deprecated in favor of wrapIteratorWithFilter()
* The behavior is identical.
@@ -111,6 +115,7 @@ class U_COMMON_API FilteredBreakIteratorBuilder : public UObject {
* @see wrapBreakIteratorWithFilter()
*/
virtual BreakIterator *build(BreakIterator* adoptBreakIterator, UErrorCode& status) = 0;
#endif // U_FORCE_HIDE_DEPRECATED_API
/**
* Wrap (adopt) an existing break iterator in a new filtered instance.
@@ -142,4 +147,6 @@ U_NAMESPACE_END
#endif // #if !UCONFIG_NO_BREAK_ITERATION && !UCONFIG_NO_FILTERED_BREAK_ITERATION
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // #ifndef FILTEREDBRK_H
+5
View File
@@ -24,6 +24,8 @@
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_IDNA
#include "unicode/bytestream.h"
@@ -322,4 +324,7 @@ private:
U_NAMESPACE_END
#endif // UCONFIG_NO_IDNA
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __IDNA_H__
+26 -3
View File
@@ -3,11 +3,14 @@
#ifndef __LOCALEBUILDER_H__
#define __LOCALEBUILDER_H__
#include "unicode/locid.h"
#include "unicode/stringpiece.h"
#include "unicode/uobject.h"
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/locid.h"
#include "unicode/localematcher.h"
#include "unicode/stringpiece.h"
#include "unicode/uobject.h"
#ifndef U_HIDE_DRAFT_API
/**
@@ -276,7 +279,24 @@ public:
*/
Locale build(UErrorCode& status);
#ifndef U_HIDE_DRAFT_API
/**
* Sets the UErrorCode if an error occurred while recording sets.
* Preserves older error codes in the outErrorCode.
* @param outErrorCode Set to an error code that occurred while setting subtags.
* Unchanged if there is no such error or if outErrorCode
* already contained an error.
* @return TRUE if U_FAILURE(outErrorCode)
* @draft ICU 65
*/
UBool copyErrorTo(UErrorCode &outErrorCode) const;
#endif /* U_HIDE_DRAFT_API */
private:
friend class LocaleMatcher::Result;
void copyExtensionsFrom(const Locale& src, UErrorCode& errorCode);
UErrorCode status_;
char language_[9];
char script_[5];
@@ -289,4 +309,7 @@ private:
U_NAMESPACE_END
#endif // U_HIDE_DRAFT_API
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __LOCALEBUILDER_H__
+605
View File
@@ -0,0 +1,605 @@
// © 2019 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
// localematcher.h
// created: 2019may08 Markus W. Scherer
#ifndef __LOCALEMATCHER_H__
#define __LOCALEMATCHER_H__
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/locid.h"
#include "unicode/stringpiece.h"
#include "unicode/uobject.h"
/**
* \file
* \brief C++ API: Locale matcher: User's desired locales vs. application's supported locales.
*/
#ifndef U_HIDE_DRAFT_API
/**
* Builder option for whether the language subtag or the script subtag is most important.
*
* @see Builder#setFavorSubtag(FavorSubtag)
* @draft ICU 65
*/
enum ULocMatchFavorSubtag {
/**
* Language differences are most important, then script differences, then region differences.
* (This is the default behavior.)
*
* @draft ICU 65
*/
ULOCMATCH_FAVOR_LANGUAGE,
/**
* Makes script differences matter relatively more than language differences.
*
* @draft ICU 65
*/
ULOCMATCH_FAVOR_SCRIPT
};
#ifndef U_IN_DOXYGEN
typedef enum ULocMatchFavorSubtag ULocMatchFavorSubtag;
#endif
/**
* Builder option for whether all desired locales are treated equally or
* earlier ones are preferred.
*
* @see Builder#setDemotionPerDesiredLocale(Demotion)
* @draft ICU 65
*/
enum ULocMatchDemotion {
/**
* All desired locales are treated equally.
*
* @draft ICU 65
*/
ULOCMATCH_DEMOTION_NONE,
/**
* Earlier desired locales are preferred.
*
* <p>From each desired locale to the next,
* the distance to any supported locale is increased by an additional amount
* which is at least as large as most region mismatches.
* A later desired locale has to have a better match with some supported locale
* due to more than merely having the same region subtag.
*
* <p>For example: <code>Supported={en, sv} desired=[en-GB, sv]</code>
* yields <code>Result(en-GB, en)</code> because
* with the demotion of sv its perfect match is no better than
* the region distance between the earlier desired locale en-GB and en=en-US.
*
* <p>Notes:
* <ul>
* <li>In some cases, language and/or script differences can be as small as
* the typical region difference. (Example: sr-Latn vs. sr-Cyrl)
* <li>It is possible for certain region differences to be larger than usual,
* and larger than the demotion.
* (As of CLDR 35 there is no such case, but
* this is possible in future versions of the data.)
* </ul>
*
* @draft ICU 65
*/
ULOCMATCH_DEMOTION_REGION
};
#ifndef U_IN_DOXYGEN
typedef enum ULocMatchDemotion ULocMatchDemotion;
#endif
struct UHashtable;
U_NAMESPACE_BEGIN
struct LSR;
class LocaleDistance;
class LocaleLsrIterator;
class UVector;
class XLikelySubtags;
/**
* Immutable class that picks the best match between a user's desired locales and
* an application's supported locales.
* Movable but not copyable.
*
* <p>Example:
* <pre>
* UErrorCode errorCode = U_ZERO_ERROR;
* LocaleMatcher matcher = LocaleMatcher::Builder().setSupportedLocales("fr, en-GB, en").build(errorCode);
* Locale *bestSupported = matcher.getBestLocale(Locale.US, errorCode); // "en"
* </pre>
*
* <p>A matcher takes into account when languages are close to one another,
* such as Danish and Norwegian,
* and when regional variants are close, like en-GB and en-AU as opposed to en-US.
*
* <p>If there are multiple supported locales with the same (language, script, region)
* likely subtags, then the current implementation returns the first of those locales.
* It ignores variant subtags (except for pseudolocale variants) and extensions.
* This may change in future versions.
*
* <p>For example, the current implementation does not distinguish between
* de, de-DE, de-Latn, de-1901, de-u-co-phonebk.
*
* <p>If you prefer one equivalent locale over another, then provide only the preferred one,
* or place it earlier in the list of supported locales.
*
* <p>Otherwise, the order of supported locales may have no effect on the best-match results.
* The current implementation compares each desired locale with supported locales
* in the following order:
* 1. Default locale, if supported;
* 2. CLDR "paradigm locales" like en-GB and es-419;
* 3. other supported locales.
* This may change in future versions.
*
* <p>Often a product will just need one matcher instance, built with the languages
* that it supports. However, it may want multiple instances with different
* default languages based on additional information, such as the domain.
*
* <p>This class is not intended for public subclassing.
*
* @draft ICU 65
*/
class U_COMMON_API LocaleMatcher : public UMemory {
public:
/**
* Data for the best-matching pair of a desired and a supported locale.
* Movable but not copyable.
*
* @draft ICU 65
*/
class U_COMMON_API Result : public UMemory {
public:
/**
* Move constructor; might modify the source.
* This object will have the same contents that the source object had.
*
* @param src Result to move contents from.
* @draft ICU 65
*/
Result(Result &&src) U_NOEXCEPT;
/**
* Destructor.
*
* @draft ICU 65
*/
~Result();
/**
* Move assignment; might modify the source.
* This object will have the same contents that the source object had.
*
* @param src Result to move contents from.
* @draft ICU 65
*/
Result &operator=(Result &&src) U_NOEXCEPT;
/**
* Returns the best-matching desired locale.
* nullptr if the list of desired locales is empty or if none matched well enough.
*
* @return the best-matching desired locale, or nullptr.
* @draft ICU 65
*/
inline const Locale *getDesiredLocale() const { return desiredLocale; }
/**
* Returns the best-matching supported locale.
* If none matched well enough, this is the default locale.
* The default locale is nullptr if the list of supported locales is empty and
* no explicit default locale is set.
*
* @return the best-matching supported locale, or nullptr.
* @draft ICU 65
*/
inline const Locale *getSupportedLocale() const { return supportedLocale; }
/**
* Returns the index of the best-matching desired locale in the input Iterable order.
* -1 if the list of desired locales is empty or if none matched well enough.
*
* @return the index of the best-matching desired locale, or -1.
* @draft ICU 65
*/
inline int32_t getDesiredIndex() const { return desiredIndex; }
/**
* Returns the index of the best-matching supported locale in the
* constructor’s or builder’s input order (“set” Collection plus “added” locales).
* If the matcher was built from a locale list string, then the iteration order is that
* of a LocalePriorityList built from the same string.
* -1 if the list of supported locales is empty or if none matched well enough.
*
* @return the index of the best-matching supported locale, or -1.
* @draft ICU 65
*/
inline int32_t getSupportedIndex() const { return supportedIndex; }
/**
* Takes the best-matching supported locale and adds relevant fields of the
* best-matching desired locale, such as the -t- and -u- extensions.
* May replace some fields of the supported locale.
* The result is the locale that should be used for date and number formatting, collation, etc.
* Returns the root locale if getSupportedLocale() returns nullptr.
*
* <p>Example: desired=ar-SA-u-nu-latn, supported=ar-EG, resolved locale=ar-SA-u-nu-latn
*
* @return a locale combining the best-matching desired and supported locales.
* @draft ICU 65
*/
Locale makeResolvedLocale(UErrorCode &errorCode) const;
private:
Result(const Locale *desired, const Locale *supported,
int32_t desIndex, int32_t suppIndex, UBool owned) :
desiredLocale(desired), supportedLocale(supported),
desiredIndex(desIndex), supportedIndex(suppIndex),
desiredIsOwned(owned) {}
Result(const Result &other) = delete;
Result &operator=(const Result &other) = delete;
const Locale *desiredLocale;
const Locale *supportedLocale;
int32_t desiredIndex;
int32_t supportedIndex;
UBool desiredIsOwned;
friend class LocaleMatcher;
};
/**
* LocaleMatcher builder.
* Movable but not copyable.
*
* @see LocaleMatcher#builder()
* @draft ICU 65
*/
class U_COMMON_API Builder : public UMemory {
public:
/**
* Constructs a builder used in chaining parameters for building a LocaleMatcher.
*
* @return a new Builder object
* @draft ICU 65
*/
Builder() {}
/**
* Move constructor; might modify the source.
* This builder will have the same contents that the source builder had.
*
* @param src Builder to move contents from.
* @draft ICU 65
*/
Builder(Builder &&src) U_NOEXCEPT;
/**
* Destructor.
*
* @draft ICU 65
*/
~Builder();
/**
* Move assignment; might modify the source.
* This builder will have the same contents that the source builder had.
*
* @param src Builder to move contents from.
* @draft ICU 65
*/
Builder &operator=(Builder &&src) U_NOEXCEPT;
/**
* Parses an Accept-Language string
* (<a href="https://tools.ietf.org/html/rfc2616#section-14.4">RFC 2616 Section 14.4</a>),
* such as "af, en, fr;q=0.9", and sets the supported locales accordingly.
* Allows whitespace in more places but does not allow "*".
* Clears any previously set/added supported locales first.
*
* @param locales the Accept-Language string of locales to set
* @return this Builder object
* @draft ICU 65
*/
Builder &setSupportedLocalesFromListString(StringPiece locales);
/**
* Copies the supported locales, preserving iteration order.
* Clears any previously set/added supported locales first.
* Duplicates are allowed, and are not removed.
*
* @param locales the list of locale
* @return this Builder object
* @draft ICU 65
*/
Builder &setSupportedLocales(Locale::Iterator &locales);
/**
* Copies the supported locales from the begin/end range, preserving iteration order.
* Clears any previously set/added supported locales first.
* Duplicates are allowed, and are not removed.
*
* Each of the iterator parameter values must be an
* input iterator whose value is convertible to const Locale &.
*
* @param begin Start of range.
* @param end Exclusive end of range.
* @return this Builder object
* @draft ICU 65
*/
template<typename Iter>
Builder &setSupportedLocales(Iter begin, Iter end) {
if (U_FAILURE(errorCode_)) { return *this; }
clearSupportedLocales();
while (begin != end) {
addSupportedLocale(*begin++);
}
return *this;
}
/**
* Copies the supported locales from the begin/end range, preserving iteration order.
* Calls the converter to convert each *begin to a Locale or const Locale &.
* Clears any previously set/added supported locales first.
* Duplicates are allowed, and are not removed.
*
* Each of the iterator parameter values must be an
* input iterator whose value is convertible to const Locale &.
*
* @param begin Start of range.
* @param end Exclusive end of range.
* @param converter Converter from *begin to const Locale & or compatible.
* @return this Builder object
* @draft ICU 65
*/
template<typename Iter, typename Conv>
Builder &setSupportedLocalesViaConverter(Iter begin, Iter end, Conv converter) {
if (U_FAILURE(errorCode_)) { return *this; }
clearSupportedLocales();
while (begin != end) {
addSupportedLocale(converter(*begin++));
}
return *this;
}
/**
* Adds another supported locale.
* Duplicates are allowed, and are not removed.
*
* @param locale another locale
* @return this Builder object
* @draft ICU 65
*/
Builder &addSupportedLocale(const Locale &locale);
/**
* Sets the default locale; if nullptr, or if it is not set explicitly,
* then the first supported locale is used as the default locale.
*
* @param defaultLocale the default locale (will be copied)
* @return this Builder object
* @draft ICU 65
*/
Builder &setDefaultLocale(const Locale *defaultLocale);
/**
* If ULOCMATCH_FAVOR_SCRIPT, then the language differences are smaller than script
* differences.
* This is used in situations (such as maps) where
* it is better to fall back to the same script than a similar language.
*
* @param subtag the subtag to favor
* @return this Builder object
* @draft ICU 65
*/
Builder &setFavorSubtag(ULocMatchFavorSubtag subtag);
/**
* Option for whether all desired locales are treated equally or
* earlier ones are preferred (this is the default).
*
* @param demotion the demotion per desired locale to set.
* @return this Builder object
* @draft ICU 65
*/
Builder &setDemotionPerDesiredLocale(ULocMatchDemotion demotion);
/**
* Sets the UErrorCode if an error occurred while setting parameters.
* Preserves older error codes in the outErrorCode.
*
* @param outErrorCode Set to an error code if it does not contain one already
* and an error occurred while setting parameters.
* Otherwise unchanged.
* @return TRUE if U_FAILURE(outErrorCode)
* @draft ICU 65
*/
UBool copyErrorTo(UErrorCode &outErrorCode) const;
/**
* Builds and returns a new locale matcher.
* This builder can continue to be used.
*
* @param errorCode 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 new LocaleMatcher.
* @draft ICU 65
*/
LocaleMatcher build(UErrorCode &errorCode) const;
private:
friend class LocaleMatcher;
Builder(const Builder &other) = delete;
Builder &operator=(const Builder &other) = delete;
void clearSupportedLocales();
bool ensureSupportedLocaleVector();
UErrorCode errorCode_ = U_ZERO_ERROR;
UVector *supportedLocales_ = nullptr;
int32_t thresholdDistance_ = -1;
ULocMatchDemotion demotion_ = ULOCMATCH_DEMOTION_REGION;
Locale *defaultLocale_ = nullptr;
ULocMatchFavorSubtag favor_ = ULOCMATCH_FAVOR_LANGUAGE;
};
// FYI No public LocaleMatcher constructors in C++; use the Builder.
/**
* Move copy constructor; might modify the source.
* This matcher will have the same settings that the source matcher had.
* @param src source matcher
* @draft ICU 65
*/
LocaleMatcher(LocaleMatcher &&src) U_NOEXCEPT;
/**
* Destructor.
* @draft ICU 65
*/
~LocaleMatcher();
/**
* Move assignment operator; might modify the source.
* This matcher will have the same settings that the source matcher had.
* The behavior is undefined if *this and src are the same object.
* @param src source matcher
* @return *this
* @draft ICU 65
*/
LocaleMatcher &operator=(LocaleMatcher &&src) U_NOEXCEPT;
/**
* Returns the supported locale which best matches the desired locale.
*
* @param desiredLocale Typically a user's language.
* @param errorCode 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 the best-matching supported locale.
* @draft ICU 65
*/
const Locale *getBestMatch(const Locale &desiredLocale, UErrorCode &errorCode) const;
/**
* Returns the supported locale which best matches one of the desired locales.
*
* @param desiredLocales Typically a user's languages, in order of preference (descending).
* @param errorCode 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 the best-matching supported locale.
* @draft ICU 65
*/
const Locale *getBestMatch(Locale::Iterator &desiredLocales, UErrorCode &errorCode) const;
/**
* Parses an Accept-Language string
* (<a href="https://tools.ietf.org/html/rfc2616#section-14.4">RFC 2616 Section 14.4</a>),
* such as "af, en, fr;q=0.9",
* and returns the supported locale which best matches one of the desired locales.
* Allows whitespace in more places but does not allow "*".
*
* @param desiredLocaleList Typically a user's languages, as an Accept-Language string.
* @param errorCode 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 the best-matching supported locale.
* @draft ICU 65
*/
const Locale *getBestMatchForListString(StringPiece desiredLocaleList, UErrorCode &errorCode) const;
/**
* Returns the best match between the desired locale and the supported locales.
* If the result's desired locale is not nullptr, then it is the address of the input locale.
* It has not been cloned.
*
* @param desiredLocale Typically a user's language.
* @param errorCode 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 the best-matching pair of the desired and a supported locale.
* @draft ICU 65
*/
Result getBestMatchResult(const Locale &desiredLocale, UErrorCode &errorCode) const;
/**
* Returns the best match between the desired and supported locales.
* If the result's desired locale is not nullptr, then it is a clone of
* the best-matching desired locale. The Result object owns the clone.
*
* @param desiredLocales Typically a user's languages, in order of preference (descending).
* @param errorCode 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 the best-matching pair of a desired and a supported locale.
* @draft ICU 65
*/
Result getBestMatchResult(Locale::Iterator &desiredLocales, UErrorCode &errorCode) const;
#ifndef U_HIDE_INTERNAL_API
/**
* Returns a fraction between 0 and 1, where 1 means that the languages are a
* perfect match, and 0 means that they are completely different.
*
* <p>This is mostly an implementation detail, and the precise values may change over time.
* The implementation may use either the maximized forms or the others ones, or both.
* The implementation may or may not rely on the forms to be consistent with each other.
*
* <p>Callers should construct and use a matcher rather than match pairs of locales directly.
*
* @param desired Desired locale.
* @param supported Supported locale.
* @param errorCode 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 value between 0 and 1, inclusive.
* @internal (has a known user)
*/
double internalMatch(const Locale &desired, const Locale &supported, UErrorCode &errorCode) const;
#endif // U_HIDE_INTERNAL_API
private:
LocaleMatcher(const Builder &builder, UErrorCode &errorCode);
LocaleMatcher(const LocaleMatcher &other) = delete;
LocaleMatcher &operator=(const LocaleMatcher &other) = delete;
int32_t getBestSuppIndex(LSR desiredLSR, LocaleLsrIterator *remainingIter, UErrorCode &errorCode) const;
const XLikelySubtags &likelySubtags;
const LocaleDistance &localeDistance;
int32_t thresholdDistance;
int32_t demotionPerDesiredLocale;
ULocMatchFavorSubtag favorSubtag;
// These are in input order.
const Locale ** supportedLocales;
LSR *lsrs;
int32_t supportedLocalesLength;
// These are in preference order: 1. Default locale 2. paradigm locales 3. others.
UHashtable *supportedLsrToIndex; // Map<LSR, Integer> stores index+1 because 0 is "not found"
// Array versions of the supportedLsrToIndex keys and values.
// The distance lookup loops over the supportedLSRs and returns the index of the best match.
const LSR **supportedLSRs;
int32_t *supportedIndexes;
int32_t supportedLSRsLength;
Locale *ownedDefaultLocale;
const Locale *defaultLocale;
int32_t defaultLocaleIndex;
};
U_NAMESPACE_END
#endif // U_HIDE_DRAFT_API
#endif // U_SHOW_CPLUSPLUS_API
#endif // __LOCALEMATCHER_H__
+4
View File
@@ -12,6 +12,8 @@
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: Provides display names of Locale and its components.
@@ -204,4 +206,6 @@ U_NAMESPACE_END
#endif
#endif /* U_SHOW_CPLUSPLUS_API */
#endif
+122 -41
View File
@@ -31,11 +31,14 @@
#ifndef LOCID_H
#define LOCID_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/bytestream.h"
#include "unicode/localpointer.h"
#include "unicode/strenum.h"
#include "unicode/stringpiece.h"
#include "unicode/utypes.h"
#include "unicode/uobject.h"
#include "unicode/putil.h"
#include "unicode/uloc.h"
@@ -284,16 +287,14 @@ public:
*/
Locale(const Locale& other);
#ifndef U_HIDE_DRAFT_API
/**
* Move constructor; might leave source in bogus state.
* This locale will have the same contents that the source locale had.
*
* @param other The Locale object being moved in.
* @draft ICU 63
* @stable ICU 63
*/
Locale(Locale&& other) U_NOEXCEPT;
#endif // U_HIDE_DRAFT_API
/**
* Destructor
@@ -310,7 +311,6 @@ public:
*/
Locale& operator=(const Locale& other);
#ifndef U_HIDE_DRAFT_API
/**
* Move assignment operator; might leave source in bogus state.
* This locale will have the same contents that the source locale had.
@@ -318,10 +318,9 @@ public:
*
* @param other The Locale object being moved in.
* @return *this
* @draft ICU 63
* @stable ICU 63
*/
Locale& operator=(Locale&& other) U_NOEXCEPT;
#endif // U_HIDE_DRAFT_API
/**
* Checks if two locale keys are the same.
@@ -389,7 +388,6 @@ public:
UErrorCode& success);
#endif /* U_HIDE_SYSTEM_API */
#ifndef U_HIDE_DRAFT_API
/**
* Returns a Locale for the specified BCP47 language tag string.
* If the specified language tag contains any ill-formed subtags,
@@ -405,7 +403,7 @@ public:
* @param tag the input BCP47 language tag.
* @param status error information if creating the Locale failed.
* @return the Locale for the specified BCP47 language tag.
* @draft ICU 63
* @stable ICU 63
*/
static Locale U_EXPORT2 forLanguageTag(StringPiece tag, UErrorCode& status);
@@ -420,7 +418,7 @@ public:
* @param sink the output sink receiving the BCP47 language
* tag for this Locale.
* @param status error information if creating the language tag failed.
* @draft ICU 63
* @stable ICU 63
*/
void toLanguageTag(ByteSink& sink, UErrorCode& status) const;
@@ -432,11 +430,10 @@ public:
*
* @param status error information if creating the language tag failed.
* @return the BCP47 language tag for this Locale.
* @draft ICU 63
* @stable ICU 63
*/
template<typename StringClass>
inline StringClass toLanguageTag(UErrorCode& status) const;
#endif // U_HIDE_DRAFT_API
/**
* Creates a locale which has had minimal canonicalization
@@ -508,7 +505,6 @@ public:
*/
const char * getBaseName() const;
#ifndef U_HIDE_DRAFT_API
/**
* Add the likely subtags for this Locale, per the algorithm described
* in the following CLDR technical report:
@@ -536,7 +532,7 @@ public:
* @param status error information if maximizing this Locale failed.
* If this Locale is not well-formed, the error code is
* U_ILLEGAL_ARGUMENT_ERROR.
* @draft ICU 63
* @stable ICU 63
*/
void addLikelySubtags(UErrorCode& status);
@@ -567,10 +563,9 @@ public:
* @param status error information if maximizing this Locale failed.
* If this Locale is not well-formed, the error code is
* U_ILLEGAL_ARGUMENT_ERROR.
* @draft ICU 63
* @stable ICU 63
*/
void minimizeSubtags(UErrorCode& status);
#endif // U_HIDE_DRAFT_API
/**
* Gets the list of keywords for the specified locale.
@@ -583,8 +578,6 @@ public:
*/
StringEnumeration * createKeywords(UErrorCode &status) const;
#ifndef U_HIDE_DRAFT_API
/**
* Gets the list of Unicode keywords for the specified locale.
*
@@ -592,7 +585,7 @@ public:
* @return pointer to StringEnumeration class, or NULL if there are no keywords.
* Client must dispose of it by calling delete.
* @see getUnicodeKeywords
* @draft ICU 63
* @stable ICU 63
*/
StringEnumeration * createUnicodeKeywords(UErrorCode &status) const;
@@ -605,7 +598,7 @@ public:
*
* @param iterator an STL style output iterator to write the keywords to.
* @param status error information if creating set of keywords failed.
* @draft ICU 63
* @stable ICU 63
*/
template<typename StringClass, typename OutputIterator>
inline void getKeywords(OutputIterator iterator, UErrorCode& status) const;
@@ -619,13 +612,11 @@ public:
*
* @param iterator an STL style output iterator to write the keywords to.
* @param status error information if creating set of keywords failed.
* @draft ICU 63
* @stable ICU 63
*/
template<typename StringClass, typename OutputIterator>
inline void getUnicodeKeywords(OutputIterator iterator, UErrorCode& status) const;
#endif // U_HIDE_DRAFT_API
/**
* Gets the value for a keyword.
*
@@ -644,7 +635,6 @@ public:
*/
int32_t getKeywordValue(const char* keywordName, char *buffer, int32_t bufferCapacity, UErrorCode &status) const;
#ifndef U_HIDE_DRAFT_API
/**
* Gets the value for a keyword.
*
@@ -656,7 +646,7 @@ public:
* @param keywordName name of the keyword for which we want the value.
* @param sink the sink to receive the keyword value.
* @param status error information if getting the value failed.
* @draft ICU 63
* @stable ICU 63
*/
void getKeywordValue(StringPiece keywordName, ByteSink& sink, UErrorCode& status) const;
@@ -671,7 +661,7 @@ public:
* @param keywordName name of the keyword for which we want the value.
* @param status error information if getting the value failed.
* @return the keyword value.
* @draft ICU 63
* @stable ICU 63
*/
template<typename StringClass>
inline StringClass getKeywordValue(StringPiece keywordName, UErrorCode& status) const;
@@ -687,7 +677,7 @@ public:
* @param keywordName name of the keyword for which we want the value.
* @param sink the sink to receive the keyword value.
* @param status error information if getting the value failed.
* @draft ICU 63
* @stable ICU 63
*/
void getUnicodeKeywordValue(StringPiece keywordName, ByteSink& sink, UErrorCode& status) const;
@@ -702,11 +692,10 @@ public:
* @param keywordName name of the keyword for which we want the value.
* @param status error information if getting the value failed.
* @return the keyword value.
* @draft ICU 63
* @stable ICU 63
*/
template<typename StringClass>
inline StringClass getUnicodeKeywordValue(StringPiece keywordName, UErrorCode& status) const;
#endif // U_HIDE_DRAFT_API
/**
* Sets or removes the value for a keyword.
@@ -729,7 +718,6 @@ public:
*/
void setKeywordValue(const char* keywordName, const char* keywordValue, UErrorCode &status);
#ifndef U_HIDE_DRAFT_API
/**
* Sets or removes the value for a keyword.
*
@@ -746,7 +734,7 @@ public:
* NULL, will result in the keyword being removed. No error is given if
* that keyword does not exist.
* @param status Returns any error information while performing this operation.
* @draft ICU 63
* @stable ICU 63
*/
void setKeywordValue(StringPiece keywordName, StringPiece keywordValue, UErrorCode& status);
@@ -766,10 +754,9 @@ public:
* NULL, will result in the keyword being removed. No error is given if
* that keyword does not exist.
* @param status Returns any error information while performing this operation.
* @draft ICU 63
* @stable ICU 63
*/
void setUnicodeKeywordValue(StringPiece keywordName, StringPiece keywordValue, UErrorCode& status);
#endif // U_HIDE_DRAFT_API
/**
* returns the locale's three-letter language code, as specified
@@ -1008,6 +995,104 @@ public:
*/
virtual UClassID getDynamicClassID() const;
#ifndef U_HIDE_DRAFT_API
/**
* A Locale iterator interface similar to a Java Iterator<Locale>.
* @draft ICU 65
*/
class U_COMMON_API Iterator /* not : public UObject because this is an interface/mixin class */ {
public:
/** @draft ICU 65 */
virtual ~Iterator();
/**
* @return TRUE if next() can be called again.
* @draft ICU 65
*/
virtual UBool hasNext() const = 0;
/**
* @return the next locale.
* @draft ICU 65
*/
virtual const Locale &next() = 0;
};
/**
* A generic Locale iterator implementation over Locale input iterators.
* @draft ICU 65
*/
template<typename Iter>
class RangeIterator : public Iterator, public UMemory {
public:
/**
* Constructs an iterator from a begin/end range.
* Each of the iterator parameter values must be an
* input iterator whose value is convertible to const Locale &.
*
* @param begin Start of range.
* @param end Exclusive end of range.
* @draft ICU 65
*/
RangeIterator(Iter begin, Iter end) : it_(begin), end_(end) {}
/**
* @return TRUE if next() can be called again.
* @draft ICU 65
*/
UBool hasNext() const override { return it_ != end_; }
/**
* @return the next locale.
* @draft ICU 65
*/
const Locale &next() override { return *it_++; }
private:
Iter it_;
const Iter end_;
};
/**
* A generic Locale iterator implementation over Locale input iterators.
* Calls the converter to convert each *begin to a const Locale &.
* @draft ICU 65
*/
template<typename Iter, typename Conv>
class ConvertingIterator : public Iterator, public UMemory {
public:
/**
* Constructs an iterator from a begin/end range.
* Each of the iterator parameter values must be an
* input iterator whose value the converter converts to const Locale &.
*
* @param begin Start of range.
* @param end Exclusive end of range.
* @param converter Converter from *begin to const Locale & or compatible.
* @draft ICU 65
*/
ConvertingIterator(Iter begin, Iter end, Conv converter) :
it_(begin), end_(end), converter_(converter) {}
/**
* @return TRUE if next() can be called again.
* @draft ICU 65
*/
UBool hasNext() const override { return it_ != end_; }
/**
* @return the next locale.
* @draft ICU 65
*/
const Locale &next() override { return converter_(*it_++); }
private:
Iter it_;
const Iter end_;
Conv converter_;
};
#endif // U_HIDE_DRAFT_API
protected: /* only protected for testing purposes. DO NOT USE. */
#ifndef U_HIDE_INTERNAL_API
/**
@@ -1074,7 +1159,6 @@ Locale::operator!=(const Locale& other) const
return !operator==(other);
}
#ifndef U_HIDE_DRAFT_API
template<typename StringClass> inline StringClass
Locale::toLanguageTag(UErrorCode& status) const
{
@@ -1083,7 +1167,6 @@ Locale::toLanguageTag(UErrorCode& status) const
toLanguageTag(sink, status);
return result;
}
#endif // U_HIDE_DRAFT_API
inline const char *
Locale::getCountry() const
@@ -1115,13 +1198,11 @@ Locale::getName() const
return fullName;
}
#ifndef U_HIDE_DRAFT_API
template<typename StringClass, typename OutputIterator> inline void
Locale::getKeywords(OutputIterator iterator, UErrorCode& status) const
{
LocalPointer<StringEnumeration> keys(createKeywords(status));
if (U_FAILURE(status)) {
if (U_FAILURE(status) || keys.isNull()) {
return;
}
for (;;) {
@@ -1138,7 +1219,7 @@ template<typename StringClass, typename OutputIterator> inline void
Locale::getUnicodeKeywords(OutputIterator iterator, UErrorCode& status) const
{
LocalPointer<StringEnumeration> keys(createUnicodeKeywords(status));
if (U_FAILURE(status)) {
if (U_FAILURE(status) || keys.isNull()) {
return;
}
for (;;) {
@@ -1169,8 +1250,6 @@ Locale::getUnicodeKeywordValue(StringPiece keywordName, UErrorCode& status) cons
return result;
}
#endif // U_HIDE_DRAFT_API
inline UBool
Locale::isBogus(void) const {
return fIsBogus;
@@ -1178,4 +1257,6 @@ Locale::isBogus(void) const {
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif
+4
View File
@@ -24,6 +24,8 @@
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/parseerr.h"
@@ -942,4 +944,6 @@ U_NAMESPACE_END
#endif // !UCONFIG_NO_FORMATTING
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __MESSAGEPATTERN_H__
+5
View File
@@ -26,6 +26,8 @@
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_NORMALIZATION
#include "unicode/stringpiece.h"
@@ -771,4 +773,7 @@ private:
U_NAMESPACE_END
#endif // !UCONFIG_NO_NORMALIZATION
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __NORMALIZER2_H__
+9 -2
View File
@@ -13,6 +13,8 @@
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: Unicode Normalization
@@ -183,6 +185,7 @@ public:
Normalizer(const CharacterIterator& iter, UNormalizationMode mode);
#endif /* U_HIDE_DEPRECATED_API */
#ifndef U_FORCE_HIDE_DEPRECATED_API
/**
* Copy constructor.
* @param copy The object to be copied.
@@ -195,7 +198,7 @@ public:
* @deprecated ICU 56 Use Normalizer2 instead.
*/
virtual ~Normalizer();
#endif // U_FORCE_HIDE_DEPRECATED_API
//-------------------------------------------------------------------------
// Static utility methods
@@ -599,7 +602,7 @@ public:
* @return a pointer to a new Normalizer
* @deprecated ICU 56 Use Normalizer2 instead.
*/
Normalizer* clone(void) const;
Normalizer* clone() const;
/**
* Generates a hash code for this iterator.
@@ -723,12 +726,14 @@ public:
static UClassID U_EXPORT2 getStaticClassID();
#endif /* U_HIDE_DEPRECATED_API */
#ifndef U_FORCE_HIDE_DEPRECATED_API
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
* @return a UClassID for the actual class.
* @deprecated ICU 56 Use Normalizer2 instead.
*/
virtual UClassID getDynamicClassID() const;
#endif // U_FORCE_HIDE_DEPRECATED_API
private:
//-------------------------------------------------------------------------
@@ -807,3 +812,5 @@ U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_NORMALIZATION */
#endif // NORMLZR_H
#endif /* U_SHOW_CPLUSPLUS_API */
+5
View File
@@ -19,6 +19,9 @@
#define PARSEPOS_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/uobject.h"
@@ -229,4 +232,6 @@ ParsePosition::setErrorIndex(int32_t ei)
}
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif
+52 -22
View File
@@ -135,6 +135,14 @@
/** Fuchsia is a POSIX-ish platform. @internal */
#define U_PF_FUCHSIA 4100
/* Maximum value for Linux-based platform is 4499 */
/**
* Emscripten is a C++ transpiler for the Web that can target asm.js or
* WebAssembly. It provides some POSIX-compatible wrappers and stubs and
* some Linux-like functionality, but is not fully compatible with
* either.
* @internal
*/
#define U_PF_EMSCRIPTEN 5010
/** z/OS is the successor to OS/390 which was the successor to MVS. @internal */
#define U_PF_OS390 9000
/** "IBM i" is the current name of what used to be i5/OS and earlier OS/400. @internal */
@@ -192,6 +200,8 @@
# define U_PLATFORM U_PF_OS390
#elif defined(__OS400__) || defined(__TOS_OS400__)
# define U_PLATFORM U_PF_OS400
#elif defined(__EMSCRIPTEN__)
# define U_PLATFORM U_PF_EMSCRIPTEN
#else
# define U_PLATFORM U_PF_UNKNOWN
#endif
@@ -414,26 +424,40 @@
#endif
/* Compatibility with compilers other than clang: http://clang.llvm.org/docs/LanguageExtensions.html */
#ifndef __has_attribute
# define __has_attribute(x) 0
#ifdef __has_attribute
# define UPRV_HAS_ATTRIBUTE(x) __has_attribute(x)
#else
# define UPRV_HAS_ATTRIBUTE(x) 0
#endif
#ifndef __has_cpp_attribute
# define __has_cpp_attribute(x) 0
#ifdef __has_cpp_attribute
# define UPRV_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
#else
# define UPRV_HAS_CPP_ATTRIBUTE(x) 0
#endif
#ifndef __has_declspec_attribute
# define __has_declspec_attribute(x) 0
#ifdef __has_declspec_attribute
# define UPRV_HAS_DECLSPEC_ATTRIBUTE(x) __has_declspec_attribute(x)
#else
# define UPRV_HAS_DECLSPEC_ATTRIBUTE(x) 0
#endif
#ifndef __has_builtin
# define __has_builtin(x) 0
#ifdef __has_builtin
# define UPRV_HAS_BUILTIN(x) __has_builtin(x)
#else
# define UPRV_HAS_BUILTIN(x) 0
#endif
#ifndef __has_feature
# define __has_feature(x) 0
#ifdef __has_feature
# define UPRV_HAS_FEATURE(x) __has_feature(x)
#else
# define UPRV_HAS_FEATURE(x) 0
#endif
#ifndef __has_extension
# define __has_extension(x) 0
#ifdef __has_extension
# define UPRV_HAS_EXTENSION(x) __has_extension(x)
#else
# define UPRV_HAS_EXTENSION(x) 0
#endif
#ifndef __has_warning
# define __has_warning(x) 0
#ifdef __has_warning
# define UPRV_HAS_WARNING(x) __has_warning(x)
#else
# define UPRV_HAS_WARNING(x) 0
#endif
/**
@@ -452,7 +476,9 @@
* Attribute to specify the size of the allocated buffer for malloc-like functions
* @internal
*/
#if (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) || __has_attribute(alloc_size)
#if (defined(__GNUC__) && \
(__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) || \
UPRV_HAS_ATTRIBUTE(alloc_size)
# define U_ALLOC_SIZE_ATTR(X) __attribute__ ((alloc_size(X)))
# define U_ALLOC_SIZE_ATTR2(X,Y) __attribute__ ((alloc_size(X,Y)))
#else
@@ -516,8 +542,9 @@ namespace std {
#elif defined(__clang__)
// Test for compiler vs. feature separately.
// Other compilers might choke on the feature test.
# if __has_cpp_attribute(clang::fallthrough) || \
(__has_feature(cxx_attributes) && __has_warning("-Wimplicit-fallthrough"))
# if UPRV_HAS_CPP_ATTRIBUTE(clang::fallthrough) || \
(UPRV_HAS_FEATURE(cxx_attributes) && \
UPRV_HAS_WARNING("-Wimplicit-fallthrough"))
# define U_FALLTHROUGH [[clang::fallthrough]]
# endif
#elif defined(__GNUC__) && (__GNUC__ >= 7)
@@ -620,7 +647,8 @@ namespace std {
*/
#ifdef U_CHARSET_IS_UTF8
/* Use the predefined value. */
#elif U_PLATFORM_IS_LINUX_BASED || U_PLATFORM_IS_DARWIN_BASED
#elif U_PLATFORM_IS_LINUX_BASED || U_PLATFORM_IS_DARWIN_BASED || \
U_PLATFORM == U_PF_EMSCRIPTEN
# define U_CHARSET_IS_UTF8 1
#else
# define U_CHARSET_IS_UTF8 0
@@ -707,7 +735,7 @@ namespace std {
* narrow-character strings are in EBCDIC.
*/
# define U_SIZEOF_WCHAR_T 2
#else
# else
/*
* LOCALETYPE(*CLD) or LOCALETYPE(*LOCALE) is specified.
* Wide-character strings are in 16-bit EBCDIC,
@@ -786,7 +814,8 @@ namespace std {
/* Use the predefined value. */
#elif defined(U_STATIC_IMPLEMENTATION)
# define U_EXPORT
#elif defined(_MSC_VER) || (__has_declspec_attribute(dllexport) && __has_declspec_attribute(dllimport))
#elif defined(_MSC_VER) || (UPRV_HAS_DECLSPEC_ATTRIBUTE(dllexport) && \
UPRV_HAS_DECLSPEC_ATTRIBUTE(dllimport))
# define U_EXPORT __declspec(dllexport)
#elif defined(__GNUC__)
# define U_EXPORT __attribute__((visibility("default")))
@@ -810,7 +839,8 @@ namespace std {
#ifdef U_IMPORT
/* Use the predefined value. */
#elif defined(_MSC_VER) || (__has_declspec_attribute(dllexport) && __has_declspec_attribute(dllimport))
#elif defined(_MSC_VER) || (UPRV_HAS_DECLSPEC_ATTRIBUTE(dllexport) && \
UPRV_HAS_DECLSPEC_ATTRIBUTE(dllimport))
/* Windows needs to export/import data. */
# define U_IMPORT __declspec(dllimport)
#else
@@ -852,4 +882,4 @@ namespace std {
#endif
/* @} */
#endif
#endif // _PLATFORM_H
+10 -5
View File
@@ -18,6 +18,8 @@
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: Rule Based Break Iterator
@@ -272,7 +274,7 @@ public:
* @return a newly-constructed RuleBasedBreakIterator
* @stable ICU 2.0
*/
virtual BreakIterator* clone() const;
virtual RuleBasedBreakIterator* clone() const;
/**
* Compute a hash code for this BreakIterator
@@ -536,6 +538,7 @@ public:
*/
static UClassID U_EXPORT2 getStaticClassID(void);
#ifndef U_FORCE_HIDE_DEPRECATED_API
/**
* Deprecated functionality. Use clone() instead.
*
@@ -562,10 +565,10 @@ public:
* or if the stackBuffer was too small to hold the clone.
* @deprecated ICU 52. Use clone() instead.
*/
virtual BreakIterator * createBufferClone(void *stackBuffer,
int32_t &BufferSize,
UErrorCode &status);
virtual RuleBasedBreakIterator *createBufferClone(void *stackBuffer,
int32_t &BufferSize,
UErrorCode &status);
#endif // U_FORCE_HIDE_DEPRECATED_API
/**
* Return the binary form of compiled break rules,
@@ -696,4 +699,6 @@ U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_BREAK_ITERATION */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif
+6 -3
View File
@@ -16,6 +16,10 @@
#ifndef REP_H
#define REP_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/uobject.h"
/**
@@ -189,9 +193,6 @@ public:
* Clones can be used concurrently in multiple threads.
* If a subclass does not implement clone(), or if an error occurs,
* then NULL is returned.
* The clone functions in all subclasses return a pointer to a Replaceable
* because some compilers do not support covariant (same-as-this)
* return types; cast to the appropriate subclass if necessary.
* The caller must delete the clone.
*
* @return a clone of this object
@@ -260,4 +261,6 @@ Replaceable::char32At(int32_t offset) const {
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif
+6
View File
@@ -49,6 +49,9 @@
#define RESBUND_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/uobject.h"
#include "unicode/ures.h"
#include "unicode/unistr.h"
@@ -489,4 +492,7 @@ private:
};
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif
+7 -1
View File
@@ -21,6 +21,9 @@
#define SCHRITER_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/chariter.h"
#include "unicode/uchriter.h"
@@ -130,7 +133,7 @@ public:
* @return the newly cloned object.
* @stable ICU 2.0
*/
virtual CharacterIterator* clone(void) const;
virtual StringCharacterIterator* clone() const;
/**
* Sets the iterator to iterate over the provided string.
@@ -186,4 +189,7 @@ protected:
};
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif
@@ -17,6 +17,9 @@
*/
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/unistr.h"
U_NAMESPACE_BEGIN
@@ -333,4 +336,6 @@ private:
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __SIMPLEFORMATTER_H__
+4
View File
@@ -27,6 +27,8 @@
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
// Workaround for a libstdc++ bug before libstdc++4.6 (2011).
// https://bugs.llvm.org/show_bug.cgi?id=13364
#if defined(__GLIBCXX__)
@@ -34,4 +36,6 @@ namespace std { class type_info; }
#endif
#include <string>
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __STD_STRING_H__
+6 -3
View File
@@ -12,6 +12,10 @@
#ifndef STRENUM_H
#define STRENUM_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/uobject.h"
#include "unicode/unistr.h"
@@ -67,9 +71,6 @@ public:
* Clones can be used concurrently in multiple threads.
* If a subclass does not implement clone(), or if an error occurs,
* then NULL is returned.
* The clone functions in all subclasses return a base class pointer
* because some compilers do not support covariant (same-as-this)
* return types; cast to the appropriate subclass if necessary.
* The caller must delete the clone.
*
* @return a clone of this object
@@ -274,5 +275,7 @@ protected:
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
/* STRENUM_H */
#endif
+35
View File
@@ -28,6 +28,12 @@
*/
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include <cstddef>
#include <type_traits>
#include "unicode/uobject.h"
#include "unicode/std_string.h"
@@ -74,6 +80,33 @@ class U_COMMON_API StringPiece : public UMemory {
*/
StringPiece(const std::string& str)
: ptr_(str.data()), length_(static_cast<int32_t>(str.size())) { }
#ifndef U_HIDE_DRAFT_API
/**
* Constructs from some other implementation of a string piece class, from any
* C++ record type that has these two methods:
*
* \code{.cpp}
*
* struct OtherStringPieceClass {
* const char* data();
* size_t size();
* };
*
* \endcode
*
* The other string piece class will typically be std::string_view from C++17
* or absl::string_view from Abseil.
*
* @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().size()), size_t>::value>::type>
StringPiece(T str)
: ptr_(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)
@@ -221,4 +254,6 @@ inline UBool operator!=(const StringPiece& x, const StringPiece& y) {
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __STRINGPIECE_H__
Loaded 100 of 453 files, more files were not shown because too many files have changed in this diff. Show more