Coverage Report

Created: 2026-06-07 06:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/icu/icu4c/source/i18n/rulebasedcollator.cpp
Line
Count
Source
1
// © 2016 and later: Unicode, Inc. and others.
2
// License & terms of use: http://www.unicode.org/copyright.html
3
/*
4
*******************************************************************************
5
* Copyright (C) 1996-2015, International Business Machines
6
* Corporation and others.  All Rights Reserved.
7
*******************************************************************************
8
* rulebasedcollator.cpp
9
*
10
* (replaced the former tblcoll.cpp)
11
*
12
* created on: 2012feb14 with new and old collation code
13
* created by: Markus W. Scherer
14
*/
15
16
#include "unicode/utypes.h"
17
18
#if !UCONFIG_NO_COLLATION
19
20
#include "unicode/coll.h"
21
#include "unicode/coleitr.h"
22
#include "unicode/localpointer.h"
23
#include "unicode/locid.h"
24
#include "unicode/sortkey.h"
25
#include "unicode/tblcoll.h"
26
#include "unicode/ucol.h"
27
#include "unicode/uiter.h"
28
#include "unicode/uloc.h"
29
#include "unicode/uniset.h"
30
#include "unicode/unistr.h"
31
#include "unicode/usetiter.h"
32
#include "unicode/utf8.h"
33
#include "unicode/uversion.h"
34
#include "bocsu.h"
35
#include "charstr.h"
36
#include "cmemory.h"
37
#include "collation.h"
38
#include "collationcompare.h"
39
#include "collationdata.h"
40
#include "collationdatareader.h"
41
#include "collationfastlatin.h"
42
#include "collationiterator.h"
43
#include "collationkeys.h"
44
#include "collationroot.h"
45
#include "collationsets.h"
46
#include "collationsettings.h"
47
#include "collationtailoring.h"
48
#include "cstring.h"
49
#include "uassert.h"
50
#include "ucol_imp.h"
51
#include "uhash.h"
52
#include "uitercollationiterator.h"
53
#include "ulocimp.h"
54
#include "ustr_imp.h"
55
#include "utf16collationiterator.h"
56
#include "utf8collationiterator.h"
57
#include "uvectr64.h"
58
59
U_NAMESPACE_BEGIN
60
61
namespace {
62
63
class FixedSortKeyByteSink : public SortKeyByteSink {
64
public:
65
    FixedSortKeyByteSink(char *dest, int32_t destCapacity)
66
0
            : SortKeyByteSink(dest, destCapacity) {}
67
    virtual ~FixedSortKeyByteSink();
68
69
private:
70
    virtual void AppendBeyondCapacity(const char *bytes, int32_t n, int32_t length) override;
71
    virtual UBool Resize(int32_t appendCapacity, int32_t length) override;
72
};
73
74
FixedSortKeyByteSink::~FixedSortKeyByteSink() {}
75
76
void
77
0
FixedSortKeyByteSink::AppendBeyondCapacity(const char *bytes, int32_t /*n*/, int32_t length) {
78
    // buffer_ != nullptr && bytes != nullptr && n > 0 && appended_ > capacity_
79
    // Fill the buffer completely.
80
0
    int32_t available = capacity_ - length;
81
0
    if (available > 0) {
82
0
        uprv_memcpy(buffer_ + length, bytes, available);
83
0
    }
84
0
}
85
86
UBool
87
0
FixedSortKeyByteSink::Resize(int32_t /*appendCapacity*/, int32_t /*length*/) {
88
0
    return false;
89
0
}
90
91
}  // namespace
92
93
// Not in an anonymous namespace, so that it can be a friend of CollationKey.
94
class CollationKeyByteSink : public SortKeyByteSink {
95
public:
96
    CollationKeyByteSink(CollationKey &key)
97
0
            : SortKeyByteSink(reinterpret_cast<char *>(key.getBytes()), key.getCapacity()),
98
0
              key_(key) {}
99
    virtual ~CollationKeyByteSink();
100
101
private:
102
    virtual void AppendBeyondCapacity(const char *bytes, int32_t n, int32_t length) override;
103
    virtual UBool Resize(int32_t appendCapacity, int32_t length) override;
104
105
    CollationKey &key_;
106
};
107
108
0
CollationKeyByteSink::~CollationKeyByteSink() {}
109
110
void
111
0
CollationKeyByteSink::AppendBeyondCapacity(const char *bytes, int32_t n, int32_t length) {
112
    // buffer_ != nullptr && bytes != nullptr && n > 0 && appended_ > capacity_
113
0
    if (Resize(n, length)) {
114
0
        uprv_memcpy(buffer_ + length, bytes, n);
115
0
    }
116
0
}
117
118
UBool
119
0
CollationKeyByteSink::Resize(int32_t appendCapacity, int32_t length) {
120
0
    if (buffer_ == nullptr) {
121
0
        return false;  // allocation failed before already
122
0
    }
123
0
    int32_t newCapacity = 2 * capacity_;
124
0
    int32_t altCapacity = length + 2 * appendCapacity;
125
0
    if (newCapacity < altCapacity) {
126
0
        newCapacity = altCapacity;
127
0
    }
128
0
    if (newCapacity < 200) {
129
0
        newCapacity = 200;
130
0
    }
131
0
    uint8_t *newBuffer = key_.reallocate(newCapacity, length);
132
0
    if (newBuffer == nullptr) {
133
0
        SetNotOk();
134
0
        return false;
135
0
    }
136
0
    buffer_ = reinterpret_cast<char *>(newBuffer);
137
0
    capacity_ = newCapacity;
138
0
    return true;
139
0
}
140
141
RuleBasedCollator::RuleBasedCollator(const RuleBasedCollator &other)
142
0
        : Collator(other),
143
0
          data(other.data),
144
0
          settings(other.settings),
145
0
          tailoring(other.tailoring),
146
0
          cacheEntry(other.cacheEntry),
147
0
          validLocale(other.validLocale),
148
0
          explicitlySetAttributes(other.explicitlySetAttributes),
149
0
          actualLocaleIsSameAsValid(other.actualLocaleIsSameAsValid) {
150
0
    settings->addRef();
151
0
    cacheEntry->addRef();
152
0
}
153
154
RuleBasedCollator::RuleBasedCollator(const uint8_t *bin, int32_t length,
155
                                     const RuleBasedCollator *base, UErrorCode &errorCode)
156
0
        : data(nullptr),
157
0
          settings(nullptr),
158
0
          tailoring(nullptr),
159
0
          cacheEntry(nullptr),
160
0
          validLocale(""),
161
0
          explicitlySetAttributes(0),
162
0
          actualLocaleIsSameAsValid(false) {
163
0
    if(U_FAILURE(errorCode)) { return; }
164
0
    if(bin == nullptr || length == 0 || base == nullptr) {
165
0
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
166
0
        return;
167
0
    }
168
0
    const CollationTailoring *root = CollationRoot::getRoot(errorCode);
169
0
    if(U_FAILURE(errorCode)) { return; }
170
0
    if(base->tailoring != root) {
171
0
        errorCode = U_UNSUPPORTED_ERROR;
172
0
        return;
173
0
    }
174
0
    LocalPointer<CollationTailoring> t(new CollationTailoring(base->tailoring->settings));
175
0
    if(t.isNull() || t->isBogus()) {
176
0
        errorCode = U_MEMORY_ALLOCATION_ERROR;
177
0
        return;
178
0
    }
179
0
    CollationDataReader::read(base->tailoring, bin, length, *t, errorCode);
180
0
    if(U_FAILURE(errorCode)) { return; }
181
0
    t->actualLocale.setToBogus();
182
0
    adoptTailoring(t.orphan(), errorCode);
183
0
}
184
185
RuleBasedCollator::RuleBasedCollator(const CollationCacheEntry *entry)
186
13.5k
        : data(entry->tailoring->data),
187
13.5k
          settings(entry->tailoring->settings),
188
13.5k
          tailoring(entry->tailoring),
189
13.5k
          cacheEntry(entry),
190
13.5k
          validLocale(entry->validLocale),
191
13.5k
          explicitlySetAttributes(0),
192
13.5k
          actualLocaleIsSameAsValid(false) {
193
13.5k
    settings->addRef();
194
13.5k
    cacheEntry->addRef();
195
13.5k
}
196
197
13.5k
RuleBasedCollator::~RuleBasedCollator() {
198
13.5k
    SharedObject::clearPtr(settings);
199
13.5k
    SharedObject::clearPtr(cacheEntry);
200
13.5k
}
201
202
void
203
0
RuleBasedCollator::adoptTailoring(CollationTailoring *t, UErrorCode &errorCode) {
204
0
    if(U_FAILURE(errorCode)) {
205
0
        t->deleteIfZeroRefCount();
206
0
        return;
207
0
    }
208
0
    U_ASSERT(settings == nullptr && data == nullptr && tailoring == nullptr && cacheEntry == nullptr);
209
0
    cacheEntry = new CollationCacheEntry(t->actualLocale, t);
210
0
    if(cacheEntry == nullptr) {
211
0
        errorCode = U_MEMORY_ALLOCATION_ERROR;
212
0
        t->deleteIfZeroRefCount();
213
0
        return;
214
0
    }
215
0
    data = t->data;
216
0
    settings = t->settings;
217
0
    settings->addRef();
218
0
    tailoring = t;
219
0
    cacheEntry->addRef();
220
0
    validLocale = t->actualLocale;
221
0
    actualLocaleIsSameAsValid = false;
222
0
}
223
224
RuleBasedCollator *
225
0
RuleBasedCollator::clone() const {
226
0
    return new RuleBasedCollator(*this);
227
0
}
228
229
0
RuleBasedCollator &RuleBasedCollator::operator=(const RuleBasedCollator &other) {
230
0
    if(this == &other) { return *this; }
231
0
    SharedObject::copyPtr(other.settings, settings);
232
0
    tailoring = other.tailoring;
233
0
    SharedObject::copyPtr(other.cacheEntry, cacheEntry);
234
0
    data = tailoring->data;
235
0
    validLocale = other.validLocale;
236
0
    explicitlySetAttributes = other.explicitlySetAttributes;
237
0
    actualLocaleIsSameAsValid = other.actualLocaleIsSameAsValid;
238
0
    return *this;
239
0
}
240
241
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(RuleBasedCollator)
242
243
bool
244
0
RuleBasedCollator::operator==(const Collator& other) const {
245
0
    if(this == &other) { return true; }
246
0
    if(!Collator::operator==(other)) { return false; }
247
0
    const RuleBasedCollator &o = static_cast<const RuleBasedCollator &>(other);
248
0
    if(*settings != *o.settings) { return false; }
249
0
    if(data == o.data) { return true; }
250
0
    UBool thisIsRoot = data->base == nullptr;
251
0
    UBool otherIsRoot = o.data->base == nullptr;
252
0
    U_ASSERT(!thisIsRoot || !otherIsRoot);  // otherwise their data pointers should be ==
253
0
    if(thisIsRoot != otherIsRoot) { return false; }
254
0
    if((thisIsRoot || !tailoring->rules.isEmpty()) &&
255
0
            (otherIsRoot || !o.tailoring->rules.isEmpty())) {
256
        // Shortcut: If both collators have valid rule strings, then compare those.
257
0
        if(tailoring->rules == o.tailoring->rules) { return true; }
258
0
    }
259
    // Different rule strings can result in the same or equivalent tailoring.
260
    // The rule strings are optional in ICU resource bundles, although included by default.
261
    // cloneBinary() drops the rule string.
262
0
    UErrorCode errorCode = U_ZERO_ERROR;
263
0
    LocalPointer<UnicodeSet> thisTailored(getTailoredSet(errorCode));
264
0
    LocalPointer<UnicodeSet> otherTailored(o.getTailoredSet(errorCode));
265
0
    if(U_FAILURE(errorCode)) { return false; }
266
0
    if(*thisTailored != *otherTailored) { return false; }
267
    // For completeness, we should compare all of the mappings;
268
    // or we should create a list of strings, sort it with one collator,
269
    // and check if both collators compare adjacent strings the same
270
    // (order & strength, down to quaternary); or similar.
271
    // Testing equality of collators seems unusual.
272
0
    return true;
273
0
}
274
275
int32_t
276
0
RuleBasedCollator::hashCode() const {
277
0
    int32_t h = settings->hashCode();
278
0
    if(data->base == nullptr) { return h; }  // root collator
279
    // Do not rely on the rule string, see comments in operator==().
280
0
    UErrorCode errorCode = U_ZERO_ERROR;
281
0
    LocalPointer<UnicodeSet> set(getTailoredSet(errorCode));
282
0
    if(U_FAILURE(errorCode)) { return 0; }
283
0
    UnicodeSetIterator iter(*set);
284
0
    while(iter.next() && !iter.isString()) {
285
0
        h ^= data->getCE32(iter.getCodepoint());
286
0
    }
287
0
    return h;
288
0
}
289
290
void
291
RuleBasedCollator::setLocales(const Locale &requested, const Locale &valid,
292
0
                              const Locale &actual) {
293
0
    if(actual == tailoring->actualLocale) {
294
0
        actualLocaleIsSameAsValid = false;
295
0
    } else {
296
0
        U_ASSERT(actual == valid);
297
0
        actualLocaleIsSameAsValid = true;
298
0
    }
299
    // Do not modify tailoring.actualLocale:
300
    // We cannot be sure that that would be thread-safe.
301
0
    validLocale = valid;
302
0
    (void)requested;  // Ignore, see also ticket #10477.
303
0
}
304
305
Locale
306
0
RuleBasedCollator::getLocale(ULocDataLocaleType type, UErrorCode& errorCode) const {
307
0
    if(U_FAILURE(errorCode)) {
308
0
        return Locale::getRoot();
309
0
    }
310
0
    switch(type) {
311
0
    case ULOC_ACTUAL_LOCALE:
312
0
        return actualLocaleIsSameAsValid ? validLocale : tailoring->actualLocale;
313
0
    case ULOC_VALID_LOCALE:
314
0
        return validLocale;
315
0
    case ULOC_REQUESTED_LOCALE:
316
0
    default:
317
0
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
318
0
        return Locale::getRoot();
319
0
    }
320
0
}
321
322
const char *
323
0
RuleBasedCollator::internalGetLocaleID(ULocDataLocaleType type, UErrorCode &errorCode) const {
324
0
    if(U_FAILURE(errorCode)) {
325
0
        return nullptr;
326
0
    }
327
0
    const Locale *result;
328
0
    switch(type) {
329
0
    case ULOC_ACTUAL_LOCALE:
330
0
        result = actualLocaleIsSameAsValid ? &validLocale : &tailoring->actualLocale;
331
0
        break;
332
0
    case ULOC_VALID_LOCALE:
333
0
        result = &validLocale;
334
0
        break;
335
0
    case ULOC_REQUESTED_LOCALE:
336
0
    default:
337
0
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
338
0
        return nullptr;
339
0
    }
340
0
    if(result->isBogus()) { return nullptr; }
341
0
    const char *id = result->getName();
342
0
    return id[0] == 0 ? "root" : id;
343
0
}
344
345
const UnicodeString&
346
0
RuleBasedCollator::getRules() const {
347
0
    return tailoring->rules;
348
0
}
349
350
void
351
0
RuleBasedCollator::getRules(UColRuleOption delta, UnicodeString &buffer) const {
352
0
    if(delta == UCOL_TAILORING_ONLY) {
353
0
        buffer = tailoring->rules;
354
0
        return;
355
0
    }
356
    // UCOL_FULL_RULES
357
0
    buffer.remove();
358
0
    CollationLoader::appendRootRules(buffer);
359
0
    buffer.append(tailoring->rules).getTerminatedBuffer();
360
0
}
361
362
void
363
0
RuleBasedCollator::getVersion(UVersionInfo version) const {
364
0
    uprv_memcpy(version, tailoring->version, U_MAX_VERSION_LENGTH);
365
0
    version[0] += (UCOL_RUNTIME_VERSION << 4) + (UCOL_RUNTIME_VERSION >> 4);
366
0
}
367
368
UnicodeSet *
369
0
RuleBasedCollator::getTailoredSet(UErrorCode &errorCode) const {
370
0
    if(U_FAILURE(errorCode)) { return nullptr; }
371
0
    UnicodeSet *tailored = new UnicodeSet();
372
0
    if(tailored == nullptr) {
373
0
        errorCode = U_MEMORY_ALLOCATION_ERROR;
374
0
        return nullptr;
375
0
    }
376
0
    if(data->base != nullptr) {
377
0
        TailoredSet(tailored).forData(data, errorCode);
378
0
        if(U_FAILURE(errorCode)) {
379
0
            delete tailored;
380
0
            return nullptr;
381
0
        }
382
0
    }
383
0
    return tailored;
384
0
}
385
386
void
387
RuleBasedCollator::internalGetContractionsAndExpansions(
388
        UnicodeSet *contractions, UnicodeSet *expansions,
389
0
        UBool addPrefixes, UErrorCode &errorCode) const {
390
0
    if(U_FAILURE(errorCode)) { return; }
391
0
    if(contractions != nullptr) {
392
0
        contractions->clear();
393
0
    }
394
0
    if(expansions != nullptr) {
395
0
        expansions->clear();
396
0
    }
397
0
    ContractionsAndExpansions(contractions, expansions, nullptr, addPrefixes).forData(data, errorCode);
398
0
}
399
400
void
401
0
RuleBasedCollator::internalAddContractions(UChar32 c, UnicodeSet &set, UErrorCode &errorCode) const {
402
0
    if(U_FAILURE(errorCode)) { return; }
403
0
    ContractionsAndExpansions(&set, nullptr, nullptr, false).forCodePoint(data, c, errorCode);
404
0
}
405
406
const CollationSettings &
407
6.83k
RuleBasedCollator::getDefaultSettings() const {
408
6.83k
    return *tailoring->settings;
409
6.83k
}
410
411
UColAttributeValue
412
7.94k
RuleBasedCollator::getAttribute(UColAttribute attr, UErrorCode &errorCode) const {
413
7.94k
    if(U_FAILURE(errorCode)) { return UCOL_DEFAULT; }
414
7.94k
    int32_t option;
415
7.94k
    switch(attr) {
416
19
    case UCOL_FRENCH_COLLATION:
417
19
        option = CollationSettings::BACKWARD_SECONDARY;
418
19
        break;
419
18
    case UCOL_ALTERNATE_HANDLING:
420
18
        return settings->getAlternateHandling();
421
15
    case UCOL_CASE_FIRST:
422
15
        return settings->getCaseFirst();
423
30
    case UCOL_CASE_LEVEL:
424
30
        option = CollationSettings::CASE_LEVEL;
425
30
        break;
426
35
    case UCOL_NORMALIZATION_MODE:
427
35
        option = CollationSettings::CHECK_FCD;
428
35
        break;
429
7.80k
    case UCOL_STRENGTH:
430
7.80k
        return static_cast<UColAttributeValue>(settings->getStrength());
431
0
    case UCOL_HIRAGANA_QUATERNARY_MODE:
432
        // Deprecated attribute, unsettable.
433
0
        return UCOL_OFF;
434
24
    case UCOL_NUMERIC_COLLATION:
435
24
        option = CollationSettings::NUMERIC;
436
24
        break;
437
0
    default:
438
0
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
439
0
        return UCOL_DEFAULT;
440
7.94k
    }
441
108
    return ((settings->options & option) == 0) ? UCOL_OFF : UCOL_ON;
442
7.94k
}
443
444
void
445
RuleBasedCollator::setAttribute(UColAttribute attr, UColAttributeValue value,
446
7.94k
                                UErrorCode &errorCode) {
447
7.94k
    UColAttributeValue oldValue = getAttribute(attr, errorCode);
448
7.94k
    if(U_FAILURE(errorCode)) { return; }
449
7.94k
    if(value == oldValue) {
450
1.32k
        setAttributeExplicitly(attr);
451
1.32k
        return;
452
1.32k
    }
453
6.61k
    const CollationSettings &defaultSettings = getDefaultSettings();
454
6.61k
    if(settings == &defaultSettings) {
455
6.56k
        if(value == UCOL_DEFAULT) {
456
0
            setAttributeDefault(attr);
457
0
            return;
458
0
        }
459
6.56k
    }
460
6.61k
    CollationSettings *ownedSettings = SharedObject::copyOnWrite(settings);
461
6.61k
    if(ownedSettings == nullptr) {
462
0
        errorCode = U_MEMORY_ALLOCATION_ERROR;
463
0
        return;
464
0
    }
465
466
6.61k
    switch(attr) {
467
19
    case UCOL_FRENCH_COLLATION:
468
19
        ownedSettings->setFlag(CollationSettings::BACKWARD_SECONDARY, value,
469
19
                               defaultSettings.options, errorCode);
470
19
        break;
471
18
    case UCOL_ALTERNATE_HANDLING:
472
18
        ownedSettings->setAlternateHandling(value, defaultSettings.options, errorCode);
473
18
        break;
474
15
    case UCOL_CASE_FIRST:
475
15
        ownedSettings->setCaseFirst(value, defaultSettings.options, errorCode);
476
15
        break;
477
30
    case UCOL_CASE_LEVEL:
478
30
        ownedSettings->setFlag(CollationSettings::CASE_LEVEL, value,
479
30
                               defaultSettings.options, errorCode);
480
30
        break;
481
33
    case UCOL_NORMALIZATION_MODE:
482
33
        ownedSettings->setFlag(CollationSettings::CHECK_FCD, value,
483
33
                               defaultSettings.options, errorCode);
484
33
        break;
485
6.47k
    case UCOL_STRENGTH:
486
6.47k
        ownedSettings->setStrength(value, defaultSettings.options, errorCode);
487
6.47k
        break;
488
0
    case UCOL_HIRAGANA_QUATERNARY_MODE:
489
        // Deprecated attribute. Check for valid values but do not change anything.
490
0
        if(value != UCOL_OFF && value != UCOL_ON && value != UCOL_DEFAULT) {
491
0
            errorCode = U_ILLEGAL_ARGUMENT_ERROR;
492
0
        }
493
0
        break;
494
24
    case UCOL_NUMERIC_COLLATION:
495
24
        ownedSettings->setFlag(CollationSettings::NUMERIC, value, defaultSettings.options, errorCode);
496
24
        break;
497
0
    default:
498
0
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
499
0
        break;
500
6.61k
    }
501
6.61k
    if(U_FAILURE(errorCode)) { return; }
502
6.56k
    setFastLatinOptions(*ownedSettings);
503
6.56k
    if(value == UCOL_DEFAULT) {
504
0
        setAttributeDefault(attr);
505
6.56k
    } else {
506
6.56k
        setAttributeExplicitly(attr);
507
6.56k
    }
508
6.56k
}
509
510
Collator &
511
17
RuleBasedCollator::setMaxVariable(UColReorderCode group, UErrorCode &errorCode) {
512
17
    if(U_FAILURE(errorCode)) { return *this; }
513
    // Convert the reorder code into a MaxVariable number, or UCOL_DEFAULT=-1.
514
17
    int32_t value;
515
17
    if(group == UCOL_REORDER_CODE_DEFAULT) {
516
0
        value = UCOL_DEFAULT;
517
17
    } else if(UCOL_REORDER_CODE_FIRST <= group && group <= UCOL_REORDER_CODE_CURRENCY) {
518
16
        value = group - UCOL_REORDER_CODE_FIRST;
519
16
    } else {
520
1
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
521
1
        return *this;
522
1
    }
523
16
    CollationSettings::MaxVariable oldValue = settings->getMaxVariable();
524
16
    if(value == oldValue) {
525
1
        setAttributeExplicitly(ATTR_VARIABLE_TOP);
526
1
        return *this;
527
1
    }
528
15
    const CollationSettings &defaultSettings = getDefaultSettings();
529
15
    if(settings == &defaultSettings) {
530
6
        if(value == UCOL_DEFAULT) {
531
0
            setAttributeDefault(ATTR_VARIABLE_TOP);
532
0
            return *this;
533
0
        }
534
6
    }
535
15
    CollationSettings *ownedSettings = SharedObject::copyOnWrite(settings);
536
15
    if(ownedSettings == nullptr) {
537
0
        errorCode = U_MEMORY_ALLOCATION_ERROR;
538
0
        return *this;
539
0
    }
540
541
15
    if(group == UCOL_REORDER_CODE_DEFAULT) {
542
0
        group = static_cast<UColReorderCode>(
543
0
            UCOL_REORDER_CODE_FIRST + int32_t{defaultSettings.getMaxVariable()});
544
0
    }
545
15
    uint32_t varTop = data->getLastPrimaryForGroup(group);
546
15
    U_ASSERT(varTop != 0);
547
15
    ownedSettings->setMaxVariable(value, defaultSettings.options, errorCode);
548
15
    if(U_FAILURE(errorCode)) { return *this; }
549
15
    ownedSettings->variableTop = varTop;
550
15
    setFastLatinOptions(*ownedSettings);
551
15
    if(value == UCOL_DEFAULT) {
552
0
        setAttributeDefault(ATTR_VARIABLE_TOP);
553
15
    } else {
554
15
        setAttributeExplicitly(ATTR_VARIABLE_TOP);
555
15
    }
556
15
    return *this;
557
15
}
558
559
UColReorderCode
560
0
RuleBasedCollator::getMaxVariable() const {
561
0
    return static_cast<UColReorderCode>(UCOL_REORDER_CODE_FIRST + int32_t{settings->getMaxVariable()});
562
0
}
563
564
uint32_t
565
0
RuleBasedCollator::getVariableTop(UErrorCode & /*errorCode*/) const {
566
0
    return settings->variableTop;
567
0
}
568
569
uint32_t
570
0
RuleBasedCollator::setVariableTop(const char16_t *varTop, int32_t len, UErrorCode &errorCode) {
571
0
    if(U_FAILURE(errorCode)) { return 0; }
572
0
    if(varTop == nullptr && len !=0) {
573
0
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
574
0
        return 0;
575
0
    }
576
0
    if(len < 0) { len = u_strlen(varTop); }
577
0
    if(len == 0) {
578
0
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
579
0
        return 0;
580
0
    }
581
0
    UBool numeric = settings->isNumeric();
582
0
    int64_t ce1, ce2;
583
0
    if(settings->dontCheckFCD()) {
584
0
        UTF16CollationIterator ci(data, numeric, varTop, varTop, varTop + len);
585
0
        ce1 = ci.nextCE(errorCode);
586
0
        ce2 = ci.nextCE(errorCode);
587
0
    } else {
588
0
        FCDUTF16CollationIterator ci(data, numeric, varTop, varTop, varTop + len);
589
0
        ce1 = ci.nextCE(errorCode);
590
0
        ce2 = ci.nextCE(errorCode);
591
0
    }
592
0
    if(ce1 == Collation::NO_CE || ce2 != Collation::NO_CE) {
593
0
        errorCode = U_CE_NOT_FOUND_ERROR;
594
0
        return 0;
595
0
    }
596
0
    setVariableTop(static_cast<uint32_t>(ce1 >> 32), errorCode);
597
0
    return settings->variableTop;
598
0
}
599
600
uint32_t
601
0
RuleBasedCollator::setVariableTop(const UnicodeString &varTop, UErrorCode &errorCode) {
602
0
    return setVariableTop(varTop.getBuffer(), varTop.length(), errorCode);
603
0
}
604
605
void
606
0
RuleBasedCollator::setVariableTop(uint32_t varTop, UErrorCode &errorCode) {
607
0
    if(U_FAILURE(errorCode)) { return; }
608
0
    if(varTop != settings->variableTop) {
609
        // Pin the variable top to the end of the reordering group which contains it.
610
        // Only a few special groups are supported.
611
0
        int32_t group = data->getGroupForPrimary(varTop);
612
0
        if(group < UCOL_REORDER_CODE_FIRST || UCOL_REORDER_CODE_CURRENCY < group) {
613
0
            errorCode = U_ILLEGAL_ARGUMENT_ERROR;
614
0
            return;
615
0
        }
616
0
        uint32_t v = data->getLastPrimaryForGroup(group);
617
0
        U_ASSERT(v != 0 && v >= varTop);
618
0
        varTop = v;
619
0
        if(varTop != settings->variableTop) {
620
0
            CollationSettings *ownedSettings = SharedObject::copyOnWrite(settings);
621
0
            if(ownedSettings == nullptr) {
622
0
                errorCode = U_MEMORY_ALLOCATION_ERROR;
623
0
                return;
624
0
            }
625
0
            ownedSettings->setMaxVariable(group - UCOL_REORDER_CODE_FIRST,
626
0
                                          getDefaultSettings().options, errorCode);
627
0
            if(U_FAILURE(errorCode)) { return; }
628
0
            ownedSettings->variableTop = varTop;
629
0
            setFastLatinOptions(*ownedSettings);
630
0
        }
631
0
    }
632
0
    if(varTop == getDefaultSettings().variableTop) {
633
0
        setAttributeDefault(ATTR_VARIABLE_TOP);
634
0
    } else {
635
0
        setAttributeExplicitly(ATTR_VARIABLE_TOP);
636
0
    }
637
0
}
638
639
int32_t
640
RuleBasedCollator::getReorderCodes(int32_t *dest, int32_t capacity,
641
0
                                   UErrorCode &errorCode) const {
642
0
    if(U_FAILURE(errorCode)) { return 0; }
643
0
    if(capacity < 0 || (dest == nullptr && capacity > 0)) {
644
0
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
645
0
        return 0;
646
0
    }
647
0
    int32_t length = settings->reorderCodesLength;
648
0
    if(length == 0) { return 0; }
649
0
    if(length > capacity) {
650
0
        errorCode = U_BUFFER_OVERFLOW_ERROR;
651
0
        return length;
652
0
    }
653
0
    uprv_memcpy(dest, settings->reorderCodes, length * 4);
654
0
    return length;
655
0
}
656
657
void
658
RuleBasedCollator::setReorderCodes(const int32_t *reorderCodes, int32_t length,
659
208
                                   UErrorCode &errorCode) {
660
208
    if(U_FAILURE(errorCode)) { return; }
661
208
    if(length < 0 || (reorderCodes == nullptr && length > 0)) {
662
0
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
663
0
        return;
664
0
    }
665
208
    if(length == 1 && reorderCodes[0] == UCOL_REORDER_CODE_NONE) {
666
2
        length = 0;
667
2
    }
668
208
    if (length == settings->reorderCodesLength &&
669
20
            (length == 0 || 
670
20
                uprv_memcmp(reorderCodes, settings->reorderCodes, length * 4) == 0)) {
671
2
        return;
672
2
    }
673
206
    const CollationSettings &defaultSettings = getDefaultSettings();
674
206
    if(length == 1 && reorderCodes[0] == UCOL_REORDER_CODE_DEFAULT) {
675
0
        if(settings != &defaultSettings) {
676
0
            CollationSettings *ownedSettings = SharedObject::copyOnWrite(settings);
677
0
            if(ownedSettings == nullptr) {
678
0
                errorCode = U_MEMORY_ALLOCATION_ERROR;
679
0
                return;
680
0
            }
681
0
            ownedSettings->copyReorderingFrom(defaultSettings, errorCode);
682
0
            setFastLatinOptions(*ownedSettings);
683
0
        }
684
0
        return;
685
0
    }
686
206
    CollationSettings *ownedSettings = SharedObject::copyOnWrite(settings);
687
206
    if(ownedSettings == nullptr) {
688
0
        errorCode = U_MEMORY_ALLOCATION_ERROR;
689
0
        return;
690
0
    }
691
206
    ownedSettings->setReordering(*data, reorderCodes, length, errorCode);
692
206
    setFastLatinOptions(*ownedSettings);
693
206
}
694
695
void
696
6.79k
RuleBasedCollator::setFastLatinOptions(CollationSettings &ownedSettings) const {
697
6.79k
    ownedSettings.fastLatinOptions = CollationFastLatin::getOptions(
698
6.79k
            data, ownedSettings,
699
6.79k
            ownedSettings.fastLatinPrimaries, UPRV_LENGTHOF(ownedSettings.fastLatinPrimaries));
700
6.79k
}
701
702
UCollationResult
703
RuleBasedCollator::compare(const UnicodeString &left, const UnicodeString &right,
704
0
                           UErrorCode &errorCode) const {
705
0
    if(U_FAILURE(errorCode)) { return UCOL_EQUAL; }
706
0
    return doCompare(left.getBuffer(), left.length(),
707
0
                     right.getBuffer(), right.length(), errorCode);
708
0
}
709
710
UCollationResult
711
RuleBasedCollator::compare(const UnicodeString &left, const UnicodeString &right,
712
0
                           int32_t length, UErrorCode &errorCode) const {
713
0
    if(U_FAILURE(errorCode) || length == 0) { return UCOL_EQUAL; }
714
0
    if(length < 0) {
715
0
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
716
0
        return UCOL_EQUAL;
717
0
    }
718
0
    int32_t leftLength = left.length();
719
0
    int32_t rightLength = right.length();
720
0
    if(leftLength > length) { leftLength = length; }
721
0
    if(rightLength > length) { rightLength = length; }
722
0
    return doCompare(left.getBuffer(), leftLength,
723
0
                     right.getBuffer(), rightLength, errorCode);
724
0
}
725
726
UCollationResult
727
RuleBasedCollator::compare(const char16_t *left, int32_t leftLength,
728
                           const char16_t *right, int32_t rightLength,
729
7.78k
                           UErrorCode &errorCode) const {
730
7.78k
    if(U_FAILURE(errorCode)) { return UCOL_EQUAL; }
731
7.78k
    if((left == nullptr && leftLength != 0) || (right == nullptr && rightLength != 0)) {
732
0
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
733
0
        return UCOL_EQUAL;
734
0
    }
735
    // Make sure both or neither strings have a known length.
736
    // We do not optimize for mixed length/termination.
737
7.78k
    if(leftLength >= 0) {
738
7.78k
        if(rightLength < 0) { rightLength = u_strlen(right); }
739
7.78k
    } else {
740
0
        if(rightLength >= 0) { leftLength = u_strlen(left); }
741
0
    }
742
7.78k
    return doCompare(left, leftLength, right, rightLength, errorCode);
743
7.78k
}
744
745
UCollationResult
746
RuleBasedCollator::compareUTF8(const StringPiece &left, const StringPiece &right,
747
0
                               UErrorCode &errorCode) const {
748
0
    if(U_FAILURE(errorCode)) { return UCOL_EQUAL; }
749
0
    const uint8_t *leftBytes = reinterpret_cast<const uint8_t *>(left.data());
750
0
    const uint8_t *rightBytes = reinterpret_cast<const uint8_t *>(right.data());
751
0
    if((leftBytes == nullptr && !left.empty()) || (rightBytes == nullptr && !right.empty())) {
752
0
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
753
0
        return UCOL_EQUAL;
754
0
    }
755
0
    return doCompare(leftBytes, left.length(), rightBytes, right.length(), errorCode);
756
0
}
757
758
UCollationResult
759
RuleBasedCollator::internalCompareUTF8(const char *left, int32_t leftLength,
760
                                       const char *right, int32_t rightLength,
761
0
                                       UErrorCode &errorCode) const {
762
0
    if(U_FAILURE(errorCode)) { return UCOL_EQUAL; }
763
0
    if((left == nullptr && leftLength != 0) || (right == nullptr && rightLength != 0)) {
764
0
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
765
0
        return UCOL_EQUAL;
766
0
    }
767
    // Make sure both or neither strings have a known length.
768
    // We do not optimize for mixed length/termination.
769
0
    if(leftLength >= 0) {
770
0
        if(rightLength < 0) { rightLength = static_cast<int32_t>(uprv_strlen(right)); }
771
0
    } else {
772
0
        if(rightLength >= 0) { leftLength = static_cast<int32_t>(uprv_strlen(left)); }
773
0
    }
774
0
    return doCompare(reinterpret_cast<const uint8_t *>(left), leftLength,
775
0
                     reinterpret_cast<const uint8_t *>(right), rightLength, errorCode);
776
0
}
777
778
namespace {
779
780
/**
781
 * Abstract iterator for identical-level string comparisons.
782
 * Returns FCD code points and handles temporary switching to NFD.
783
 */
784
class NFDIterator : public UObject {
785
public:
786
1.77k
    NFDIterator() : index(-1), length(0) {}
787
0
    virtual ~NFDIterator() {}
788
    /**
789
     * Returns the next code point from the internal normalization buffer,
790
     * or else the next text code point.
791
     * Returns -1 at the end of the text.
792
     */
793
20.3k
    UChar32 nextCodePoint() {
794
20.3k
        if(index >= 0) {
795
1.71k
            if(index == length) {
796
1.56k
                index = -1;
797
1.56k
            } else {
798
150
                UChar32 c;
799
150
                U16_NEXT_UNSAFE(decomp, index, c);
800
150
                return c;
801
150
            }
802
1.71k
        }
803
20.1k
        return nextRawCodePoint();
804
20.3k
    }
805
    /**
806
     * @param nfcImpl
807
     * @param c the last code point returned by nextCodePoint() or nextDecomposedCodePoint()
808
     * @return the first code point in c's decomposition,
809
     *         or c itself if it was decomposed already or if it does not decompose
810
     */
811
4.60k
    UChar32 nextDecomposedCodePoint(const Normalizer2Impl &nfcImpl, UChar32 c) {
812
4.60k
        if(index >= 0) { return c; }
813
4.55k
        decomp = nfcImpl.getDecomposition(c, buffer, length);
814
4.55k
        if(decomp == nullptr) { return c; }
815
1.67k
        index = 0;
816
1.67k
        U16_NEXT_UNSAFE(decomp, index, c);
817
1.67k
        return c;
818
4.55k
    }
819
protected:
820
    /**
821
     * Returns the next text code point in FCD order.
822
     * Returns -1 at the end of the text.
823
     */
824
    virtual UChar32 nextRawCodePoint() = 0;
825
private:
826
    const char16_t *decomp;
827
    char16_t buffer[4];
828
    int32_t index;
829
    int32_t length;
830
};
831
832
class UTF16NFDIterator : public NFDIterator {
833
public:
834
1.77k
    UTF16NFDIterator(const char16_t *text, const char16_t *textLimit) : s(text), limit(textLimit) {}
835
protected:
836
20.1k
    virtual UChar32 nextRawCodePoint() override {
837
20.1k
        if(s == limit) { return U_SENTINEL; }
838
19.9k
        UChar32 c = *s++;
839
19.9k
        if(limit == nullptr && c == 0) {
840
0
            s = nullptr;
841
0
            return U_SENTINEL;
842
0
        }
843
19.9k
        char16_t trail;
844
19.9k
        if(U16_IS_LEAD(c) && s != limit && U16_IS_TRAIL(trail = *s)) {
845
1.06k
            ++s;
846
1.06k
            c = U16_GET_SUPPLEMENTARY(c, trail);
847
1.06k
        }
848
19.9k
        return c;
849
19.9k
    }
850
851
    const char16_t *s;
852
    const char16_t *limit;
853
};
854
855
class FCDUTF16NFDIterator : public UTF16NFDIterator {
856
public:
857
    FCDUTF16NFDIterator(const Normalizer2Impl &nfcImpl, const char16_t *text, const char16_t *textLimit)
858
1.29k
            : UTF16NFDIterator(nullptr, nullptr) {
859
1.29k
        UErrorCode errorCode = U_ZERO_ERROR;
860
1.29k
        const char16_t *spanLimit = nfcImpl.makeFCD(text, textLimit, nullptr, errorCode);
861
1.29k
        if(U_FAILURE(errorCode)) { return; }
862
1.29k
        if(spanLimit == textLimit || (textLimit == nullptr && *spanLimit == 0)) {
863
490
            s = text;
864
490
            limit = spanLimit;
865
800
        } else {
866
800
            str.setTo(text, static_cast<int32_t>(spanLimit - text));
867
800
            {
868
800
                ReorderingBuffer r_buffer(nfcImpl, str);
869
800
                if(r_buffer.init(str.length(), errorCode)) {
870
800
                    nfcImpl.makeFCD(spanLimit, textLimit, &r_buffer, errorCode);
871
800
                }
872
800
            }
873
800
            if(U_SUCCESS(errorCode)) {
874
800
                s = str.getBuffer();
875
800
                limit = s + str.length();
876
800
            }
877
800
        }
878
1.29k
    }
879
private:
880
    UnicodeString str;
881
};
882
883
class UTF8NFDIterator : public NFDIterator {
884
public:
885
    UTF8NFDIterator(const uint8_t *text, int32_t textLength)
886
0
        : s(text), pos(0), length(textLength) {}
887
protected:
888
0
    virtual UChar32 nextRawCodePoint() override {
889
0
        if(pos == length || (s[pos] == 0 && length < 0)) { return U_SENTINEL; }
890
0
        UChar32 c;
891
0
        U8_NEXT_OR_FFFD(s, pos, length, c);
892
0
        return c;
893
0
    }
894
895
    const uint8_t *s;
896
    int32_t pos;
897
    int32_t length;
898
};
899
900
class FCDUTF8NFDIterator : public NFDIterator {
901
public:
902
    FCDUTF8NFDIterator(const CollationData *data, const uint8_t *text, int32_t textLength)
903
0
            : u8ci(data, false, text, 0, textLength) {}
904
protected:
905
0
    virtual UChar32 nextRawCodePoint() override {
906
0
        UErrorCode errorCode = U_ZERO_ERROR;
907
0
        return u8ci.nextCodePoint(errorCode);
908
0
    }
909
private:
910
    FCDUTF8CollationIterator u8ci;
911
};
912
913
class UIterNFDIterator : public NFDIterator {
914
public:
915
0
    UIterNFDIterator(UCharIterator &it) : iter(it) {}
916
protected:
917
0
    virtual UChar32 nextRawCodePoint() override {
918
0
        return uiter_next32(&iter);
919
0
    }
920
private:
921
    UCharIterator &iter;
922
};
923
924
class FCDUIterNFDIterator : public NFDIterator {
925
public:
926
    FCDUIterNFDIterator(const CollationData *data, UCharIterator &it, int32_t startIndex)
927
0
            : uici(data, false, it, startIndex) {}
928
protected:
929
0
    virtual UChar32 nextRawCodePoint() override {
930
0
        UErrorCode errorCode = U_ZERO_ERROR;
931
0
        return uici.nextCodePoint(errorCode);
932
0
    }
933
private:
934
    FCDUIterCollationIterator uici;
935
};
936
937
UCollationResult compareNFDIter(const Normalizer2Impl &nfcImpl,
938
885
                                NFDIterator &left, NFDIterator &right) {
939
10.1k
    for(;;) {
940
        // Fetch the next FCD code point from each string.
941
10.1k
        UChar32 leftCp = left.nextCodePoint();
942
10.1k
        UChar32 rightCp = right.nextCodePoint();
943
10.1k
        if(leftCp == rightCp) {
944
7.84k
            if(leftCp < 0) { break; }
945
7.71k
            continue;
946
7.84k
        }
947
        // If they are different, then decompose each and compare again.
948
2.32k
        if(leftCp < 0) {
949
6
            leftCp = -2;  // end of string
950
2.31k
        } else if(leftCp == 0xfffe) {
951
1
            leftCp = -1;  // U+FFFE: merge separator
952
2.31k
        } else {
953
2.31k
            leftCp = left.nextDecomposedCodePoint(nfcImpl, leftCp);
954
2.31k
        }
955
2.32k
        if(rightCp < 0) {
956
16
            rightCp = -2;  // end of string
957
2.30k
        } else if(rightCp == 0xfffe) {
958
16
            rightCp = -1;  // U+FFFE: merge separator
959
2.29k
        } else {
960
2.29k
            rightCp = right.nextDecomposedCodePoint(nfcImpl, rightCp);
961
2.29k
        }
962
2.32k
        if(leftCp < rightCp) { return UCOL_LESS; }
963
2.00k
        if(leftCp > rightCp) { return UCOL_GREATER; }
964
2.00k
    }
965
134
    return UCOL_EQUAL;
966
885
}
967
968
}  // namespace
969
970
UCollationResult
971
RuleBasedCollator::doCompare(const char16_t *left, int32_t leftLength,
972
                             const char16_t *right, int32_t rightLength,
973
7.78k
                             UErrorCode &errorCode) const {
974
    // U_FAILURE(errorCode) checked by caller.
975
7.78k
    if(left == right && leftLength == rightLength) {
976
0
        return UCOL_EQUAL;
977
0
    }
978
979
    // Identical-prefix test.
980
7.78k
    const char16_t *leftLimit;
981
7.78k
    const char16_t *rightLimit;
982
7.78k
    int32_t equalPrefixLength = 0;
983
7.78k
    if(leftLength < 0) {
984
0
        leftLimit = nullptr;
985
0
        rightLimit = nullptr;
986
0
        char16_t c;
987
0
        while((c = left[equalPrefixLength]) == right[equalPrefixLength]) {
988
0
            if(c == 0) { return UCOL_EQUAL; }
989
0
            ++equalPrefixLength;
990
0
        }
991
7.78k
    } else {
992
7.78k
        leftLimit = left + leftLength;
993
7.78k
        rightLimit = right + rightLength;
994
20.4k
        for(;;) {
995
20.4k
            if(equalPrefixLength == leftLength) {
996
410
                if(equalPrefixLength == rightLength) { return UCOL_EQUAL; }
997
0
                break;
998
20.0k
            } else if(equalPrefixLength == rightLength ||
999
20.0k
                      left[equalPrefixLength] != right[equalPrefixLength]) {
1000
7.37k
                break;
1001
7.37k
            }
1002
12.6k
            ++equalPrefixLength;
1003
12.6k
        }
1004
7.78k
    }
1005
1006
7.37k
    UBool numeric = settings->isNumeric();
1007
7.37k
    if(equalPrefixLength > 0) {
1008
1.03k
        if((equalPrefixLength != leftLength &&
1009
1.03k
                    data->isUnsafeBackward(left[equalPrefixLength], numeric)) ||
1010
341
                (equalPrefixLength != rightLength &&
1011
849
                    data->isUnsafeBackward(right[equalPrefixLength], numeric))) {
1012
            // Identical prefix: Back up to the start of a contraction or reordering sequence.
1013
7.36k
            while(--equalPrefixLength > 0 &&
1014
6.54k
                    data->isUnsafeBackward(left[equalPrefixLength], numeric)) {}
1015
849
        }
1016
        // Notes:
1017
        // - A longer string can compare equal to a prefix of it if only ignorables follow.
1018
        // - With a backward level, a longer string can compare less-than a prefix of it.
1019
1020
        // Pass the actual start of each string into the CollationIterators,
1021
        // plus the equalPrefixLength position,
1022
        // so that prefix matches back into the equal prefix work.
1023
1.03k
    }
1024
1025
7.37k
    int32_t result;
1026
7.37k
    int32_t fastLatinOptions = settings->fastLatinOptions;
1027
7.37k
    if(fastLatinOptions >= 0 &&
1028
7.35k
            (equalPrefixLength == leftLength ||
1029
7.35k
                left[equalPrefixLength] <= CollationFastLatin::LATIN_MAX) &&
1030
1.31k
            (equalPrefixLength == rightLength ||
1031
1.31k
                right[equalPrefixLength] <= CollationFastLatin::LATIN_MAX)) {
1032
836
        if(leftLength >= 0) {
1033
836
            result = CollationFastLatin::compareUTF16(data->fastLatinTable,
1034
836
                                                      settings->fastLatinPrimaries,
1035
836
                                                      fastLatinOptions,
1036
836
                                                      left + equalPrefixLength,
1037
836
                                                      leftLength - equalPrefixLength,
1038
836
                                                      right + equalPrefixLength,
1039
836
                                                      rightLength - equalPrefixLength);
1040
836
        } else {
1041
0
            result = CollationFastLatin::compareUTF16(data->fastLatinTable,
1042
0
                                                      settings->fastLatinPrimaries,
1043
0
                                                      fastLatinOptions,
1044
0
                                                      left + equalPrefixLength, -1,
1045
0
                                                      right + equalPrefixLength, -1);
1046
0
        }
1047
6.53k
    } else {
1048
6.53k
        result = CollationFastLatin::BAIL_OUT_RESULT;
1049
6.53k
    }
1050
1051
7.37k
    if(result == CollationFastLatin::BAIL_OUT_RESULT) {
1052
6.94k
        if(settings->dontCheckFCD()) {
1053
4.35k
            UTF16CollationIterator leftIter(data, numeric,
1054
4.35k
                                            left, left + equalPrefixLength, leftLimit);
1055
4.35k
            UTF16CollationIterator rightIter(data, numeric,
1056
4.35k
                                            right, right + equalPrefixLength, rightLimit);
1057
4.35k
            result = CollationCompare::compareUpToQuaternary(leftIter, rightIter, *settings, errorCode);
1058
4.35k
        } else {
1059
2.59k
            FCDUTF16CollationIterator leftIter(data, numeric,
1060
2.59k
                                              left, left + equalPrefixLength, leftLimit);
1061
2.59k
            FCDUTF16CollationIterator rightIter(data, numeric,
1062
2.59k
                                                right, right + equalPrefixLength, rightLimit);
1063
2.59k
            result = CollationCompare::compareUpToQuaternary(leftIter, rightIter, *settings, errorCode);
1064
2.59k
        }
1065
6.94k
    }
1066
7.37k
    if(result != UCOL_EQUAL || settings->getStrength() < UCOL_IDENTICAL || U_FAILURE(errorCode)) {
1067
6.48k
        return static_cast<UCollationResult>(result);
1068
6.48k
    }
1069
1070
    // Note: If NUL-terminated, we could get the actual limits from the iterators now.
1071
    // That would complicate the iterators a bit, NUL-terminated strings are only a C convenience,
1072
    // and the benefit seems unlikely to be measurable.
1073
1074
    // Compare identical level.
1075
885
    const Normalizer2Impl &nfcImpl = data->nfcImpl;
1076
885
    left += equalPrefixLength;
1077
885
    right += equalPrefixLength;
1078
885
    if(settings->dontCheckFCD()) {
1079
240
        UTF16NFDIterator leftIter(left, leftLimit);
1080
240
        UTF16NFDIterator rightIter(right, rightLimit);
1081
240
        return compareNFDIter(nfcImpl, leftIter, rightIter);
1082
645
    } else {
1083
645
        FCDUTF16NFDIterator leftIter(nfcImpl, left, leftLimit);
1084
645
        FCDUTF16NFDIterator rightIter(nfcImpl, right, rightLimit);
1085
645
        return compareNFDIter(nfcImpl, leftIter, rightIter);
1086
645
    }
1087
885
}
1088
1089
UCollationResult
1090
RuleBasedCollator::doCompare(const uint8_t *left, int32_t leftLength,
1091
                             const uint8_t *right, int32_t rightLength,
1092
0
                             UErrorCode &errorCode) const {
1093
    // U_FAILURE(errorCode) checked by caller.
1094
0
    if(left == right && leftLength == rightLength) {
1095
0
        return UCOL_EQUAL;
1096
0
    }
1097
1098
    // Identical-prefix test.
1099
0
    int32_t equalPrefixLength = 0;
1100
0
    if(leftLength < 0) {
1101
0
        uint8_t c;
1102
0
        while((c = left[equalPrefixLength]) == right[equalPrefixLength]) {
1103
0
            if(c == 0) { return UCOL_EQUAL; }
1104
0
            ++equalPrefixLength;
1105
0
        }
1106
0
    } else {
1107
0
        for(;;) {
1108
0
            if(equalPrefixLength == leftLength) {
1109
0
                if(equalPrefixLength == rightLength) { return UCOL_EQUAL; }
1110
0
                break;
1111
0
            } else if(equalPrefixLength == rightLength ||
1112
0
                      left[equalPrefixLength] != right[equalPrefixLength]) {
1113
0
                break;
1114
0
            }
1115
0
            ++equalPrefixLength;
1116
0
        }
1117
0
    }
1118
    // Back up to the start of a partially-equal code point.
1119
0
    if(equalPrefixLength > 0 &&
1120
0
            ((equalPrefixLength != leftLength && U8_IS_TRAIL(left[equalPrefixLength])) ||
1121
0
            (equalPrefixLength != rightLength && U8_IS_TRAIL(right[equalPrefixLength])))) {
1122
0
        while(--equalPrefixLength > 0 && U8_IS_TRAIL(left[equalPrefixLength])) {}
1123
0
    }
1124
1125
0
    UBool numeric = settings->isNumeric();
1126
0
    if(equalPrefixLength > 0) {
1127
0
        UBool unsafe = false;
1128
0
        if(equalPrefixLength != leftLength) {
1129
0
            int32_t i = equalPrefixLength;
1130
0
            UChar32 c;
1131
0
            U8_NEXT_OR_FFFD(left, i, leftLength, c);
1132
0
            unsafe = data->isUnsafeBackward(c, numeric);
1133
0
        }
1134
0
        if(!unsafe && equalPrefixLength != rightLength) {
1135
0
            int32_t i = equalPrefixLength;
1136
0
            UChar32 c;
1137
0
            U8_NEXT_OR_FFFD(right, i, rightLength, c);
1138
0
            unsafe = data->isUnsafeBackward(c, numeric);
1139
0
        }
1140
0
        if(unsafe) {
1141
            // Identical prefix: Back up to the start of a contraction or reordering sequence.
1142
0
            UChar32 c;
1143
0
            do {
1144
0
                U8_PREV_OR_FFFD(left, 0, equalPrefixLength, c);
1145
0
            } while(equalPrefixLength > 0 && data->isUnsafeBackward(c, numeric));
1146
0
        }
1147
        // See the notes in the UTF-16 version.
1148
1149
        // Pass the actual start of each string into the CollationIterators,
1150
        // plus the equalPrefixLength position,
1151
        // so that prefix matches back into the equal prefix work.
1152
0
    }
1153
1154
0
    int32_t result;
1155
0
    int32_t fastLatinOptions = settings->fastLatinOptions;
1156
0
    if(fastLatinOptions >= 0 &&
1157
0
            (equalPrefixLength == leftLength ||
1158
0
                left[equalPrefixLength] <= CollationFastLatin::LATIN_MAX_UTF8_LEAD) &&
1159
0
            (equalPrefixLength == rightLength ||
1160
0
                right[equalPrefixLength] <= CollationFastLatin::LATIN_MAX_UTF8_LEAD)) {
1161
0
        if(leftLength >= 0) {
1162
0
            result = CollationFastLatin::compareUTF8(data->fastLatinTable,
1163
0
                                                     settings->fastLatinPrimaries,
1164
0
                                                     fastLatinOptions,
1165
0
                                                     left + equalPrefixLength,
1166
0
                                                     leftLength - equalPrefixLength,
1167
0
                                                     right + equalPrefixLength,
1168
0
                                                     rightLength - equalPrefixLength);
1169
0
        } else {
1170
0
            result = CollationFastLatin::compareUTF8(data->fastLatinTable,
1171
0
                                                     settings->fastLatinPrimaries,
1172
0
                                                     fastLatinOptions,
1173
0
                                                     left + equalPrefixLength, -1,
1174
0
                                                     right + equalPrefixLength, -1);
1175
0
        }
1176
0
    } else {
1177
0
        result = CollationFastLatin::BAIL_OUT_RESULT;
1178
0
    }
1179
1180
0
    if(result == CollationFastLatin::BAIL_OUT_RESULT) {
1181
0
        if(settings->dontCheckFCD()) {
1182
0
            UTF8CollationIterator leftIter(data, numeric, left, equalPrefixLength, leftLength);
1183
0
            UTF8CollationIterator rightIter(data, numeric, right, equalPrefixLength, rightLength);
1184
0
            result = CollationCompare::compareUpToQuaternary(leftIter, rightIter, *settings, errorCode);
1185
0
        } else {
1186
0
            FCDUTF8CollationIterator leftIter(data, numeric, left, equalPrefixLength, leftLength);
1187
0
            FCDUTF8CollationIterator rightIter(data, numeric, right, equalPrefixLength, rightLength);
1188
0
            result = CollationCompare::compareUpToQuaternary(leftIter, rightIter, *settings, errorCode);
1189
0
        }
1190
0
    }
1191
0
    if(result != UCOL_EQUAL || settings->getStrength() < UCOL_IDENTICAL || U_FAILURE(errorCode)) {
1192
0
        return static_cast<UCollationResult>(result);
1193
0
    }
1194
1195
    // Note: If NUL-terminated, we could get the actual limits from the iterators now.
1196
    // That would complicate the iterators a bit, NUL-terminated strings are only a C convenience,
1197
    // and the benefit seems unlikely to be measurable.
1198
1199
    // Compare identical level.
1200
0
    const Normalizer2Impl &nfcImpl = data->nfcImpl;
1201
0
    left += equalPrefixLength;
1202
0
    right += equalPrefixLength;
1203
0
    if(leftLength > 0) {
1204
0
        leftLength -= equalPrefixLength;
1205
0
        rightLength -= equalPrefixLength;
1206
0
    }
1207
0
    if(settings->dontCheckFCD()) {
1208
0
        UTF8NFDIterator leftIter(left, leftLength);
1209
0
        UTF8NFDIterator rightIter(right, rightLength);
1210
0
        return compareNFDIter(nfcImpl, leftIter, rightIter);
1211
0
    } else {
1212
0
        FCDUTF8NFDIterator leftIter(data, left, leftLength);
1213
0
        FCDUTF8NFDIterator rightIter(data, right, rightLength);
1214
0
        return compareNFDIter(nfcImpl, leftIter, rightIter);
1215
0
    }
1216
0
}
1217
1218
UCollationResult
1219
RuleBasedCollator::compare(UCharIterator &left, UCharIterator &right,
1220
0
                           UErrorCode &errorCode) const {
1221
0
    if(U_FAILURE(errorCode) || &left == &right) { return UCOL_EQUAL; }
1222
0
    UBool numeric = settings->isNumeric();
1223
1224
    // Identical-prefix test.
1225
0
    int32_t equalPrefixLength = 0;
1226
0
    {
1227
0
        UChar32 leftUnit;
1228
0
        UChar32 rightUnit;
1229
0
        while((leftUnit = left.next(&left)) == (rightUnit = right.next(&right))) {
1230
0
            if(leftUnit < 0) { return UCOL_EQUAL; }
1231
0
            ++equalPrefixLength;
1232
0
        }
1233
1234
        // Back out the code units that differed, for the real collation comparison.
1235
0
        if(leftUnit >= 0) { left.previous(&left); }
1236
0
        if(rightUnit >= 0) { right.previous(&right); }
1237
1238
0
        if(equalPrefixLength > 0) {
1239
0
            if((leftUnit >= 0 && data->isUnsafeBackward(leftUnit, numeric)) ||
1240
0
                    (rightUnit >= 0 && data->isUnsafeBackward(rightUnit, numeric))) {
1241
                // Identical prefix: Back up to the start of a contraction or reordering sequence.
1242
0
                do {
1243
0
                    --equalPrefixLength;
1244
0
                    leftUnit = left.previous(&left);
1245
0
                    right.previous(&right);
1246
0
                } while(equalPrefixLength > 0 && data->isUnsafeBackward(leftUnit, numeric));
1247
0
            }
1248
            // See the notes in the UTF-16 version.
1249
0
        }
1250
0
    }
1251
1252
0
    UCollationResult result;
1253
0
    if(settings->dontCheckFCD()) {
1254
0
        UIterCollationIterator leftIter(data, numeric, left);
1255
0
        UIterCollationIterator rightIter(data, numeric, right);
1256
0
        result = CollationCompare::compareUpToQuaternary(leftIter, rightIter, *settings, errorCode);
1257
0
    } else {
1258
0
        FCDUIterCollationIterator leftIter(data, numeric, left, equalPrefixLength);
1259
0
        FCDUIterCollationIterator rightIter(data, numeric, right, equalPrefixLength);
1260
0
        result = CollationCompare::compareUpToQuaternary(leftIter, rightIter, *settings, errorCode);
1261
0
    }
1262
0
    if(result != UCOL_EQUAL || settings->getStrength() < UCOL_IDENTICAL || U_FAILURE(errorCode)) {
1263
0
        return result;
1264
0
    }
1265
1266
    // Compare identical level.
1267
0
    left.move(&left, equalPrefixLength, UITER_ZERO);
1268
0
    right.move(&right, equalPrefixLength, UITER_ZERO);
1269
0
    const Normalizer2Impl &nfcImpl = data->nfcImpl;
1270
0
    if(settings->dontCheckFCD()) {
1271
0
        UIterNFDIterator leftIter(left);
1272
0
        UIterNFDIterator rightIter(right);
1273
0
        return compareNFDIter(nfcImpl, leftIter, rightIter);
1274
0
    } else {
1275
0
        FCDUIterNFDIterator leftIter(data, left, equalPrefixLength);
1276
0
        FCDUIterNFDIterator rightIter(data, right, equalPrefixLength);
1277
0
        return compareNFDIter(nfcImpl, leftIter, rightIter);
1278
0
    }
1279
0
}
1280
1281
CollationKey &
1282
RuleBasedCollator::getCollationKey(const UnicodeString &s, CollationKey &key,
1283
0
                                   UErrorCode &errorCode) const {
1284
0
    return getCollationKey(s.getBuffer(), s.length(), key, errorCode);
1285
0
}
1286
1287
CollationKey &
1288
RuleBasedCollator::getCollationKey(const char16_t *s, int32_t length, CollationKey& key,
1289
0
                                   UErrorCode &errorCode) const {
1290
0
    if(U_FAILURE(errorCode)) {
1291
0
        return key.setToBogus();
1292
0
    }
1293
0
    if(s == nullptr && length != 0) {
1294
0
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
1295
0
        return key.setToBogus();
1296
0
    }
1297
0
    key.reset();  // resets the "bogus" state
1298
0
    CollationKeyByteSink sink(key);
1299
0
    writeSortKey(s, length, sink, errorCode);
1300
0
    if(U_FAILURE(errorCode)) {
1301
0
        key.setToBogus();
1302
0
    } else if(key.isBogus()) {
1303
0
        errorCode = U_MEMORY_ALLOCATION_ERROR;
1304
0
    } else {
1305
0
        key.setLength(sink.NumberOfBytesAppended());
1306
0
    }
1307
0
    return key;
1308
0
}
1309
1310
int32_t
1311
RuleBasedCollator::getSortKey(const UnicodeString &s,
1312
0
                              uint8_t *dest, int32_t capacity) const {
1313
0
    return getSortKey(s.getBuffer(), s.length(), dest, capacity);
1314
0
}
1315
1316
int32_t
1317
RuleBasedCollator::getSortKey(const char16_t *s, int32_t length,
1318
0
                              uint8_t *dest, int32_t capacity) const {
1319
0
    if((s == nullptr && length != 0) || capacity < 0 || (dest == nullptr && capacity > 0)) {
1320
0
        return 0;
1321
0
    }
1322
0
    uint8_t noDest[1] = { 0 };
1323
0
    if(dest == nullptr) {
1324
        // Distinguish pure preflighting from an allocation error.
1325
0
        dest = noDest;
1326
0
        capacity = 0;
1327
0
    }
1328
0
    FixedSortKeyByteSink sink(reinterpret_cast<char *>(dest), capacity);
1329
0
    UErrorCode errorCode = U_ZERO_ERROR;
1330
0
    writeSortKey(s, length, sink, errorCode);
1331
0
    return U_SUCCESS(errorCode) ? sink.NumberOfBytesAppended() : 0;
1332
0
}
1333
1334
void
1335
RuleBasedCollator::writeSortKey(const char16_t *s, int32_t length,
1336
0
                                SortKeyByteSink &sink, UErrorCode &errorCode) const {
1337
0
    if(U_FAILURE(errorCode)) { return; }
1338
0
    const char16_t *limit = (length >= 0) ? s + length : nullptr;
1339
0
    UBool numeric = settings->isNumeric();
1340
0
    CollationKeys::LevelCallback callback;
1341
0
    if(settings->dontCheckFCD()) {
1342
0
        UTF16CollationIterator iter(data, numeric, s, s, limit);
1343
0
        CollationKeys::writeSortKeyUpToQuaternary(iter, data->compressibleBytes, *settings,
1344
0
                                                  sink, Collation::PRIMARY_LEVEL,
1345
0
                                                  callback, true, errorCode);
1346
0
    } else {
1347
0
        FCDUTF16CollationIterator iter(data, numeric, s, s, limit);
1348
0
        CollationKeys::writeSortKeyUpToQuaternary(iter, data->compressibleBytes, *settings,
1349
0
                                                  sink, Collation::PRIMARY_LEVEL,
1350
0
                                                  callback, true, errorCode);
1351
0
    }
1352
0
    if(settings->getStrength() == UCOL_IDENTICAL) {
1353
0
        writeIdenticalLevel(s, limit, sink, errorCode);
1354
0
    }
1355
0
    static const char terminator = 0;  // TERMINATOR_BYTE
1356
0
    sink.Append(&terminator, 1);
1357
0
}
1358
1359
void
1360
RuleBasedCollator::writeIdenticalLevel(const char16_t *s, const char16_t *limit,
1361
0
                                       SortKeyByteSink &sink, UErrorCode &errorCode) const {
1362
    // NFD quick check
1363
0
    const char16_t *nfdQCYesLimit = data->nfcImpl.decompose(s, limit, nullptr, errorCode);
1364
0
    if(U_FAILURE(errorCode)) { return; }
1365
0
    sink.Append(Collation::LEVEL_SEPARATOR_BYTE);
1366
0
    UChar32 prev = 0;
1367
0
    if(nfdQCYesLimit != s) {
1368
0
        prev = u_writeIdenticalLevelRun(prev, s, static_cast<int32_t>(nfdQCYesLimit - s), sink);
1369
0
    }
1370
    // Is there non-NFD text?
1371
0
    int32_t destLengthEstimate;
1372
0
    if(limit != nullptr) {
1373
0
        if(nfdQCYesLimit == limit) { return; }
1374
0
        destLengthEstimate = static_cast<int32_t>(limit - nfdQCYesLimit);
1375
0
    } else {
1376
        // s is NUL-terminated
1377
0
        if(*nfdQCYesLimit == 0) { return; }
1378
0
        destLengthEstimate = -1;
1379
0
    }
1380
0
    UnicodeString nfd;
1381
0
    data->nfcImpl.decompose(nfdQCYesLimit, limit, nfd, destLengthEstimate, errorCode);
1382
0
    u_writeIdenticalLevelRun(prev, nfd.getBuffer(), nfd.length(), sink);
1383
0
}
1384
1385
namespace {
1386
1387
/**
1388
 * internalNextSortKeyPart() calls CollationKeys::writeSortKeyUpToQuaternary()
1389
 * with an instance of this callback class.
1390
 * When another level is about to be written, the callback
1391
 * records the level and the number of bytes that will be written until
1392
 * the sink (which is actually a FixedSortKeyByteSink) fills up.
1393
 *
1394
 * When internalNextSortKeyPart() is called again, it restarts with the last level
1395
 * and ignores as many bytes as were written previously for that level.
1396
 */
1397
class PartLevelCallback : public CollationKeys::LevelCallback {
1398
public:
1399
    PartLevelCallback(const SortKeyByteSink &s)
1400
0
            : sink(s), level(Collation::PRIMARY_LEVEL) {
1401
0
        levelCapacity = sink.GetRemainingCapacity();
1402
0
    }
1403
0
    virtual ~PartLevelCallback() {}
1404
0
    virtual UBool needToWrite(Collation::Level l) override {
1405
0
        if(!sink.Overflowed()) {
1406
            // Remember a level that will be at least partially written.
1407
0
            level = l;
1408
0
            levelCapacity = sink.GetRemainingCapacity();
1409
0
            return true;
1410
0
        } else {
1411
0
            return false;
1412
0
        }
1413
0
    }
1414
0
    Collation::Level getLevel() const { return level; }
1415
0
    int32_t getLevelCapacity() const { return levelCapacity; }
1416
1417
private:
1418
    const SortKeyByteSink &sink;
1419
    Collation::Level level;
1420
    int32_t levelCapacity;
1421
};
1422
1423
}  // namespace
1424
1425
int32_t
1426
RuleBasedCollator::internalNextSortKeyPart(UCharIterator *iter, uint32_t state[2],
1427
0
                                           uint8_t *dest, int32_t count, UErrorCode &errorCode) const {
1428
0
    if(U_FAILURE(errorCode)) { return 0; }
1429
0
    if(iter == nullptr || state == nullptr || count < 0 || (count > 0 && dest == nullptr)) {
1430
0
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
1431
0
        return 0;
1432
0
    }
1433
0
    if(count == 0) { return 0; }
1434
1435
0
    FixedSortKeyByteSink sink(reinterpret_cast<char *>(dest), count);
1436
0
    sink.IgnoreBytes(static_cast<int32_t>(state[1]));
1437
0
    iter->move(iter, 0, UITER_START);
1438
1439
0
    Collation::Level level = static_cast<Collation::Level>(state[0]);
1440
0
    if(level <= Collation::QUATERNARY_LEVEL) {
1441
0
        UBool numeric = settings->isNumeric();
1442
0
        PartLevelCallback callback(sink);
1443
0
        if(settings->dontCheckFCD()) {
1444
0
            UIterCollationIterator ci(data, numeric, *iter);
1445
0
            CollationKeys::writeSortKeyUpToQuaternary(ci, data->compressibleBytes, *settings,
1446
0
                                                      sink, level, callback, false, errorCode);
1447
0
        } else {
1448
0
            FCDUIterCollationIterator ci(data, numeric, *iter, 0);
1449
0
            CollationKeys::writeSortKeyUpToQuaternary(ci, data->compressibleBytes, *settings,
1450
0
                                                      sink, level, callback, false, errorCode);
1451
0
        }
1452
0
        if(U_FAILURE(errorCode)) { return 0; }
1453
0
        if(sink.NumberOfBytesAppended() > count) {
1454
0
            state[0] = static_cast<uint32_t>(callback.getLevel());
1455
0
            state[1] = static_cast<uint32_t>(callback.getLevelCapacity());
1456
0
            return count;
1457
0
        }
1458
        // All of the normal levels are done.
1459
0
        if(settings->getStrength() == UCOL_IDENTICAL) {
1460
0
            level = Collation::IDENTICAL_LEVEL;
1461
0
            iter->move(iter, 0, UITER_START);
1462
0
        }
1463
        // else fall through to setting ZERO_LEVEL
1464
0
    }
1465
1466
0
    if(level == Collation::IDENTICAL_LEVEL) {
1467
0
        int32_t levelCapacity = sink.GetRemainingCapacity();
1468
0
        UnicodeString s;
1469
0
        for(;;) {
1470
0
            UChar32 c = iter->next(iter);
1471
0
            if(c < 0) { break; }
1472
0
            s.append(static_cast<char16_t>(c));
1473
0
        }
1474
0
        const char16_t *sArray = s.getBuffer();
1475
0
        writeIdenticalLevel(sArray, sArray + s.length(), sink, errorCode);
1476
0
        if(U_FAILURE(errorCode)) { return 0; }
1477
0
        if(sink.NumberOfBytesAppended() > count) {
1478
0
            state[0] = static_cast<uint32_t>(level);
1479
0
            state[1] = static_cast<uint32_t>(levelCapacity);
1480
0
            return count;
1481
0
        }
1482
0
    }
1483
1484
    // ZERO_LEVEL: Fill the remainder of dest with 00 bytes.
1485
0
    state[0] = static_cast<uint32_t>(Collation::ZERO_LEVEL);
1486
0
    state[1] = 0;
1487
0
    int32_t length = sink.NumberOfBytesAppended();
1488
0
    int32_t i = length;
1489
0
    while(i < count) { dest[i++] = 0; }
1490
0
    return length;
1491
0
}
1492
1493
void
1494
RuleBasedCollator::internalGetCEs(const UnicodeString &str, UVector64 &ces,
1495
0
                                  UErrorCode &errorCode) const {
1496
0
    if(U_FAILURE(errorCode)) { return; }
1497
0
    const char16_t *s = str.getBuffer();
1498
0
    const char16_t *limit = s + str.length();
1499
0
    UBool numeric = settings->isNumeric();
1500
0
    if(settings->dontCheckFCD()) {
1501
0
        UTF16CollationIterator iter(data, numeric, s, s, limit);
1502
0
        int64_t ce;
1503
0
        while((ce = iter.nextCE(errorCode)) != Collation::NO_CE) {
1504
0
            ces.addElement(ce, errorCode);
1505
0
        }
1506
0
    } else {
1507
0
        FCDUTF16CollationIterator iter(data, numeric, s, s, limit);
1508
0
        int64_t ce;
1509
0
        while((ce = iter.nextCE(errorCode)) != Collation::NO_CE) {
1510
0
            ces.addElement(ce, errorCode);
1511
0
        }
1512
0
    }
1513
0
}
1514
1515
namespace {
1516
1517
void appendSubtag(CharString &s, char letter, const char *subtag, int32_t length,
1518
0
                  UErrorCode &errorCode) {
1519
0
    if(U_FAILURE(errorCode) || length == 0) { return; }
1520
0
    if(!s.isEmpty()) {
1521
0
        s.append('_', errorCode);
1522
0
    }
1523
0
    s.append(letter, errorCode);
1524
0
    for(int32_t i = 0; i < length; ++i) {
1525
0
        s.append(uprv_toupper(subtag[i]), errorCode);
1526
0
    }
1527
0
}
1528
1529
void appendAttribute(CharString &s, char letter, UColAttributeValue value,
1530
0
                     UErrorCode &errorCode) {
1531
0
    if(U_FAILURE(errorCode)) { return; }
1532
0
    if(!s.isEmpty()) {
1533
0
        s.append('_', errorCode);
1534
0
    }
1535
0
    static const char *valueChars = "1234...........IXO..SN..LU......";
1536
0
    s.append(letter, errorCode);
1537
0
    s.append(valueChars[value], errorCode);
1538
0
}
1539
1540
}  // namespace
1541
1542
int32_t
1543
RuleBasedCollator::internalGetShortDefinitionString(const char *locale,
1544
                                                    char *buffer, int32_t capacity,
1545
0
                                                    UErrorCode &errorCode) const {
1546
0
    if(U_FAILURE(errorCode)) { return 0; }
1547
0
    if(buffer == nullptr ? capacity != 0 : capacity < 0) {
1548
0
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
1549
0
        return 0;
1550
0
    }
1551
0
    if(locale == nullptr) {
1552
0
        locale = internalGetLocaleID(ULOC_VALID_LOCALE, errorCode);
1553
0
    }
1554
1555
0
    char resultLocale[ULOC_FULLNAME_CAPACITY + 1];
1556
0
    int32_t length = ucol_getFunctionalEquivalent(resultLocale, ULOC_FULLNAME_CAPACITY,
1557
0
                                                  "collation", locale,
1558
0
                                                  nullptr, &errorCode);
1559
0
    if(U_FAILURE(errorCode)) { return 0; }
1560
0
    resultLocale[length] = 0;
1561
1562
    // Append items in alphabetic order of their short definition letters.
1563
0
    CharString result;
1564
1565
0
    if(attributeHasBeenSetExplicitly(UCOL_ALTERNATE_HANDLING)) {
1566
0
        appendAttribute(result, 'A', getAttribute(UCOL_ALTERNATE_HANDLING, errorCode), errorCode);
1567
0
    }
1568
    // ATTR_VARIABLE_TOP not supported because 'B' was broken.
1569
    // See ICU tickets #10372 and #10386.
1570
0
    if(attributeHasBeenSetExplicitly(UCOL_CASE_FIRST)) {
1571
0
        appendAttribute(result, 'C', getAttribute(UCOL_CASE_FIRST, errorCode), errorCode);
1572
0
    }
1573
0
    if(attributeHasBeenSetExplicitly(UCOL_NUMERIC_COLLATION)) {
1574
0
        appendAttribute(result, 'D', getAttribute(UCOL_NUMERIC_COLLATION, errorCode), errorCode);
1575
0
    }
1576
0
    if(attributeHasBeenSetExplicitly(UCOL_CASE_LEVEL)) {
1577
0
        appendAttribute(result, 'E', getAttribute(UCOL_CASE_LEVEL, errorCode), errorCode);
1578
0
    }
1579
0
    if(attributeHasBeenSetExplicitly(UCOL_FRENCH_COLLATION)) {
1580
0
        appendAttribute(result, 'F', getAttribute(UCOL_FRENCH_COLLATION, errorCode), errorCode);
1581
0
    }
1582
    // Note: UCOL_HIRAGANA_QUATERNARY_MODE is deprecated and never changes away from default.
1583
0
    CharString collation = ulocimp_getKeywordValue(resultLocale, "collation", errorCode);
1584
0
    appendSubtag(result, 'K', collation.data(), collation.length(), errorCode);
1585
0
    CharString language;
1586
0
    CharString script;
1587
0
    CharString region;
1588
0
    CharString variant;
1589
0
    ulocimp_getSubtags(resultLocale, &language, &script, &region, &variant, nullptr, errorCode);
1590
0
    if (language.isEmpty()) {
1591
0
        appendSubtag(result, 'L', "root", 4, errorCode);
1592
0
    } else {
1593
0
        appendSubtag(result, 'L', language.data(), language.length(), errorCode);
1594
0
    }
1595
0
    if(attributeHasBeenSetExplicitly(UCOL_NORMALIZATION_MODE)) {
1596
0
        appendAttribute(result, 'N', getAttribute(UCOL_NORMALIZATION_MODE, errorCode), errorCode);
1597
0
    }
1598
0
    appendSubtag(result, 'R', region.data(), region.length(), errorCode);
1599
0
    if(attributeHasBeenSetExplicitly(UCOL_STRENGTH)) {
1600
0
        appendAttribute(result, 'S', getAttribute(UCOL_STRENGTH, errorCode), errorCode);
1601
0
    }
1602
0
    appendSubtag(result, 'V', variant.data(), variant.length(), errorCode);
1603
0
    appendSubtag(result, 'Z', script.data(), script.length(), errorCode);
1604
1605
0
    if(U_FAILURE(errorCode)) { return 0; }
1606
0
    return result.extract(buffer, capacity, errorCode);
1607
0
}
1608
1609
UBool
1610
0
RuleBasedCollator::isUnsafe(UChar32 c) const {
1611
0
    return data->isUnsafeBackward(c, settings->isNumeric());
1612
0
}
1613
1614
void U_CALLCONV
1615
0
RuleBasedCollator::computeMaxExpansions(const CollationTailoring *t, UErrorCode &errorCode) {
1616
0
    t->maxExpansions = CollationElementIterator::computeMaxExpansions(t->data, errorCode);
1617
0
}
1618
1619
UBool
1620
0
RuleBasedCollator::initMaxExpansions(UErrorCode &errorCode) const {
1621
0
    umtx_initOnce(tailoring->maxExpansionsInitOnce, computeMaxExpansions, tailoring, errorCode);
1622
0
    return U_SUCCESS(errorCode);
1623
0
}
1624
1625
CollationElementIterator *
1626
0
RuleBasedCollator::createCollationElementIterator(const UnicodeString& source) const {
1627
0
    UErrorCode errorCode = U_ZERO_ERROR;
1628
0
    if(!initMaxExpansions(errorCode)) { return nullptr; }
1629
0
    CollationElementIterator *cei = new CollationElementIterator(source, this, errorCode);
1630
0
    if(U_FAILURE(errorCode)) {
1631
0
        delete cei;
1632
0
        return nullptr;
1633
0
    }
1634
0
    return cei;
1635
0
}
1636
1637
CollationElementIterator *
1638
0
RuleBasedCollator::createCollationElementIterator(const CharacterIterator& source) const {
1639
0
    UErrorCode errorCode = U_ZERO_ERROR;
1640
0
    if(!initMaxExpansions(errorCode)) { return nullptr; }
1641
0
    CollationElementIterator *cei = new CollationElementIterator(source, this, errorCode);
1642
0
    if(U_FAILURE(errorCode)) {
1643
0
        delete cei;
1644
0
        return nullptr;
1645
0
    }
1646
0
    return cei;
1647
0
}
1648
1649
int32_t
1650
0
RuleBasedCollator::getMaxExpansion(int32_t order) const {
1651
0
    UErrorCode errorCode = U_ZERO_ERROR;
1652
0
    (void)initMaxExpansions(errorCode);
1653
0
    return CollationElementIterator::getMaxExpansion(tailoring->maxExpansions, order);
1654
0
}
1655
1656
U_NAMESPACE_END
1657
1658
#endif  // !UCONFIG_NO_COLLATION