Path: blob/master/libs/icui18n/collationdatabuilder.cpp
12343 views
// © 2016 and later: Unicode, Inc. and others.1// License & terms of use: http://www.unicode.org/copyright.html2/*3*******************************************************************************4* Copyright (C) 2012-2015, International Business Machines5* Corporation and others. All Rights Reserved.6*******************************************************************************7* collationdatabuilder.cpp8*9* (replaced the former ucol_elm.cpp)10*11* created on: 2012apr0112* created by: Markus W. Scherer13*/1415#include "unicode/utypes.h"1617#if !UCONFIG_NO_COLLATION1819#include "unicode/localpointer.h"20#include "unicode/uchar.h"21#include "unicode/ucharstrie.h"22#include "unicode/ucharstriebuilder.h"23#include "unicode/uniset.h"24#include "unicode/unistr.h"25#include "unicode/usetiter.h"26#include "unicode/utf16.h"27#include "cmemory.h"28#include "collation.h"29#include "collationdata.h"30#include "collationdatabuilder.h"31#include "collationfastlatinbuilder.h"32#include "collationiterator.h"33#include "normalizer2impl.h"34#include "utrie2.h"35#include "uvectr32.h"36#include "uvectr64.h"37#include "uvector.h"3839U_NAMESPACE_BEGIN4041CollationDataBuilder::CEModifier::~CEModifier() {}4243/**44* Build-time context and CE32 for a code point.45* If a code point has contextual mappings, then the default (no-context) mapping46* and all conditional mappings are stored in a singly-linked list47* of ConditionalCE32, sorted by context strings.48*49* Context strings sort by prefix length, then by prefix, then by contraction suffix.50* Context strings must be unique and in ascending order.51*/52struct ConditionalCE32 : public UMemory {53ConditionalCE32()54: context(),55ce32(0), defaultCE32(Collation::NO_CE32), builtCE32(Collation::NO_CE32),56next(-1) {}57ConditionalCE32(const UnicodeString &ct, uint32_t ce)58: context(ct),59ce32(ce), defaultCE32(Collation::NO_CE32), builtCE32(Collation::NO_CE32),60next(-1) {}6162inline UBool hasContext() const { return context.length() > 1; }63inline int32_t prefixLength() const { return context.charAt(0); }6465/**66* "\0" for the first entry for any code point, with its default CE32.67*68* Otherwise one unit with the length of the prefix string,69* then the prefix string, then the contraction suffix.70*/71UnicodeString context;72/**73* CE32 for the code point and its context.74* Can be special (e.g., for an expansion) but not contextual (prefix or contraction tag).75*/76uint32_t ce32;77/**78* Default CE32 for all contexts with this same prefix.79* Initially NO_CE32. Set only while building runtime data structures,80* and only on one of the nodes of a sub-list with the same prefix.81*/82uint32_t defaultCE32;83/**84* CE32 for the built contexts.85* When fetching CEs from the builder, the contexts are built into their runtime form86* so that the normal collation implementation can process them.87* The result is cached in the list head. It is reset when the contexts are modified.88* All of these builtCE32 are invalidated by clearContexts(),89* via incrementing the contextsEra.90*/91uint32_t builtCE32;92/**93* The "era" of building intermediate contexts when the above builtCE32 was set.94* When the array of cached, temporary contexts overflows, then clearContexts()95* removes them all and invalidates the builtCE32 that used to point to built tries.96*/97int32_t era = -1;98/**99* Index of the next ConditionalCE32.100* Negative for the end of the list.101*/102int32_t next;103// Note: We could create a separate class for all of the contextual mappings for104// a code point, with the builtCE32, the era, and a list of the actual mappings.105// The class that represents one mapping would then not need to106// store those fields in each element.107};108109U_CDECL_BEGIN110111void U_CALLCONV112uprv_deleteConditionalCE32(void *obj) {113delete static_cast<ConditionalCE32 *>(obj);114}115116U_CDECL_END117118/**119* Build-time collation element and character iterator.120* Uses the runtime CollationIterator for fetching CEs for a string121* but reads from the builder's unfinished data structures.122* In particular, this class reads from the unfinished trie123* and has to avoid CollationIterator::nextCE() and redirect other124* calls to data->getCE32() and data->getCE32FromSupplementary().125*126* We do this so that we need not implement the collation algorithm127* again for the builder and make it behave exactly like the runtime code.128* That would be more difficult to test and maintain than this indirection.129*130* Some CE32 tags (for example, the DIGIT_TAG) do not occur in the builder data,131* so the data accesses from those code paths need not be modified.132*133* This class iterates directly over whole code points134* so that the CollationIterator does not need the finished trie135* for handling the LEAD_SURROGATE_TAG.136*/137class DataBuilderCollationIterator : public CollationIterator {138public:139DataBuilderCollationIterator(CollationDataBuilder &b);140141virtual ~DataBuilderCollationIterator();142143int32_t fetchCEs(const UnicodeString &str, int32_t start, int64_t ces[], int32_t cesLength);144145virtual void resetToOffset(int32_t newOffset) override;146virtual int32_t getOffset() const override;147148virtual UChar32 nextCodePoint(UErrorCode &errorCode) override;149virtual UChar32 previousCodePoint(UErrorCode &errorCode) override;150151protected:152virtual void forwardNumCodePoints(int32_t num, UErrorCode &errorCode) override;153virtual void backwardNumCodePoints(int32_t num, UErrorCode &errorCode) override;154155virtual uint32_t getDataCE32(UChar32 c) const override;156virtual uint32_t getCE32FromBuilderData(uint32_t ce32, UErrorCode &errorCode) override;157158CollationDataBuilder &builder;159CollationData builderData;160uint32_t jamoCE32s[CollationData::JAMO_CE32S_LENGTH];161const UnicodeString *s;162int32_t pos;163};164165DataBuilderCollationIterator::DataBuilderCollationIterator(CollationDataBuilder &b)166: CollationIterator(&builderData, /*numeric=*/ false),167builder(b), builderData(b.nfcImpl),168s(NULL), pos(0) {169builderData.base = builder.base;170// Set all of the jamoCE32s[] to indirection CE32s.171for(int32_t j = 0; j < CollationData::JAMO_CE32S_LENGTH; ++j) { // Count across Jamo types.172UChar32 jamo = CollationDataBuilder::jamoCpFromIndex(j);173jamoCE32s[j] = Collation::makeCE32FromTagAndIndex(Collation::BUILDER_DATA_TAG, jamo) |174CollationDataBuilder::IS_BUILDER_JAMO_CE32;175}176builderData.jamoCE32s = jamoCE32s;177}178179DataBuilderCollationIterator::~DataBuilderCollationIterator() {}180181int32_t182DataBuilderCollationIterator::fetchCEs(const UnicodeString &str, int32_t start,183int64_t ces[], int32_t cesLength) {184// Set the pointers each time, in case they changed due to reallocation.185builderData.ce32s = reinterpret_cast<const uint32_t *>(builder.ce32s.getBuffer());186builderData.ces = builder.ce64s.getBuffer();187builderData.contexts = builder.contexts.getBuffer();188// Modified copy of CollationIterator::nextCE() and CollationIterator::nextCEFromCE32().189reset();190s = &str;191pos = start;192UErrorCode errorCode = U_ZERO_ERROR;193while(U_SUCCESS(errorCode) && pos < s->length()) {194// No need to keep all CEs in the iterator buffer.195clearCEs();196UChar32 c = s->char32At(pos);197pos += U16_LENGTH(c);198uint32_t ce32 = utrie2_get32(builder.trie, c);199const CollationData *d;200if(ce32 == Collation::FALLBACK_CE32) {201d = builder.base;202ce32 = builder.base->getCE32(c);203} else {204d = &builderData;205}206appendCEsFromCE32(d, c, ce32, /*forward=*/ true, errorCode);207U_ASSERT(U_SUCCESS(errorCode));208for(int32_t i = 0; i < getCEsLength(); ++i) {209int64_t ce = getCE(i);210if(ce != 0) {211if(cesLength < Collation::MAX_EXPANSION_LENGTH) {212ces[cesLength] = ce;213}214++cesLength;215}216}217}218return cesLength;219}220221void222DataBuilderCollationIterator::resetToOffset(int32_t newOffset) {223reset();224pos = newOffset;225}226227int32_t228DataBuilderCollationIterator::getOffset() const {229return pos;230}231232UChar32233DataBuilderCollationIterator::nextCodePoint(UErrorCode & /*errorCode*/) {234if(pos == s->length()) {235return U_SENTINEL;236}237UChar32 c = s->char32At(pos);238pos += U16_LENGTH(c);239return c;240}241242UChar32243DataBuilderCollationIterator::previousCodePoint(UErrorCode & /*errorCode*/) {244if(pos == 0) {245return U_SENTINEL;246}247UChar32 c = s->char32At(pos - 1);248pos -= U16_LENGTH(c);249return c;250}251252void253DataBuilderCollationIterator::forwardNumCodePoints(int32_t num, UErrorCode & /*errorCode*/) {254pos = s->moveIndex32(pos, num);255}256257void258DataBuilderCollationIterator::backwardNumCodePoints(int32_t num, UErrorCode & /*errorCode*/) {259pos = s->moveIndex32(pos, -num);260}261262uint32_t263DataBuilderCollationIterator::getDataCE32(UChar32 c) const {264return utrie2_get32(builder.trie, c);265}266267uint32_t268DataBuilderCollationIterator::getCE32FromBuilderData(uint32_t ce32, UErrorCode &errorCode) {269if (U_FAILURE(errorCode)) { return 0; }270U_ASSERT(Collation::hasCE32Tag(ce32, Collation::BUILDER_DATA_TAG));271if((ce32 & CollationDataBuilder::IS_BUILDER_JAMO_CE32) != 0) {272UChar32 jamo = Collation::indexFromCE32(ce32);273return utrie2_get32(builder.trie, jamo);274} else {275ConditionalCE32 *cond = builder.getConditionalCE32ForCE32(ce32);276if (cond == nullptr) {277errorCode = U_INTERNAL_PROGRAM_ERROR;278// TODO: ICU-21531 figure out why this happens.279return 0;280}281if(cond->builtCE32 == Collation::NO_CE32 || cond->era != builder.contextsEra) {282// Build the context-sensitive mappings into their runtime form and cache the result.283cond->builtCE32 = builder.buildContext(cond, errorCode);284if(errorCode == U_BUFFER_OVERFLOW_ERROR) {285errorCode = U_ZERO_ERROR;286builder.clearContexts();287cond->builtCE32 = builder.buildContext(cond, errorCode);288}289cond->era = builder.contextsEra;290builderData.contexts = builder.contexts.getBuffer();291}292return cond->builtCE32;293}294}295296// ------------------------------------------------------------------------- ***297298CollationDataBuilder::CollationDataBuilder(UBool icu4xMode, UErrorCode &errorCode)299: nfcImpl(*Normalizer2Factory::getNFCImpl(errorCode)),300base(NULL), baseSettings(NULL),301trie(NULL),302ce32s(errorCode), ce64s(errorCode), conditionalCE32s(errorCode),303modified(false),304icu4xMode(icu4xMode),305fastLatinEnabled(false), fastLatinBuilder(NULL),306collIter(NULL) {307// Reserve the first CE32 for U+0000.308if (!icu4xMode) {309ce32s.addElement(0, errorCode);310}311conditionalCE32s.setDeleter(uprv_deleteConditionalCE32);312}313314CollationDataBuilder::~CollationDataBuilder() {315utrie2_close(trie);316delete fastLatinBuilder;317delete collIter;318}319320void321CollationDataBuilder::initForTailoring(const CollationData *b, UErrorCode &errorCode) {322if(U_FAILURE(errorCode)) { return; }323if(trie != NULL) {324errorCode = U_INVALID_STATE_ERROR;325return;326}327if(b == NULL) {328errorCode = U_ILLEGAL_ARGUMENT_ERROR;329return;330}331base = b;332333// For a tailoring, the default is to fall back to the base.334// For ICU4X, use the same value for fallback as for the default335// to avoid having to have different blocks for the two.336trie = utrie2_open(Collation::FALLBACK_CE32, icu4xMode ? Collation::FALLBACK_CE32 : Collation::FFFD_CE32, &errorCode);337338if (!icu4xMode) {339// Set the Latin-1 letters block so that it is allocated first in the data array,340// to try to improve locality of reference when sorting Latin-1 text.341// Do not use utrie2_setRange32() since that will not actually allocate blocks342// that are filled with the default value.343// ASCII (0..7F) is already preallocated anyway.344for(UChar32 c = 0xc0; c <= 0xff; ++c) {345utrie2_set32(trie, c, Collation::FALLBACK_CE32, &errorCode);346}347348// Hangul syllables are not tailorable (except via tailoring Jamos).349// Always set the Hangul tag to help performance.350// Do this here, rather than in buildMappings(),351// so that we see the HANGUL_TAG in various assertions.352uint32_t hangulCE32 = Collation::makeCE32FromTagAndIndex(Collation::HANGUL_TAG, 0);353utrie2_setRange32(trie, Hangul::HANGUL_BASE, Hangul::HANGUL_END, hangulCE32, true, &errorCode);354355// Copy the set contents but don't copy/clone the set as a whole because356// that would copy the isFrozen state too.357unsafeBackwardSet.addAll(*b->unsafeBackwardSet);358}359360if(U_FAILURE(errorCode)) { return; }361}362363UBool364CollationDataBuilder::maybeSetPrimaryRange(UChar32 start, UChar32 end,365uint32_t primary, int32_t step,366UErrorCode &errorCode) {367if(U_FAILURE(errorCode)) { return false; }368U_ASSERT(start <= end);369// TODO: Do we need to check what values are currently set for start..end?370// An offset range is worth it only if we can achieve an overlap between371// adjacent UTrie2 blocks of 32 code points each.372// An offset CE is also a little more expensive to look up and compute373// than a simple CE.374// If the range spans at least three UTrie2 block boundaries (> 64 code points),375// then we take it.376// If the range spans one or two block boundaries and there are377// at least 4 code points on either side, then we take it.378// (We could additionally require a minimum range length of, say, 16.)379int32_t blockDelta = (end >> 5) - (start >> 5);380if(2 <= step && step <= 0x7f &&381(blockDelta >= 3 ||382(blockDelta > 0 && (start & 0x1f) <= 0x1c && (end & 0x1f) >= 3))) {383int64_t dataCE = ((int64_t)primary << 32) | (start << 8) | step;384if(isCompressiblePrimary(primary)) { dataCE |= 0x80; }385int32_t index = addCE(dataCE, errorCode);386if(U_FAILURE(errorCode)) { return 0; }387if(index > Collation::MAX_INDEX) {388errorCode = U_BUFFER_OVERFLOW_ERROR;389return 0;390}391uint32_t offsetCE32 = Collation::makeCE32FromTagAndIndex(Collation::OFFSET_TAG, index);392utrie2_setRange32(trie, start, end, offsetCE32, true, &errorCode);393modified = true;394return true;395} else {396return false;397}398}399400uint32_t401CollationDataBuilder::setPrimaryRangeAndReturnNext(UChar32 start, UChar32 end,402uint32_t primary, int32_t step,403UErrorCode &errorCode) {404if(U_FAILURE(errorCode)) { return 0; }405UBool isCompressible = isCompressiblePrimary(primary);406if(maybeSetPrimaryRange(start, end, primary, step, errorCode)) {407return Collation::incThreeBytePrimaryByOffset(primary, isCompressible,408(end - start + 1) * step);409} else {410// Short range: Set individual CE32s.411for(;;) {412utrie2_set32(trie, start, Collation::makeLongPrimaryCE32(primary), &errorCode);413++start;414primary = Collation::incThreeBytePrimaryByOffset(primary, isCompressible, step);415if(start > end) { return primary; }416}417modified = true;418}419}420421uint32_t422CollationDataBuilder::getCE32FromOffsetCE32(UBool fromBase, UChar32 c, uint32_t ce32) const {423int32_t i = Collation::indexFromCE32(ce32);424int64_t dataCE = fromBase ? base->ces[i] : ce64s.elementAti(i);425uint32_t p = Collation::getThreeBytePrimaryForOffsetData(c, dataCE);426return Collation::makeLongPrimaryCE32(p);427}428429UBool430CollationDataBuilder::isCompressibleLeadByte(uint32_t b) const {431return base->isCompressibleLeadByte(b);432}433434UBool435CollationDataBuilder::isAssigned(UChar32 c) const {436return Collation::isAssignedCE32(utrie2_get32(trie, c));437}438439uint32_t440CollationDataBuilder::getLongPrimaryIfSingleCE(UChar32 c) const {441uint32_t ce32 = utrie2_get32(trie, c);442if(Collation::isLongPrimaryCE32(ce32)) {443return Collation::primaryFromLongPrimaryCE32(ce32);444} else {445return 0;446}447}448449int64_t450CollationDataBuilder::getSingleCE(UChar32 c, UErrorCode &errorCode) const {451if(U_FAILURE(errorCode)) { return 0; }452// Keep parallel with CollationData::getSingleCE().453UBool fromBase = false;454uint32_t ce32 = utrie2_get32(trie, c);455if(ce32 == Collation::FALLBACK_CE32) {456fromBase = true;457ce32 = base->getCE32(c);458}459while(Collation::isSpecialCE32(ce32)) {460switch(Collation::tagFromCE32(ce32)) {461case Collation::LATIN_EXPANSION_TAG:462case Collation::BUILDER_DATA_TAG:463case Collation::PREFIX_TAG:464case Collation::CONTRACTION_TAG:465case Collation::HANGUL_TAG:466case Collation::LEAD_SURROGATE_TAG:467errorCode = U_UNSUPPORTED_ERROR;468return 0;469case Collation::FALLBACK_TAG:470case Collation::RESERVED_TAG_3:471errorCode = U_INTERNAL_PROGRAM_ERROR;472return 0;473case Collation::LONG_PRIMARY_TAG:474return Collation::ceFromLongPrimaryCE32(ce32);475case Collation::LONG_SECONDARY_TAG:476return Collation::ceFromLongSecondaryCE32(ce32);477case Collation::EXPANSION32_TAG:478if(Collation::lengthFromCE32(ce32) == 1) {479int32_t i = Collation::indexFromCE32(ce32);480ce32 = fromBase ? base->ce32s[i] : ce32s.elementAti(i);481break;482} else {483errorCode = U_UNSUPPORTED_ERROR;484return 0;485}486case Collation::EXPANSION_TAG: {487if(Collation::lengthFromCE32(ce32) == 1) {488int32_t i = Collation::indexFromCE32(ce32);489return fromBase ? base->ces[i] : ce64s.elementAti(i);490} else {491errorCode = U_UNSUPPORTED_ERROR;492return 0;493}494}495case Collation::DIGIT_TAG:496// Fetch the non-numeric-collation CE32 and continue.497ce32 = ce32s.elementAti(Collation::indexFromCE32(ce32));498break;499case Collation::U0000_TAG:500U_ASSERT(c == 0);501// Fetch the normal ce32 for U+0000 and continue.502ce32 = fromBase ? base->ce32s[0] : ce32s.elementAti(0);503break;504case Collation::OFFSET_TAG:505ce32 = getCE32FromOffsetCE32(fromBase, c, ce32);506break;507case Collation::IMPLICIT_TAG:508return Collation::unassignedCEFromCodePoint(c);509}510}511return Collation::ceFromSimpleCE32(ce32);512}513514int32_t515CollationDataBuilder::addCE(int64_t ce, UErrorCode &errorCode) {516int32_t length = ce64s.size();517for(int32_t i = 0; i < length; ++i) {518if(ce == ce64s.elementAti(i)) { return i; }519}520ce64s.addElement(ce, errorCode);521return length;522}523524int32_t525CollationDataBuilder::addCE32(uint32_t ce32, UErrorCode &errorCode) {526int32_t length = ce32s.size();527for(int32_t i = 0; i < length; ++i) {528if(ce32 == (uint32_t)ce32s.elementAti(i)) { return i; }529}530ce32s.addElement((int32_t)ce32, errorCode);531return length;532}533534int32_t535CollationDataBuilder::addConditionalCE32(const UnicodeString &context, uint32_t ce32,536UErrorCode &errorCode) {537if(U_FAILURE(errorCode)) { return -1; }538U_ASSERT(!context.isEmpty());539int32_t index = conditionalCE32s.size();540if(index > Collation::MAX_INDEX) {541errorCode = U_BUFFER_OVERFLOW_ERROR;542return -1;543}544LocalPointer<ConditionalCE32> cond(new ConditionalCE32(context, ce32), errorCode);545conditionalCE32s.adoptElement(cond.orphan(), errorCode);546if(U_FAILURE(errorCode)) {547return -1;548}549return index;550}551552void553CollationDataBuilder::add(const UnicodeString &prefix, const UnicodeString &s,554const int64_t ces[], int32_t cesLength,555UErrorCode &errorCode) {556uint32_t ce32 = encodeCEs(ces, cesLength, errorCode);557addCE32(prefix, s, ce32, errorCode);558}559560void561CollationDataBuilder::addCE32(const UnicodeString &prefix, const UnicodeString &s,562uint32_t ce32, UErrorCode &errorCode) {563if(U_FAILURE(errorCode)) { return; }564if(s.isEmpty()) {565errorCode = U_ILLEGAL_ARGUMENT_ERROR;566return;567}568if(trie == NULL || utrie2_isFrozen(trie)) {569errorCode = U_INVALID_STATE_ERROR;570return;571}572UChar32 c = s.char32At(0);573int32_t cLength = U16_LENGTH(c);574uint32_t oldCE32 = utrie2_get32(trie, c);575UBool hasContext = !prefix.isEmpty() || s.length() > cLength;576577if (icu4xMode) {578if (base && c >= 0x1100 && c < 0x1200) {579// Omit jamo tailorings.580// TODO(https://github.com/unicode-org/icu4x/issues/1941).581}582const Normalizer2* nfdNormalizer = Normalizer2::getNFDInstance(errorCode);583UnicodeString sInNfd;584nfdNormalizer->normalize(s, sInNfd, errorCode);585if (s != sInNfd) {586// s is not in NFD, so it cannot match in ICU4X, since ICU4X only587// does NFD lookups.588// Now check that we're only rejecting known cases.589if (s.length() == 2) {590char16_t second = s.charAt(1);591if (second == 0x0F73 || second == 0x0F75 || second == 0x0F81) {592// Second is a special decomposing Tibetan vowel sign.593// These also get added in the decomposed form, so ignoring594// this instance is OK.595return;596}597if (c == 0xFDD1 && second == 0xAC00) {598// This strange contraction exists in the root and599// doesn't have a decomposed counterpart there.600// This won't match in ICU4X anyway and is very strange:601// Unassigned Arabic presentation form contracting with602// the very first Hangul syllable. Let's ignore this603// explicitly.604return;605}606}607// Unknown case worth investigating if ever found.608errorCode = U_UNSUPPORTED_ERROR;609return;610}611612if (!prefix.isEmpty()) {613UnicodeString prefixInNfd;614nfdNormalizer->normalize(prefix, prefixInNfd, errorCode);615if (prefix != prefixInNfd) {616errorCode = U_UNSUPPORTED_ERROR;617return;618}619620int32_t count = prefix.countChar32();621if (count > 2) {622// Prefix too long for ICU4X.623errorCode = U_UNSUPPORTED_ERROR;624return;625}626UChar32 utf32[4];627int32_t len = prefix.toUTF32(utf32, 4, errorCode);628if (len != count) {629errorCode = U_INVALID_STATE_ERROR;630return;631}632UChar32 c = utf32[0];633if (u_getCombiningClass(c)) {634// Prefix must start with as starter for ICU4X.635errorCode = U_UNSUPPORTED_ERROR;636return;637}638// XXX: Korean searchjl has jamo in prefix, so commenting out this639// check for now. ICU4X currently ignores non-root jamo tables anyway.640// searchjl was added in641// https://unicode-org.atlassian.net/browse/CLDR-3560642// Contractions were changed to prefixes in643// https://unicode-org.atlassian.net/browse/CLDR-6546644//645// if ((c >= 0x1100 && c < 0x1200) || (c >= 0xAC00 && c < 0xD7A4)) {646// errorCode = U_UNSUPPORTED_ERROR;647// return;648// }649if ((len > 1) && !(utf32[1] == 0x3099 || utf32[1] == 0x309A)) {650// Second character in prefix, if present, must be a kana voicing mark for ICU4X.651errorCode = U_UNSUPPORTED_ERROR;652return;653}654}655656if (s.length() > cLength) {657// Check that there's no modern Hangul in contractions.658for (int32_t i = 0; i < s.length(); ++i) {659UChar c = s.charAt(i);660if ((c >= 0x1100 && c < 0x1100 + 19) || (c >= 0x1161 && c < 0x1161 + 21) || (c >= 0x11A7 && c < 0x11A7 + 28) || (c >= 0xAC00 && c < 0xD7A4)) {661errorCode = U_UNSUPPORTED_ERROR;662return;663}664}665}666}667668if(oldCE32 == Collation::FALLBACK_CE32) {669// First tailoring for c.670// If c has contextual base mappings or if we add a contextual mapping,671// then copy the base mappings.672// Otherwise we just override the base mapping.673uint32_t baseCE32 = base->getFinalCE32(base->getCE32(c));674if(hasContext || Collation::ce32HasContext(baseCE32)) {675oldCE32 = copyFromBaseCE32(c, baseCE32, true, errorCode);676utrie2_set32(trie, c, oldCE32, &errorCode);677if(U_FAILURE(errorCode)) { return; }678}679}680if(!hasContext) {681// No prefix, no contraction.682if(!isBuilderContextCE32(oldCE32)) {683utrie2_set32(trie, c, ce32, &errorCode);684} else {685ConditionalCE32 *cond = getConditionalCE32ForCE32(oldCE32);686cond->builtCE32 = Collation::NO_CE32;687cond->ce32 = ce32;688}689} else {690ConditionalCE32 *cond;691if(!isBuilderContextCE32(oldCE32)) {692// Replace the simple oldCE32 with a builder context CE32693// pointing to a new ConditionalCE32 list head.694int32_t index = addConditionalCE32(UnicodeString((UChar)0), oldCE32, errorCode);695if(U_FAILURE(errorCode)) { return; }696uint32_t contextCE32 = makeBuilderContextCE32(index);697utrie2_set32(trie, c, contextCE32, &errorCode);698contextChars.add(c);699cond = getConditionalCE32(index);700} else {701cond = getConditionalCE32ForCE32(oldCE32);702cond->builtCE32 = Collation::NO_CE32;703}704UnicodeString suffix(s, cLength);705UnicodeString context((UChar)prefix.length());706context.append(prefix).append(suffix);707unsafeBackwardSet.addAll(suffix);708for(;;) {709// invariant: context > cond->context710int32_t next = cond->next;711if(next < 0) {712// Append a new ConditionalCE32 after cond.713int32_t index = addConditionalCE32(context, ce32, errorCode);714if(U_FAILURE(errorCode)) { return; }715cond->next = index;716break;717}718ConditionalCE32 *nextCond = getConditionalCE32(next);719int8_t cmp = context.compare(nextCond->context);720if(cmp < 0) {721// Insert a new ConditionalCE32 between cond and nextCond.722int32_t index = addConditionalCE32(context, ce32, errorCode);723if(U_FAILURE(errorCode)) { return; }724cond->next = index;725getConditionalCE32(index)->next = next;726break;727} else if(cmp == 0) {728// Same context as before, overwrite its ce32.729nextCond->ce32 = ce32;730break;731}732cond = nextCond;733}734}735modified = true;736}737738uint32_t739CollationDataBuilder::encodeOneCEAsCE32(int64_t ce) {740uint32_t p = (uint32_t)(ce >> 32);741uint32_t lower32 = (uint32_t)ce;742uint32_t t = (uint32_t)(ce & 0xffff);743U_ASSERT((t & 0xc000) != 0xc000); // Impossible case bits 11 mark special CE32s.744if((ce & INT64_C(0xffff00ff00ff)) == 0) {745// normal form ppppsstt746return p | (lower32 >> 16) | (t >> 8);747} else if((ce & INT64_C(0xffffffffff)) == Collation::COMMON_SEC_AND_TER_CE) {748// long-primary form ppppppC1749return Collation::makeLongPrimaryCE32(p);750} else if(p == 0 && (t & 0xff) == 0) {751// long-secondary form ssssttC2752return Collation::makeLongSecondaryCE32(lower32);753}754return Collation::NO_CE32;755}756757uint32_t758CollationDataBuilder::encodeOneCE(int64_t ce, UErrorCode &errorCode) {759// Try to encode one CE as one CE32.760uint32_t ce32 = encodeOneCEAsCE32(ce);761if(ce32 != Collation::NO_CE32) { return ce32; }762int32_t index = addCE(ce, errorCode);763if(U_FAILURE(errorCode)) { return 0; }764if(index > Collation::MAX_INDEX) {765errorCode = U_BUFFER_OVERFLOW_ERROR;766return 0;767}768return Collation::makeCE32FromTagIndexAndLength(Collation::EXPANSION_TAG, index, 1);769}770771uint32_t772CollationDataBuilder::encodeCEs(const int64_t ces[], int32_t cesLength,773UErrorCode &errorCode) {774if(U_FAILURE(errorCode)) { return 0; }775if(cesLength < 0 || cesLength > Collation::MAX_EXPANSION_LENGTH) {776errorCode = U_ILLEGAL_ARGUMENT_ERROR;777return 0;778}779if(trie == NULL || utrie2_isFrozen(trie)) {780errorCode = U_INVALID_STATE_ERROR;781return 0;782}783if(cesLength == 0) {784// Convenience: We cannot map to nothing, but we can map to a completely ignorable CE.785// Do this here so that callers need not do it.786return encodeOneCEAsCE32(0);787} else if(cesLength == 1) {788return encodeOneCE(ces[0], errorCode);789} else if(cesLength == 2 && !icu4xMode) {790// Try to encode two CEs as one CE32.791// Turn this off for ICU4X, because without the canonical closure792// these are so rare that it doesn't make sense to spend a branch793// on checking this tag when using the data.794int64_t ce0 = ces[0];795int64_t ce1 = ces[1];796uint32_t p0 = (uint32_t)(ce0 >> 32);797if((ce0 & INT64_C(0xffffffffff00ff)) == Collation::COMMON_SECONDARY_CE &&798(ce1 & INT64_C(0xffffffff00ffffff)) == Collation::COMMON_TERTIARY_CE &&799p0 != 0) {800// Latin mini expansion801return802p0 |803(((uint32_t)ce0 & 0xff00u) << 8) |804(uint32_t)(ce1 >> 16) |805Collation::SPECIAL_CE32_LOW_BYTE |806Collation::LATIN_EXPANSION_TAG;807}808}809// Try to encode two or more CEs as CE32s.810int32_t newCE32s[Collation::MAX_EXPANSION_LENGTH];811for(int32_t i = 0;; ++i) {812if(i == cesLength) {813return encodeExpansion32(newCE32s, cesLength, errorCode);814}815uint32_t ce32 = encodeOneCEAsCE32(ces[i]);816if(ce32 == Collation::NO_CE32) { break; }817newCE32s[i] = (int32_t)ce32;818}819return encodeExpansion(ces, cesLength, errorCode);820}821822uint32_t823CollationDataBuilder::encodeExpansion(const int64_t ces[], int32_t length, UErrorCode &errorCode) {824if(U_FAILURE(errorCode)) { return 0; }825// See if this sequence of CEs has already been stored.826int64_t first = ces[0];827int32_t ce64sMax = ce64s.size() - length;828for(int32_t i = 0; i <= ce64sMax; ++i) {829if(first == ce64s.elementAti(i)) {830if(i > Collation::MAX_INDEX) {831errorCode = U_BUFFER_OVERFLOW_ERROR;832return 0;833}834for(int32_t j = 1;; ++j) {835if(j == length) {836return Collation::makeCE32FromTagIndexAndLength(837Collation::EXPANSION_TAG, i, length);838}839if(ce64s.elementAti(i + j) != ces[j]) { break; }840}841}842}843// Store the new sequence.844int32_t i = ce64s.size();845if(i > Collation::MAX_INDEX) {846errorCode = U_BUFFER_OVERFLOW_ERROR;847return 0;848}849for(int32_t j = 0; j < length; ++j) {850ce64s.addElement(ces[j], errorCode);851}852return Collation::makeCE32FromTagIndexAndLength(Collation::EXPANSION_TAG, i, length);853}854855uint32_t856CollationDataBuilder::encodeExpansion32(const int32_t newCE32s[], int32_t length,857UErrorCode &errorCode) {858if(U_FAILURE(errorCode)) { return 0; }859// See if this sequence of CE32s has already been stored.860int32_t first = newCE32s[0];861int32_t ce32sMax = ce32s.size() - length;862for(int32_t i = 0; i <= ce32sMax; ++i) {863if(first == ce32s.elementAti(i)) {864if(i > Collation::MAX_INDEX) {865errorCode = U_BUFFER_OVERFLOW_ERROR;866return 0;867}868for(int32_t j = 1;; ++j) {869if(j == length) {870return Collation::makeCE32FromTagIndexAndLength(871Collation::EXPANSION32_TAG, i, length);872}873if(ce32s.elementAti(i + j) != newCE32s[j]) { break; }874}875}876}877// Store the new sequence.878int32_t i = ce32s.size();879if(i > Collation::MAX_INDEX) {880errorCode = U_BUFFER_OVERFLOW_ERROR;881return 0;882}883for(int32_t j = 0; j < length; ++j) {884ce32s.addElement(newCE32s[j], errorCode);885}886return Collation::makeCE32FromTagIndexAndLength(Collation::EXPANSION32_TAG, i, length);887}888889uint32_t890CollationDataBuilder::copyFromBaseCE32(UChar32 c, uint32_t ce32, UBool withContext,891UErrorCode &errorCode) {892if(U_FAILURE(errorCode)) { return 0; }893if(!Collation::isSpecialCE32(ce32)) { return ce32; }894switch(Collation::tagFromCE32(ce32)) {895case Collation::LONG_PRIMARY_TAG:896case Collation::LONG_SECONDARY_TAG:897case Collation::LATIN_EXPANSION_TAG:898// copy as is899break;900case Collation::EXPANSION32_TAG: {901const uint32_t *baseCE32s = base->ce32s + Collation::indexFromCE32(ce32);902int32_t length = Collation::lengthFromCE32(ce32);903ce32 = encodeExpansion32(904reinterpret_cast<const int32_t *>(baseCE32s), length, errorCode);905break;906}907case Collation::EXPANSION_TAG: {908const int64_t *baseCEs = base->ces + Collation::indexFromCE32(ce32);909int32_t length = Collation::lengthFromCE32(ce32);910ce32 = encodeExpansion(baseCEs, length, errorCode);911break;912}913case Collation::PREFIX_TAG: {914// Flatten prefixes and nested suffixes (contractions)915// into a linear list of ConditionalCE32.916const UChar *p = base->contexts + Collation::indexFromCE32(ce32);917ce32 = CollationData::readCE32(p); // Default if no prefix match.918if(!withContext) {919return copyFromBaseCE32(c, ce32, false, errorCode);920}921ConditionalCE32 head;922UnicodeString context((UChar)0);923int32_t index;924if(Collation::isContractionCE32(ce32)) {925index = copyContractionsFromBaseCE32(context, c, ce32, &head, errorCode);926} else {927ce32 = copyFromBaseCE32(c, ce32, true, errorCode);928head.next = index = addConditionalCE32(context, ce32, errorCode);929}930if(U_FAILURE(errorCode)) { return 0; }931ConditionalCE32 *cond = getConditionalCE32(index); // the last ConditionalCE32 so far932UCharsTrie::Iterator prefixes(p + 2, 0, errorCode);933while(prefixes.next(errorCode)) {934context = prefixes.getString();935context.reverse();936context.insert(0, (UChar)context.length());937ce32 = (uint32_t)prefixes.getValue();938if(Collation::isContractionCE32(ce32)) {939index = copyContractionsFromBaseCE32(context, c, ce32, cond, errorCode);940} else {941ce32 = copyFromBaseCE32(c, ce32, true, errorCode);942cond->next = index = addConditionalCE32(context, ce32, errorCode);943}944if(U_FAILURE(errorCode)) { return 0; }945cond = getConditionalCE32(index);946}947ce32 = makeBuilderContextCE32(head.next);948contextChars.add(c);949break;950}951case Collation::CONTRACTION_TAG: {952if(!withContext) {953const UChar *p = base->contexts + Collation::indexFromCE32(ce32);954ce32 = CollationData::readCE32(p); // Default if no suffix match.955return copyFromBaseCE32(c, ce32, false, errorCode);956}957ConditionalCE32 head;958UnicodeString context((UChar)0);959copyContractionsFromBaseCE32(context, c, ce32, &head, errorCode);960ce32 = makeBuilderContextCE32(head.next);961contextChars.add(c);962break;963}964case Collation::HANGUL_TAG:965errorCode = U_UNSUPPORTED_ERROR; // We forbid tailoring of Hangul syllables.966break;967case Collation::OFFSET_TAG:968ce32 = getCE32FromOffsetCE32(true, c, ce32);969break;970case Collation::IMPLICIT_TAG:971ce32 = encodeOneCE(Collation::unassignedCEFromCodePoint(c), errorCode);972break;973default:974UPRV_UNREACHABLE_EXIT; // require ce32 == base->getFinalCE32(ce32)975}976return ce32;977}978979int32_t980CollationDataBuilder::copyContractionsFromBaseCE32(UnicodeString &context, UChar32 c, uint32_t ce32,981ConditionalCE32 *cond, UErrorCode &errorCode) {982if(U_FAILURE(errorCode)) { return 0; }983const UChar *p = base->contexts + Collation::indexFromCE32(ce32);984int32_t index;985if((ce32 & Collation::CONTRACT_SINGLE_CP_NO_MATCH) != 0) {986// No match on the single code point.987// We are underneath a prefix, and the default mapping is just988// a fallback to the mappings for a shorter prefix.989U_ASSERT(context.length() > 1);990index = -1;991} else {992ce32 = CollationData::readCE32(p); // Default if no suffix match.993U_ASSERT(!Collation::isContractionCE32(ce32));994ce32 = copyFromBaseCE32(c, ce32, true, errorCode);995cond->next = index = addConditionalCE32(context, ce32, errorCode);996if(U_FAILURE(errorCode)) { return 0; }997cond = getConditionalCE32(index);998}9991000int32_t suffixStart = context.length();1001UCharsTrie::Iterator suffixes(p + 2, 0, errorCode);1002while(suffixes.next(errorCode)) {1003context.append(suffixes.getString());1004ce32 = copyFromBaseCE32(c, (uint32_t)suffixes.getValue(), true, errorCode);1005cond->next = index = addConditionalCE32(context, ce32, errorCode);1006if(U_FAILURE(errorCode)) { return 0; }1007// No need to update the unsafeBackwardSet because the tailoring set1008// is already a copy of the base set.1009cond = getConditionalCE32(index);1010context.truncate(suffixStart);1011}1012U_ASSERT(index >= 0);1013return index;1014}10151016class CopyHelper {1017public:1018CopyHelper(const CollationDataBuilder &s, CollationDataBuilder &d,1019const CollationDataBuilder::CEModifier &m, UErrorCode &initialErrorCode)1020: src(s), dest(d), modifier(m),1021errorCode(initialErrorCode) {}10221023UBool copyRangeCE32(UChar32 start, UChar32 end, uint32_t ce32) {1024ce32 = copyCE32(ce32);1025utrie2_setRange32(dest.trie, start, end, ce32, true, &errorCode);1026if(CollationDataBuilder::isBuilderContextCE32(ce32)) {1027dest.contextChars.add(start, end);1028}1029return U_SUCCESS(errorCode);1030}10311032uint32_t copyCE32(uint32_t ce32) {1033if(!Collation::isSpecialCE32(ce32)) {1034int64_t ce = modifier.modifyCE32(ce32);1035if(ce != Collation::NO_CE) {1036ce32 = dest.encodeOneCE(ce, errorCode);1037}1038} else {1039int32_t tag = Collation::tagFromCE32(ce32);1040if(tag == Collation::EXPANSION32_TAG) {1041const uint32_t *srcCE32s = reinterpret_cast<uint32_t *>(src.ce32s.getBuffer());1042srcCE32s += Collation::indexFromCE32(ce32);1043int32_t length = Collation::lengthFromCE32(ce32);1044// Inspect the source CE32s. Just copy them if none are modified.1045// Otherwise copy to modifiedCEs, with modifications.1046UBool isModified = false;1047for(int32_t i = 0; i < length; ++i) {1048ce32 = srcCE32s[i];1049int64_t ce;1050if(Collation::isSpecialCE32(ce32) ||1051(ce = modifier.modifyCE32(ce32)) == Collation::NO_CE) {1052if(isModified) {1053modifiedCEs[i] = Collation::ceFromCE32(ce32);1054}1055} else {1056if(!isModified) {1057for(int32_t j = 0; j < i; ++j) {1058modifiedCEs[j] = Collation::ceFromCE32(srcCE32s[j]);1059}1060isModified = true;1061}1062modifiedCEs[i] = ce;1063}1064}1065if(isModified) {1066ce32 = dest.encodeCEs(modifiedCEs, length, errorCode);1067} else {1068ce32 = dest.encodeExpansion32(1069reinterpret_cast<const int32_t *>(srcCE32s), length, errorCode);1070}1071} else if(tag == Collation::EXPANSION_TAG) {1072const int64_t *srcCEs = src.ce64s.getBuffer();1073srcCEs += Collation::indexFromCE32(ce32);1074int32_t length = Collation::lengthFromCE32(ce32);1075// Inspect the source CEs. Just copy them if none are modified.1076// Otherwise copy to modifiedCEs, with modifications.1077UBool isModified = false;1078for(int32_t i = 0; i < length; ++i) {1079int64_t srcCE = srcCEs[i];1080int64_t ce = modifier.modifyCE(srcCE);1081if(ce == Collation::NO_CE) {1082if(isModified) {1083modifiedCEs[i] = srcCE;1084}1085} else {1086if(!isModified) {1087for(int32_t j = 0; j < i; ++j) {1088modifiedCEs[j] = srcCEs[j];1089}1090isModified = true;1091}1092modifiedCEs[i] = ce;1093}1094}1095if(isModified) {1096ce32 = dest.encodeCEs(modifiedCEs, length, errorCode);1097} else {1098ce32 = dest.encodeExpansion(srcCEs, length, errorCode);1099}1100} else if(tag == Collation::BUILDER_DATA_TAG) {1101// Copy the list of ConditionalCE32.1102ConditionalCE32 *cond = src.getConditionalCE32ForCE32(ce32);1103U_ASSERT(!cond->hasContext());1104int32_t destIndex = dest.addConditionalCE32(1105cond->context, copyCE32(cond->ce32), errorCode);1106ce32 = CollationDataBuilder::makeBuilderContextCE32(destIndex);1107while(cond->next >= 0) {1108cond = src.getConditionalCE32(cond->next);1109ConditionalCE32 *prevDestCond = dest.getConditionalCE32(destIndex);1110destIndex = dest.addConditionalCE32(1111cond->context, copyCE32(cond->ce32), errorCode);1112int32_t suffixStart = cond->prefixLength() + 1;1113dest.unsafeBackwardSet.addAll(cond->context.tempSubString(suffixStart));1114prevDestCond->next = destIndex;1115}1116} else {1117// Just copy long CEs and Latin mini expansions (and other expected values) as is,1118// assuming that the modifier would not modify them.1119U_ASSERT(tag == Collation::LONG_PRIMARY_TAG ||1120tag == Collation::LONG_SECONDARY_TAG ||1121tag == Collation::LATIN_EXPANSION_TAG ||1122tag == Collation::HANGUL_TAG);1123}1124}1125return ce32;1126}11271128const CollationDataBuilder &src;1129CollationDataBuilder &dest;1130const CollationDataBuilder::CEModifier &modifier;1131int64_t modifiedCEs[Collation::MAX_EXPANSION_LENGTH];1132UErrorCode errorCode;1133};11341135U_CDECL_BEGIN11361137static UBool U_CALLCONV1138enumRangeForCopy(const void *context, UChar32 start, UChar32 end, uint32_t value) {1139return1140value == Collation::UNASSIGNED_CE32 || value == Collation::FALLBACK_CE32 ||1141((CopyHelper *)context)->copyRangeCE32(start, end, value);1142}11431144U_CDECL_END11451146void1147CollationDataBuilder::copyFrom(const CollationDataBuilder &src, const CEModifier &modifier,1148UErrorCode &errorCode) {1149if(U_FAILURE(errorCode)) { return; }1150if(trie == NULL || utrie2_isFrozen(trie)) {1151errorCode = U_INVALID_STATE_ERROR;1152return;1153}1154CopyHelper helper(src, *this, modifier, errorCode);1155utrie2_enum(src.trie, NULL, enumRangeForCopy, &helper);1156errorCode = helper.errorCode;1157// Update the contextChars and the unsafeBackwardSet while copying,1158// in case a character had conditional mappings in the source builder1159// and they were removed later.1160modified |= src.modified;1161}11621163void1164CollationDataBuilder::optimize(const UnicodeSet &set, UErrorCode &errorCode) {1165if(U_FAILURE(errorCode) || set.isEmpty()) { return; }1166UnicodeSetIterator iter(set);1167while(iter.next() && !iter.isString()) {1168UChar32 c = iter.getCodepoint();1169uint32_t ce32 = utrie2_get32(trie, c);1170if(ce32 == Collation::FALLBACK_CE32) {1171ce32 = base->getFinalCE32(base->getCE32(c));1172ce32 = copyFromBaseCE32(c, ce32, true, errorCode);1173utrie2_set32(trie, c, ce32, &errorCode);1174}1175}1176modified = true;1177}11781179void1180CollationDataBuilder::suppressContractions(const UnicodeSet &set, UErrorCode &errorCode) {1181if(U_FAILURE(errorCode) || set.isEmpty()) { return; }1182UnicodeSetIterator iter(set);1183while(iter.next() && !iter.isString()) {1184UChar32 c = iter.getCodepoint();1185uint32_t ce32 = utrie2_get32(trie, c);1186if(ce32 == Collation::FALLBACK_CE32) {1187ce32 = base->getFinalCE32(base->getCE32(c));1188if(Collation::ce32HasContext(ce32)) {1189ce32 = copyFromBaseCE32(c, ce32, false /* without context */, errorCode);1190utrie2_set32(trie, c, ce32, &errorCode);1191}1192} else if(isBuilderContextCE32(ce32)) {1193ce32 = getConditionalCE32ForCE32(ce32)->ce32;1194// Simply abandon the list of ConditionalCE32.1195// The caller will copy this builder in the end,1196// eliminating unreachable data.1197utrie2_set32(trie, c, ce32, &errorCode);1198contextChars.remove(c);1199}1200}1201modified = true;1202}12031204UBool1205CollationDataBuilder::getJamoCE32s(uint32_t jamoCE32s[], UErrorCode &errorCode) {1206if(U_FAILURE(errorCode)) { return false; }1207UBool anyJamoAssigned = base == NULL; // always set jamoCE32s in the base data1208UBool needToCopyFromBase = false;1209for(int32_t j = 0; j < CollationData::JAMO_CE32S_LENGTH; ++j) { // Count across Jamo types.1210UChar32 jamo = jamoCpFromIndex(j);1211UBool fromBase = false;1212uint32_t ce32 = utrie2_get32(trie, jamo);1213anyJamoAssigned |= Collation::isAssignedCE32(ce32);1214// TODO: Try to prevent [optimize [Jamo]] from counting as anyJamoAssigned.1215// (As of CLDR 24 [2013] the Korean tailoring does not optimize conjoining Jamo.)1216if(ce32 == Collation::FALLBACK_CE32) {1217fromBase = true;1218ce32 = base->getCE32(jamo);1219}1220if(Collation::isSpecialCE32(ce32)) {1221switch(Collation::tagFromCE32(ce32)) {1222case Collation::LONG_PRIMARY_TAG:1223case Collation::LONG_SECONDARY_TAG:1224case Collation::LATIN_EXPANSION_TAG:1225// Copy the ce32 as-is.1226break;1227case Collation::EXPANSION32_TAG:1228case Collation::EXPANSION_TAG:1229case Collation::PREFIX_TAG:1230case Collation::CONTRACTION_TAG:1231if(fromBase) {1232// Defer copying until we know if anyJamoAssigned.1233ce32 = Collation::FALLBACK_CE32;1234needToCopyFromBase = true;1235}1236break;1237case Collation::IMPLICIT_TAG:1238// An unassigned Jamo should only occur in tests with incomplete bases.1239U_ASSERT(fromBase);1240ce32 = Collation::FALLBACK_CE32;1241needToCopyFromBase = true;1242break;1243case Collation::OFFSET_TAG:1244ce32 = getCE32FromOffsetCE32(fromBase, jamo, ce32);1245break;1246case Collation::FALLBACK_TAG:1247case Collation::RESERVED_TAG_3:1248case Collation::BUILDER_DATA_TAG:1249case Collation::DIGIT_TAG:1250case Collation::U0000_TAG:1251case Collation::HANGUL_TAG:1252case Collation::LEAD_SURROGATE_TAG:1253errorCode = U_INTERNAL_PROGRAM_ERROR;1254return false;1255}1256}1257jamoCE32s[j] = ce32;1258}1259if(anyJamoAssigned && needToCopyFromBase) {1260for(int32_t j = 0; j < CollationData::JAMO_CE32S_LENGTH; ++j) {1261if(jamoCE32s[j] == Collation::FALLBACK_CE32) {1262UChar32 jamo = jamoCpFromIndex(j);1263jamoCE32s[j] = copyFromBaseCE32(jamo, base->getCE32(jamo),1264/*withContext=*/ true, errorCode);1265}1266}1267}1268return anyJamoAssigned && U_SUCCESS(errorCode);1269}12701271void1272CollationDataBuilder::setDigitTags(UErrorCode &errorCode) {1273UnicodeSet digits(UNICODE_STRING_SIMPLE("[:Nd:]"), errorCode);1274if(U_FAILURE(errorCode)) { return; }1275UnicodeSetIterator iter(digits);1276while(iter.next()) {1277U_ASSERT(!iter.isString());1278UChar32 c = iter.getCodepoint();1279uint32_t ce32 = utrie2_get32(trie, c);1280if(ce32 != Collation::FALLBACK_CE32 && ce32 != Collation::UNASSIGNED_CE32) {1281int32_t index = addCE32(ce32, errorCode);1282if(U_FAILURE(errorCode)) { return; }1283if(index > Collation::MAX_INDEX) {1284errorCode = U_BUFFER_OVERFLOW_ERROR;1285return;1286}1287ce32 = Collation::makeCE32FromTagIndexAndLength(1288Collation::DIGIT_TAG, index, u_charDigitValue(c));1289utrie2_set32(trie, c, ce32, &errorCode);1290}1291}1292}12931294U_CDECL_BEGIN12951296static UBool U_CALLCONV1297enumRangeLeadValue(const void *context, UChar32 /*start*/, UChar32 /*end*/, uint32_t value) {1298int32_t *pValue = (int32_t *)context;1299if(value == Collation::UNASSIGNED_CE32) {1300value = Collation::LEAD_ALL_UNASSIGNED;1301} else if(value == Collation::FALLBACK_CE32) {1302value = Collation::LEAD_ALL_FALLBACK;1303} else {1304*pValue = Collation::LEAD_MIXED;1305return false;1306}1307if(*pValue < 0) {1308*pValue = (int32_t)value;1309} else if(*pValue != (int32_t)value) {1310*pValue = Collation::LEAD_MIXED;1311return false;1312}1313return true;1314}13151316U_CDECL_END13171318void1319CollationDataBuilder::setLeadSurrogates(UErrorCode &errorCode) {1320for(UChar lead = 0xd800; lead < 0xdc00; ++lead) {1321int32_t value = -1;1322utrie2_enumForLeadSurrogate(trie, lead, NULL, enumRangeLeadValue, &value);1323utrie2_set32ForLeadSurrogateCodeUnit(1324trie, lead,1325Collation::makeCE32FromTagAndIndex(Collation::LEAD_SURROGATE_TAG, 0) | (uint32_t)value,1326&errorCode);1327}1328}13291330void1331CollationDataBuilder::build(CollationData &data, UErrorCode &errorCode) {1332buildMappings(data, errorCode);1333if(base != NULL) {1334data.numericPrimary = base->numericPrimary;1335data.compressibleBytes = base->compressibleBytes;1336data.numScripts = base->numScripts;1337data.scriptsIndex = base->scriptsIndex;1338data.scriptStarts = base->scriptStarts;1339data.scriptStartsLength = base->scriptStartsLength;1340}1341buildFastLatinTable(data, errorCode);1342}13431344void1345CollationDataBuilder::buildMappings(CollationData &data, UErrorCode &errorCode) {1346if(U_FAILURE(errorCode)) { return; }1347if(trie == NULL || utrie2_isFrozen(trie)) {1348errorCode = U_INVALID_STATE_ERROR;1349return;1350}13511352buildContexts(errorCode);13531354uint32_t jamoCE32s[CollationData::JAMO_CE32S_LENGTH];1355int32_t jamoIndex = -1;1356if(getJamoCE32s(jamoCE32s, errorCode)) {1357jamoIndex = ce32s.size();1358for(int32_t i = 0; i < CollationData::JAMO_CE32S_LENGTH; ++i) {1359ce32s.addElement((int32_t)jamoCE32s[i], errorCode);1360}1361// Small optimization: Use a bit in the Hangul ce321362// to indicate that none of the Jamo CE32s are isSpecialCE32()1363// (as it should be in the root collator).1364// It allows CollationIterator to avoid recursive function calls and per-Jamo tests.1365// In order to still have good trie compression and keep this code simple,1366// we only set this flag if a whole block of 588 Hangul syllables starting with1367// a common leading consonant (Jamo L) has this property.1368UBool isAnyJamoVTSpecial = false;1369for(int32_t i = Hangul::JAMO_L_COUNT; i < CollationData::JAMO_CE32S_LENGTH; ++i) {1370if(Collation::isSpecialCE32(jamoCE32s[i])) {1371isAnyJamoVTSpecial = true;1372break;1373}1374}1375uint32_t hangulCE32 = Collation::makeCE32FromTagAndIndex(Collation::HANGUL_TAG, 0);1376UChar32 c = Hangul::HANGUL_BASE;1377for(int32_t i = 0; i < Hangul::JAMO_L_COUNT; ++i) { // iterate over the Jamo L1378uint32_t ce32 = hangulCE32;1379if(!isAnyJamoVTSpecial && !Collation::isSpecialCE32(jamoCE32s[i])) {1380ce32 |= Collation::HANGUL_NO_SPECIAL_JAMO;1381}1382UChar32 limit = c + Hangul::JAMO_VT_COUNT;1383utrie2_setRange32(trie, c, limit - 1, ce32, true, &errorCode);1384c = limit;1385}1386} else {1387// Copy the Hangul CE32s from the base in blocks per Jamo L,1388// assuming that HANGUL_NO_SPECIAL_JAMO is set or not set for whole blocks.1389for(UChar32 c = Hangul::HANGUL_BASE; c < Hangul::HANGUL_LIMIT;) {1390uint32_t ce32 = base->getCE32(c);1391U_ASSERT(Collation::hasCE32Tag(ce32, Collation::HANGUL_TAG));1392UChar32 limit = c + Hangul::JAMO_VT_COUNT;1393utrie2_setRange32(trie, c, limit - 1, ce32, true, &errorCode);1394c = limit;1395}1396}13971398setDigitTags(errorCode);1399setLeadSurrogates(errorCode);14001401if (!icu4xMode) {1402// For U+0000, move its normal ce32 into CE32s[0] and set U0000_TAG.1403ce32s.setElementAt((int32_t)utrie2_get32(trie, 0), 0);1404utrie2_set32(trie, 0, Collation::makeCE32FromTagAndIndex(Collation::U0000_TAG, 0), &errorCode);1405}14061407utrie2_freeze(trie, UTRIE2_32_VALUE_BITS, &errorCode);1408if(U_FAILURE(errorCode)) { return; }14091410// Mark each lead surrogate as "unsafe"1411// if any of its 1024 associated supplementary code points is "unsafe".1412UChar32 c = 0x10000;1413for(UChar lead = 0xd800; lead < 0xdc00; ++lead, c += 0x400) {1414if(unsafeBackwardSet.containsSome(c, c + 0x3ff)) {1415unsafeBackwardSet.add(lead);1416}1417}1418unsafeBackwardSet.freeze();14191420data.trie = trie;1421data.ce32s = reinterpret_cast<const uint32_t *>(ce32s.getBuffer());1422data.ces = ce64s.getBuffer();1423data.contexts = contexts.getBuffer();14241425data.ce32sLength = ce32s.size();1426data.cesLength = ce64s.size();1427data.contextsLength = contexts.length();14281429data.base = base;1430if(jamoIndex >= 0) {1431data.jamoCE32s = data.ce32s + jamoIndex;1432} else {1433data.jamoCE32s = base->jamoCE32s;1434}1435data.unsafeBackwardSet = &unsafeBackwardSet;1436}14371438void1439CollationDataBuilder::clearContexts() {1440contexts.remove();1441// Incrementing the contexts build "era" invalidates all of the builtCE321442// from before this clearContexts() call.1443// Simpler than finding and resetting all of those fields.1444++contextsEra;1445}14461447void1448CollationDataBuilder::buildContexts(UErrorCode &errorCode) {1449if(U_FAILURE(errorCode)) { return; }1450// Ignore abandoned lists and the cached builtCE32,1451// and build all contexts from scratch.1452clearContexts();1453UnicodeSetIterator iter(contextChars);1454while(U_SUCCESS(errorCode) && iter.next()) {1455U_ASSERT(!iter.isString());1456UChar32 c = iter.getCodepoint();1457uint32_t ce32 = utrie2_get32(trie, c);1458if(!isBuilderContextCE32(ce32)) {1459// Impossible: No context data for c in contextChars.1460errorCode = U_INTERNAL_PROGRAM_ERROR;1461return;1462}1463ConditionalCE32 *cond = getConditionalCE32ForCE32(ce32);1464ce32 = buildContext(cond, errorCode);1465utrie2_set32(trie, c, ce32, &errorCode);1466}1467}14681469uint32_t1470CollationDataBuilder::buildContext(ConditionalCE32 *head, UErrorCode &errorCode) {1471if(U_FAILURE(errorCode)) { return 0; }1472// The list head must have no context.1473U_ASSERT(!head->hasContext());1474// The list head must be followed by one or more nodes that all do have context.1475U_ASSERT(head->next >= 0);1476UCharsTrieBuilder prefixBuilder(errorCode);1477UCharsTrieBuilder contractionBuilder(errorCode);1478// This outer loop goes from each prefix to the next.1479// For each prefix it finds the one or more same-prefix entries (firstCond..lastCond).1480// If there are multiple suffixes for the same prefix,1481// then an inner loop builds a contraction trie for them.1482for(ConditionalCE32 *cond = head;; cond = getConditionalCE32(cond->next)) {1483if(U_FAILURE(errorCode)) { return 0; } // early out for memory allocation errors1484// After the list head, the prefix or suffix can be empty, but not both.1485U_ASSERT(cond == head || cond->hasContext());1486int32_t prefixLength = cond->prefixLength();1487UnicodeString prefix(cond->context, 0, prefixLength + 1);1488// Collect all contraction suffixes for one prefix.1489ConditionalCE32 *firstCond = cond;1490ConditionalCE32 *lastCond;1491do {1492lastCond = cond;1493// Clear the defaultCE32 fields as we go.1494// They are left over from building a previous version of this list of contexts.1495//1496// One of the code paths below may copy a preceding defaultCE321497// into its emptySuffixCE32.1498// If a new suffix has been inserted before what used to be1499// the firstCond for its prefix, then that previous firstCond could still1500// contain an outdated defaultCE32 from an earlier buildContext() and1501// result in an incorrect emptySuffixCE32.1502// So we reset all defaultCE32 before reading and setting new values.1503cond->defaultCE32 = Collation::NO_CE32;1504} while(cond->next >= 0 &&1505(cond = getConditionalCE32(cond->next))->context.startsWith(prefix));1506uint32_t ce32;1507int32_t suffixStart = prefixLength + 1; // == prefix.length()1508if(lastCond->context.length() == suffixStart) {1509// One prefix without contraction suffix.1510U_ASSERT(firstCond == lastCond);1511ce32 = lastCond->ce32;1512cond = lastCond;1513} else {1514// Build the contractions trie.1515contractionBuilder.clear();1516// Entry for an empty suffix, to be stored before the trie.1517uint32_t emptySuffixCE32 = 0;1518uint32_t flags = 0;1519if(firstCond->context.length() == suffixStart) {1520// There is a mapping for the prefix and the single character c. (p|c)1521// If no other suffix matches, then we return this value.1522emptySuffixCE32 = firstCond->ce32;1523cond = getConditionalCE32(firstCond->next);1524} else {1525// There is no mapping for the prefix and just the single character.1526// (There is no p|c, only p|cd, p|ce etc.)1527flags |= Collation::CONTRACT_SINGLE_CP_NO_MATCH;1528// When the prefix matches but none of the prefix-specific suffixes,1529// then we fall back to the mappings with the next-longest prefix,1530// and ultimately to mappings with no prefix.1531// Each fallback might be another set of contractions.1532// For example, if there are mappings for ch, p|cd, p|ce, but not for p|c,1533// then in text "pch" we find the ch contraction.1534for(cond = head;; cond = getConditionalCE32(cond->next)) {1535int32_t length = cond->prefixLength();1536if(length == prefixLength) { break; }1537if(cond->defaultCE32 != Collation::NO_CE32 &&1538(length==0 || prefix.endsWith(cond->context, 1, length))) {1539emptySuffixCE32 = cond->defaultCE32;1540}1541}1542cond = firstCond;1543}1544// Optimization: Set a flag when1545// the first character of every contraction suffix has lccc!=0.1546// Short-circuits contraction matching when a normal letter follows.1547flags |= Collation::CONTRACT_NEXT_CCC;1548// Add all of the non-empty suffixes into the contraction trie.1549for(;;) {1550UnicodeString suffix(cond->context, suffixStart);1551uint16_t fcd16 = nfcImpl.getFCD16(suffix.char32At(0));1552if(fcd16 <= 0xff) {1553flags &= ~Collation::CONTRACT_NEXT_CCC;1554}1555fcd16 = nfcImpl.getFCD16(suffix.char32At(suffix.length() - 1));1556if(fcd16 > 0xff) {1557// The last suffix character has lccc!=0, allowing for discontiguous contractions.1558flags |= Collation::CONTRACT_TRAILING_CCC;1559}1560if (icu4xMode && (flags & Collation::CONTRACT_HAS_STARTER) == 0) {1561for (int32_t i = 0; i < suffix.length();) {1562UChar32 c = suffix.char32At(i);1563if (!u_getCombiningClass(c)) {1564flags |= Collation::CONTRACT_HAS_STARTER;1565break;1566}1567if (c > 0xFFFF) {1568i += 2;1569} else {1570++i;1571}1572}1573}1574contractionBuilder.add(suffix, (int32_t)cond->ce32, errorCode);1575if(cond == lastCond) { break; }1576cond = getConditionalCE32(cond->next);1577}1578int32_t index = addContextTrie(emptySuffixCE32, contractionBuilder, errorCode);1579if(U_FAILURE(errorCode)) { return 0; }1580if(index > Collation::MAX_INDEX) {1581errorCode = U_BUFFER_OVERFLOW_ERROR;1582return 0;1583}1584ce32 = Collation::makeCE32FromTagAndIndex(Collation::CONTRACTION_TAG, index) | flags;1585}1586U_ASSERT(cond == lastCond);1587firstCond->defaultCE32 = ce32;1588if(prefixLength == 0) {1589if(cond->next < 0) {1590// No non-empty prefixes, only contractions.1591return ce32;1592}1593} else {1594prefix.remove(0, 1); // Remove the length unit.1595prefix.reverse();1596prefixBuilder.add(prefix, (int32_t)ce32, errorCode);1597if(cond->next < 0) { break; }1598}1599}1600U_ASSERT(head->defaultCE32 != Collation::NO_CE32);1601int32_t index = addContextTrie(head->defaultCE32, prefixBuilder, errorCode);1602if(U_FAILURE(errorCode)) { return 0; }1603if(index > Collation::MAX_INDEX) {1604errorCode = U_BUFFER_OVERFLOW_ERROR;1605return 0;1606}1607return Collation::makeCE32FromTagAndIndex(Collation::PREFIX_TAG, index);1608}16091610int32_t1611CollationDataBuilder::addContextTrie(uint32_t defaultCE32, UCharsTrieBuilder &trieBuilder,1612UErrorCode &errorCode) {1613UnicodeString context;1614context.append((UChar)(defaultCE32 >> 16)).append((UChar)defaultCE32);1615UnicodeString trieString;1616context.append(trieBuilder.buildUnicodeString(USTRINGTRIE_BUILD_SMALL, trieString, errorCode));1617if(U_FAILURE(errorCode)) { return -1; }1618int32_t index = contexts.indexOf(context);1619if(index < 0) {1620index = contexts.length();1621contexts.append(context);1622}1623return index;1624}16251626void1627CollationDataBuilder::buildFastLatinTable(CollationData &data, UErrorCode &errorCode) {1628if(U_FAILURE(errorCode) || !fastLatinEnabled) { return; }16291630delete fastLatinBuilder;1631fastLatinBuilder = new CollationFastLatinBuilder(errorCode);1632if(fastLatinBuilder == NULL) {1633errorCode = U_MEMORY_ALLOCATION_ERROR;1634return;1635}1636if(fastLatinBuilder->forData(data, errorCode)) {1637const uint16_t *table = fastLatinBuilder->getTable();1638int32_t length = fastLatinBuilder->lengthOfTable();1639if(base != NULL && length == base->fastLatinTableLength &&1640uprv_memcmp(table, base->fastLatinTable, length * 2) == 0) {1641// Same fast Latin table as in the base, use that one instead.1642delete fastLatinBuilder;1643fastLatinBuilder = NULL;1644table = base->fastLatinTable;1645}1646data.fastLatinTable = table;1647data.fastLatinTableLength = length;1648} else {1649delete fastLatinBuilder;1650fastLatinBuilder = NULL;1651}1652}16531654int32_t1655CollationDataBuilder::getCEs(const UnicodeString &s, int64_t ces[], int32_t cesLength) {1656return getCEs(s, 0, ces, cesLength);1657}16581659int32_t1660CollationDataBuilder::getCEs(const UnicodeString &prefix, const UnicodeString &s,1661int64_t ces[], int32_t cesLength) {1662int32_t prefixLength = prefix.length();1663if(prefixLength == 0) {1664return getCEs(s, 0, ces, cesLength);1665} else {1666return getCEs(prefix + s, prefixLength, ces, cesLength);1667}1668}16691670int32_t1671CollationDataBuilder::getCEs(const UnicodeString &s, int32_t start,1672int64_t ces[], int32_t cesLength) {1673if(collIter == NULL) {1674collIter = new DataBuilderCollationIterator(*this);1675if(collIter == NULL) { return 0; }1676}1677return collIter->fetchCEs(s, start, ces, cesLength);1678}16791680U_NAMESPACE_END16811682#endif // !UCONFIG_NO_COLLATION168316841685