Coverage Report

Created: 2022-11-20 06:20

/src/icu/icu4c/source/i18n/collationfastlatinbuilder.cpp
Line
Count
Source (jump to first uncovered line)
1
// © 2016 and later: Unicode, Inc. and others.
2
// License & terms of use: http://www.unicode.org/copyright.html
3
/*
4
*******************************************************************************
5
* Copyright (C) 2013-2015, International Business Machines
6
* Corporation and others.  All Rights Reserved.
7
*******************************************************************************
8
* collationfastlatinbuilder.cpp
9
*
10
* created on: 2013aug09
11
* created by: Markus W. Scherer
12
*/
13
14
#define DEBUG_COLLATION_FAST_LATIN_BUILDER 0  // 0 or 1 or 2
15
#if DEBUG_COLLATION_FAST_LATIN_BUILDER
16
#include <stdio.h>
17
#include <string>
18
#endif
19
20
#include "unicode/utypes.h"
21
22
#if !UCONFIG_NO_COLLATION
23
24
#include "unicode/ucol.h"
25
#include "unicode/ucharstrie.h"
26
#include "unicode/unistr.h"
27
#include "unicode/uobject.h"
28
#include "unicode/uscript.h"
29
#include "cmemory.h"
30
#include "collation.h"
31
#include "collationdata.h"
32
#include "collationfastlatin.h"
33
#include "collationfastlatinbuilder.h"
34
#include "uassert.h"
35
#include "uvectr64.h"
36
37
U_NAMESPACE_BEGIN
38
39
struct CollationData;
40
41
namespace {
42
43
/**
44
 * Compare two signed int64_t values as if they were unsigned.
45
 */
46
int32_t
47
4.24M
compareInt64AsUnsigned(int64_t a, int64_t b) {
48
4.24M
    if((uint64_t)a < (uint64_t)b) {
49
1.90M
        return -1;
50
2.33M
    } else if((uint64_t)a > (uint64_t)b) {
51
1.84M
        return 1;
52
1.84M
    } else {
53
494k
        return 0;
54
494k
    }
55
4.24M
}
56
57
// TODO: Merge this with the near-identical version in collationbasedatabuilder.cpp
58
/**
59
 * Like Java Collections.binarySearch(List, String, Comparator).
60
 *
61
 * @return the index>=0 where the item was found,
62
 *         or the index<0 for inserting the string at ~index in sorted order
63
 */
64
int32_t
65
622k
binarySearch(const int64_t list[], int32_t limit, int64_t ce) {
66
622k
    if (limit == 0) { return ~0; }
67
622k
    int32_t start = 0;
68
4.24M
    for (;;) {
69
4.24M
        int32_t i = (start + limit) / 2;
70
4.24M
        int32_t cmp = compareInt64AsUnsigned(ce, list[i]);
71
4.24M
        if (cmp == 0) {
72
494k
            return i;
73
3.74M
        } else if (cmp < 0) {
74
1.90M
            if (i == start) {
75
1.43k
                return ~start;  // insert ce before i
76
1.43k
            }
77
1.90M
            limit = i;
78
1.90M
        } else {
79
1.84M
            if (i == start) {
80
125k
                return ~(start + 1);  // insert ce after i
81
125k
            }
82
1.71M
            start = i;
83
1.71M
        }
84
4.24M
    }
85
622k
}
86
87
}  // namespace
88
89
CollationFastLatinBuilder::CollationFastLatinBuilder(UErrorCode &errorCode)
90
        : ce0(0), ce1(0),
91
          contractionCEs(errorCode), uniqueCEs(errorCode),
92
          miniCEs(NULL),
93
          firstDigitPrimary(0), firstLatinPrimary(0), lastLatinPrimary(0),
94
          firstShortPrimary(0), shortPrimaryOverflow(false),
95
557
          headerLength(0) {
96
557
}
97
98
557
CollationFastLatinBuilder::~CollationFastLatinBuilder() {
99
557
    uprv_free(miniCEs);
100
557
}
101
102
UBool
103
557
CollationFastLatinBuilder::forData(const CollationData &data, UErrorCode &errorCode) {
104
557
    if(U_FAILURE(errorCode)) { return false; }
105
557
    if(!result.isEmpty()) {  // This builder is not reusable.
106
0
        errorCode = U_INVALID_STATE_ERROR;
107
0
        return false;
108
0
    }
109
557
    if(!loadGroups(data, errorCode)) { return false; }
110
111
    // Fast handling of digits.
112
557
    firstShortPrimary = firstDigitPrimary;
113
557
    getCEs(data, errorCode);
114
557
    if(!encodeUniqueCEs(errorCode)) { return false; }
115
557
    if(shortPrimaryOverflow) {
116
        // Give digits long mini primaries,
117
        // so that there are more short primaries for letters.
118
51
        firstShortPrimary = firstLatinPrimary;
119
51
        resetCEs();
120
51
        getCEs(data, errorCode);
121
51
        if(!encodeUniqueCEs(errorCode)) { return false; }
122
51
    }
123
    // Note: If we still have a short-primary overflow but not a long-primary overflow,
124
    // then we could calculate how many more long primaries would fit,
125
    // and set the firstShortPrimary to that many after the current firstShortPrimary,
126
    // and try again.
127
    // However, this might only benefit the en_US_POSIX tailoring,
128
    // and it is simpler to suppress building fast Latin data for it in genrb,
129
    // or by returning false here if shortPrimaryOverflow.
130
131
557
    UBool ok = !shortPrimaryOverflow &&
132
557
            encodeCharCEs(errorCode) && encodeContractions(errorCode);
133
557
    contractionCEs.removeAllElements();  // might reduce heap memory usage
134
557
    uniqueCEs.removeAllElements();
135
557
    return ok;
136
557
}
137
138
UBool
139
557
CollationFastLatinBuilder::loadGroups(const CollationData &data, UErrorCode &errorCode) {
140
557
    if(U_FAILURE(errorCode)) { return false; }
141
557
    headerLength = 1 + NUM_SPECIAL_GROUPS;
142
557
    uint32_t r0 = (CollationFastLatin::VERSION << 8) | headerLength;
143
557
    result.append((UChar)r0);
144
    // The first few reordering groups should be special groups
145
    // (space, punct, ..., digit) followed by Latn, then Grek and other scripts.
146
2.78k
    for(int32_t i = 0; i < NUM_SPECIAL_GROUPS; ++i) {
147
2.22k
        lastSpecialPrimaries[i] = data.getLastPrimaryForGroup(UCOL_REORDER_CODE_FIRST + i);
148
2.22k
        if(lastSpecialPrimaries[i] == 0) {
149
            // missing data
150
0
            return false;
151
0
        }
152
2.22k
        result.append((UChar)0);  // reserve a slot for this group
153
2.22k
    }
154
155
557
    firstDigitPrimary = data.getFirstPrimaryForGroup(UCOL_REORDER_CODE_DIGIT);
156
557
    firstLatinPrimary = data.getFirstPrimaryForGroup(USCRIPT_LATIN);
157
557
    lastLatinPrimary = data.getLastPrimaryForGroup(USCRIPT_LATIN);
158
557
    if(firstDigitPrimary == 0 || firstLatinPrimary == 0) {
159
        // missing data
160
0
        return false;
161
0
    }
162
557
    return true;
163
557
}
164
165
UBool
166
12.0k
CollationFastLatinBuilder::inSameGroup(uint32_t p, uint32_t q) const {
167
    // Both or neither need to be encoded as short primaries,
168
    // so that we can test only one and use the same bit mask.
169
12.0k
    if(p >= firstShortPrimary) {
170
8.86k
        return q >= firstShortPrimary;
171
8.86k
    } else if(q >= firstShortPrimary) {
172
298
        return false;
173
298
    }
174
    // Both or neither must be potentially-variable,
175
    // so that we can test only one and determine if both are variable.
176
2.89k
    uint32_t lastVariablePrimary = lastSpecialPrimaries[NUM_SPECIAL_GROUPS - 1];
177
2.89k
    if(p > lastVariablePrimary) {
178
520
        return q > lastVariablePrimary;
179
2.37k
    } else if(q > lastVariablePrimary) {
180
0
        return false;
181
0
    }
182
    // Both will be encoded with long mini primaries.
183
    // They must be in the same special reordering group,
184
    // so that we can test only one and determine if both are variable.
185
2.37k
    U_ASSERT(p != 0 && q != 0);
186
4.75k
    for(int32_t i = 0;; ++i) {  // will terminate
187
4.75k
        uint32_t lastPrimary = lastSpecialPrimaries[i];
188
4.75k
        if(p <= lastPrimary) {
189
2.37k
            return q <= lastPrimary;
190
2.37k
        } else if(q <= lastPrimary) {
191
0
            return false;
192
0
        }
193
4.75k
    }
194
2.37k
}
195
196
void
197
51
CollationFastLatinBuilder::resetCEs() {
198
51
    contractionCEs.removeAllElements();
199
51
    uniqueCEs.removeAllElements();
200
51
    shortPrimaryOverflow = false;
201
51
    result.truncate(headerLength);
202
51
}
203
204
void
205
608
CollationFastLatinBuilder::getCEs(const CollationData &data, UErrorCode &errorCode) {
206
608
    if(U_FAILURE(errorCode)) { return; }
207
608
    int32_t i = 0;
208
272k
    for(UChar c = 0;; ++i, ++c) {
209
272k
        if(c == CollationFastLatin::LATIN_LIMIT) {
210
608
            c = CollationFastLatin::PUNCT_START;
211
272k
        } else if(c == CollationFastLatin::PUNCT_LIMIT) {
212
608
            break;
213
608
        }
214
272k
        const CollationData *d;
215
272k
        uint32_t ce32 = data.getCE32(c);
216
272k
        if(ce32 == Collation::FALLBACK_CE32) {
217
141k
            d = data.base;
218
141k
            ce32 = d->getCE32(c);
219
141k
        } else {
220
130k
            d = &data;
221
130k
        }
222
272k
        if(getCEsFromCE32(*d, c, ce32, errorCode)) {
223
260k
            charCEs[i][0] = ce0;
224
260k
            charCEs[i][1] = ce1;
225
260k
            addUniqueCE(ce0, errorCode);
226
260k
            addUniqueCE(ce1, errorCode);
227
260k
        } else {
228
            // bail out for c
229
12.3k
            charCEs[i][0] = ce0 = Collation::NO_CE;
230
12.3k
            charCEs[i][1] = ce1 = 0;
231
12.3k
        }
232
272k
        if(c == 0 && !isContractionCharCE(ce0)) {
233
            // Always map U+0000 to a contraction.
234
            // Write a contraction list with only a default value if there is no real contraction.
235
411
            U_ASSERT(contractionCEs.isEmpty());
236
411
            addContractionEntry(CollationFastLatin::CONTR_CHAR_MASK, ce0, ce1, errorCode);
237
411
            charCEs[0][0] = ((int64_t)Collation::NO_CE_PRIMARY << 32) | CONTRACTION_FLAG;
238
411
            charCEs[0][1] = 0;
239
411
        }
240
272k
    }
241
    // Terminate the last contraction list.
242
608
    contractionCEs.addElement(CollationFastLatin::CONTR_CHAR_MASK, errorCode);
243
608
}
244
245
UBool
246
CollationFastLatinBuilder::getCEsFromCE32(const CollationData &data, UChar32 c, uint32_t ce32,
247
278k
                                          UErrorCode &errorCode) {
248
278k
    if(U_FAILURE(errorCode)) { return false; }
249
278k
    ce32 = data.getFinalCE32(ce32);
250
278k
    ce1 = 0;
251
278k
    if(Collation::isSimpleOrLongCE32(ce32)) {
252
151k
        ce0 = Collation::ceFromCE32(ce32);
253
151k
    } else {
254
126k
        switch(Collation::tagFromCE32(ce32)) {
255
87.7k
        case Collation::LATIN_EXPANSION_TAG:
256
87.7k
            ce0 = Collation::latinCE0FromCE32(ce32);
257
87.7k
            ce1 = Collation::latinCE1FromCE32(ce32);
258
87.7k
            break;
259
25.5k
        case Collation::EXPANSION32_TAG: {
260
25.5k
            const uint32_t *ce32s = data.ce32s + Collation::indexFromCE32(ce32);
261
25.5k
            int32_t length = Collation::lengthFromCE32(ce32);
262
25.5k
            if(length <= 2) {
263
18.3k
                ce0 = Collation::ceFromCE32(ce32s[0]);
264
18.3k
                if(length == 2) {
265
18.3k
                    ce1 = Collation::ceFromCE32(ce32s[1]);
266
18.3k
                }
267
18.3k
                break;
268
18.3k
            } else {
269
7.25k
                return false;
270
7.25k
            }
271
25.5k
        }
272
10.4k
        case Collation::EXPANSION_TAG: {
273
10.4k
            const int64_t *ces = data.ces + Collation::indexFromCE32(ce32);
274
10.4k
            int32_t length = Collation::lengthFromCE32(ce32);
275
10.4k
            if(length <= 2) {
276
9.22k
                ce0 = ces[0];
277
9.22k
                if(length == 2) {
278
6.40k
                    ce1 = ces[1];
279
6.40k
                }
280
9.22k
                break;
281
9.22k
            } else {
282
1.26k
                return false;
283
1.26k
            }
284
10.4k
        }
285
        // Note: We could support PREFIX_TAG (assert c>=0)
286
        // by recursing on its default CE32 and checking that none of the prefixes starts
287
        // with a fast Latin character.
288
        // However, currently (2013) there are only the L-before-middle-dot
289
        // prefix mappings in the Latin range, and those would be rejected anyway.
290
2.32k
        case Collation::CONTRACTION_TAG:
291
2.32k
            U_ASSERT(c >= 0);
292
2.32k
            return getCEsFromContractionCE32(data, ce32, errorCode);
293
0
        case Collation::OFFSET_TAG:
294
0
            U_ASSERT(c >= 0);
295
0
            ce0 = data.getCEFromOffsetCE32(c, ce32);
296
0
            break;
297
795
        default:
298
795
            return false;
299
126k
        }
300
126k
    }
301
    // A mapping can be completely ignorable.
302
266k
    if(ce0 == 0) { return ce1 == 0; }
303
    // We do not support an ignorable ce0 unless it is completely ignorable.
304
227k
    uint32_t p0 = (uint32_t)(ce0 >> 32);
305
227k
    if(p0 == 0) { return false; }
306
    // We only support primaries up to the Latin script.
307
226k
    if(p0 > lastLatinPrimary) { return false; }
308
    // We support non-common secondary and case weights only together with short primaries.
309
224k
    uint32_t lower32_0 = (uint32_t)ce0;
310
224k
    if(p0 < firstShortPrimary) {
311
67.1k
        uint32_t sc0 = lower32_0 & Collation::SECONDARY_AND_CASE_MASK;
312
67.1k
        if(sc0 != Collation::COMMON_SECONDARY_CE) { return false; }
313
67.1k
    }
314
    // No below-common tertiary weights.
315
223k
    if((lower32_0 & Collation::ONLY_TERTIARY_MASK) < Collation::COMMON_WEIGHT16) { return false; }
316
223k
    if(ce1 != 0) {
317
        // Both primaries must be in the same group,
318
        // or both must get short mini primaries,
319
        // or a short-primary CE is followed by a secondary CE.
320
        // This is so that we can test the first primary and use the same mask for both,
321
        // and determine for both whether they are variable.
322
111k
        uint32_t p1 = (uint32_t)(ce1 >> 32);
323
111k
        if(p1 == 0 ? p0 < firstShortPrimary : !inSameGroup(p0, p1)) { return false; }
324
110k
        uint32_t lower32_1 = (uint32_t)ce1;
325
        // No tertiary CEs.
326
110k
        if((lower32_1 >> 16) == 0) { return false; }
327
        // We support non-common secondary and case weights
328
        // only for secondary CEs or together with short primaries.
329
110k
        if(p1 != 0 && p1 < firstShortPrimary) {
330
2.89k
            uint32_t sc1 = lower32_1 & Collation::SECONDARY_AND_CASE_MASK;
331
2.89k
            if(sc1 != Collation::COMMON_SECONDARY_CE) { return false; }
332
2.89k
        }
333
        // No below-common tertiary weights.
334
110k
        if((lower32_1 & Collation::ONLY_TERTIARY_MASK) < Collation::COMMON_WEIGHT16) { return false; }
335
110k
    }
336
    // No quaternary weights.
337
223k
    if(((ce0 | ce1) & Collation::QUATERNARY_MASK) != 0) { return false; }
338
223k
    return true;
339
223k
}
340
341
UBool
342
CollationFastLatinBuilder::getCEsFromContractionCE32(const CollationData &data, uint32_t ce32,
343
2.32k
                                                     UErrorCode &errorCode) {
344
2.32k
    if(U_FAILURE(errorCode)) { return false; }
345
2.32k
    const UChar *p = data.contexts + Collation::indexFromCE32(ce32);
346
2.32k
    ce32 = CollationData::readCE32(p);  // Default if no suffix match.
347
    // Since the original ce32 is not a prefix mapping,
348
    // the default ce32 must not be another contraction.
349
2.32k
    U_ASSERT(!Collation::isContractionCE32(ce32));
350
2.32k
    int32_t contractionIndex = contractionCEs.size();
351
2.32k
    if(getCEsFromCE32(data, U_SENTINEL, ce32, errorCode)) {
352
2.05k
        addContractionEntry(CollationFastLatin::CONTR_CHAR_MASK, ce0, ce1, errorCode);
353
2.05k
    } else {
354
        // Bail out for c-without-contraction.
355
266
        addContractionEntry(CollationFastLatin::CONTR_CHAR_MASK, Collation::NO_CE, 0, errorCode);
356
266
    }
357
    // Handle an encodable contraction unless the next contraction is too long
358
    // and starts with the same character.
359
2.32k
    int32_t prevX = -1;
360
2.32k
    UBool addContraction = false;
361
2.32k
    UCharsTrie::Iterator suffixes(p + 2, 0, errorCode);
362
33.3k
    while(suffixes.next(errorCode)) {
363
31.0k
        const UnicodeString &suffix = suffixes.getString();
364
31.0k
        int32_t x = CollationFastLatin::getCharIndex(suffix.charAt(0));
365
31.0k
        if(x < 0) { continue; }  // ignore anything but fast Latin text
366
9.23k
        if(x == prevX) {
367
5.14k
            if(addContraction) {
368
                // Bail out for all contractions starting with this character.
369
36
                addContractionEntry(x, Collation::NO_CE, 0, errorCode);
370
36
                addContraction = false;
371
36
            }
372
5.14k
            continue;
373
5.14k
        }
374
4.09k
        if(addContraction) {
375
2.11k
            addContractionEntry(prevX, ce0, ce1, errorCode);
376
2.11k
        }
377
4.09k
        ce32 = (uint32_t)suffixes.getValue();
378
4.09k
        if(suffix.length() == 1 && getCEsFromCE32(data, U_SENTINEL, ce32, errorCode)) {
379
2.91k
            addContraction = true;
380
2.91k
        } else {
381
1.18k
            addContractionEntry(x, Collation::NO_CE, 0, errorCode);
382
1.18k
            addContraction = false;
383
1.18k
        }
384
4.09k
        prevX = x;
385
4.09k
    }
386
2.32k
    if(addContraction) {
387
764
        addContractionEntry(prevX, ce0, ce1, errorCode);
388
764
    }
389
2.32k
    if(U_FAILURE(errorCode)) { return false; }
390
    // Note: There might not be any fast Latin contractions, but
391
    // we need to enter contraction handling anyway so that we can bail out
392
    // when there is a non-fast-Latin character following.
393
    // For example: Danish &Y<<u+umlaut, when we compare Y vs. u\u0308 we need to see the
394
    // following umlaut and bail out, rather than return the difference of Y vs. u.
395
2.32k
    ce0 = ((int64_t)Collation::NO_CE_PRIMARY << 32) | CONTRACTION_FLAG | contractionIndex;
396
2.32k
    ce1 = 0;
397
2.32k
    return true;
398
2.32k
}
399
400
void
401
CollationFastLatinBuilder::addContractionEntry(int32_t x, int64_t cce0, int64_t cce1,
402
6.82k
                                               UErrorCode &errorCode) {
403
6.82k
    contractionCEs.addElement(x, errorCode);
404
6.82k
    contractionCEs.addElement(cce0, errorCode);
405
6.82k
    contractionCEs.addElement(cce1, errorCode);
406
6.82k
    addUniqueCE(cce0, errorCode);
407
6.82k
    addUniqueCE(cce1, errorCode);
408
6.82k
}
409
410
void
411
533k
CollationFastLatinBuilder::addUniqueCE(int64_t ce, UErrorCode &errorCode) {
412
533k
    if(U_FAILURE(errorCode)) { return; }
413
533k
    if(ce == 0 || (uint32_t)(ce >> 32) == Collation::NO_CE_PRIMARY) { return; }
414
333k
    ce &= ~(int64_t)Collation::CASE_MASK;  // blank out case bits
415
333k
    int32_t i = binarySearch(uniqueCEs.getBuffer(), uniqueCEs.size(), ce);
416
333k
    if(i < 0) {
417
127k
        uniqueCEs.insertElementAt(ce, ~i, errorCode);
418
127k
    }
419
333k
}
420
421
uint32_t
422
288k
CollationFastLatinBuilder::getMiniCE(int64_t ce) const {
423
288k
    ce &= ~(int64_t)Collation::CASE_MASK;  // blank out case bits
424
288k
    int32_t index = binarySearch(uniqueCEs.getBuffer(), uniqueCEs.size(), ce);
425
288k
    U_ASSERT(index >= 0);
426
288k
    return miniCEs[index];
427
288k
}
428
429
UBool
430
608
CollationFastLatinBuilder::encodeUniqueCEs(UErrorCode &errorCode) {
431
608
    if(U_FAILURE(errorCode)) { return false; }
432
608
    uprv_free(miniCEs);
433
608
    miniCEs = (uint16_t *)uprv_malloc(uniqueCEs.size() * 2);
434
608
    if(miniCEs == NULL) {
435
0
        errorCode = U_MEMORY_ALLOCATION_ERROR;
436
0
        return false;
437
0
    }
438
608
    int32_t group = 0;
439
608
    uint32_t lastGroupPrimary = lastSpecialPrimaries[group];
440
    // The lowest unique CE must be at least a secondary CE.
441
608
    U_ASSERT(((uint32_t)uniqueCEs.elementAti(0) >> 16) != 0);
442
608
    uint32_t prevPrimary = 0;
443
608
    uint32_t prevSecondary = 0;
444
608
    uint32_t pri = 0;
445
608
    uint32_t sec = 0;
446
608
    uint32_t ter = CollationFastLatin::COMMON_TER;
447
128k
    for(int32_t i = 0; i < uniqueCEs.size(); ++i) {
448
127k
        int64_t ce = uniqueCEs.elementAti(i);
449
        // Note: At least one of the p/s/t weights changes from one unique CE to the next.
450
        // (uniqueCEs does not store case bits.)
451
127k
        uint32_t p = (uint32_t)(ce >> 32);
452
127k
        if(p != prevPrimary) {
453
88.3k
            while(p > lastGroupPrimary) {
454
2.43k
                U_ASSERT(pri <= CollationFastLatin::MAX_LONG);
455
                // Set the group's header entry to the
456
                // last "long primary" in or before the group.
457
2.43k
                result.setCharAt(1 + group, (UChar)pri);
458
2.43k
                if(++group < NUM_SPECIAL_GROUPS) {
459
1.82k
                    lastGroupPrimary = lastSpecialPrimaries[group];
460
1.82k
                } else {
461
608
                    lastGroupPrimary = 0xffffffff;
462
608
                    break;
463
608
                }
464
2.43k
            }
465
86.5k
            if(p < firstShortPrimary) {
466
54.6k
                if(pri == 0) {
467
608
                    pri = CollationFastLatin::MIN_LONG;
468
54.0k
                } else if(pri < CollationFastLatin::MAX_LONG) {
469
53.8k
                    pri += CollationFastLatin::LONG_INC;
470
53.8k
                } else {
471
#if DEBUG_COLLATION_FAST_LATIN_BUILDER
472
                    printf("long-primary overflow for %08x\n", p);
473
#endif
474
193
                    miniCEs[i] = CollationFastLatin::BAIL_OUT;
475
193
                    continue;
476
193
                }
477
54.6k
            } else {
478
31.8k
                if(pri < CollationFastLatin::MIN_SHORT) {
479
608
                    pri = CollationFastLatin::MIN_SHORT;
480
31.2k
                } else if(pri < (CollationFastLatin::MAX_SHORT - CollationFastLatin::SHORT_INC)) {
481
                    // Reserve the highest primary weight for U+FFFF.
482
26.2k
                    pri += CollationFastLatin::SHORT_INC;
483
26.2k
                } else {
484
#if DEBUG_COLLATION_FAST_LATIN_BUILDER
485
                    printf("short-primary overflow for %08x\n", p);
486
#endif
487
5.05k
                    shortPrimaryOverflow = true;
488
5.05k
                    miniCEs[i] = CollationFastLatin::BAIL_OUT;
489
5.05k
                    continue;
490
5.05k
                }
491
31.8k
            }
492
81.3k
            prevPrimary = p;
493
81.3k
            prevSecondary = Collation::COMMON_WEIGHT16;
494
81.3k
            sec = CollationFastLatin::COMMON_SEC;
495
81.3k
            ter = CollationFastLatin::COMMON_TER;
496
81.3k
        }
497
122k
        uint32_t lower32 = (uint32_t)ce;
498
122k
        uint32_t s = lower32 >> 16;
499
122k
        if(s != prevSecondary) {
500
12.5k
            if(pri == 0) {
501
9.38k
                if(sec == 0) {
502
608
                    sec = CollationFastLatin::MIN_SEC_HIGH;
503
8.77k
                } else if(sec < CollationFastLatin::MAX_SEC_HIGH) {
504
8.77k
                    sec += CollationFastLatin::SEC_INC;
505
8.77k
                } else {
506
0
                    miniCEs[i] = CollationFastLatin::BAIL_OUT;
507
0
                    continue;
508
0
                }
509
9.38k
                prevSecondary = s;
510
9.38k
                ter = CollationFastLatin::COMMON_TER;
511
9.38k
            } else if(s < Collation::COMMON_WEIGHT16) {
512
0
                if(sec == CollationFastLatin::COMMON_SEC) {
513
0
                    sec = CollationFastLatin::MIN_SEC_BEFORE;
514
0
                } else if(sec < CollationFastLatin::MAX_SEC_BEFORE) {
515
0
                    sec += CollationFastLatin::SEC_INC;
516
0
                } else {
517
0
                    miniCEs[i] = CollationFastLatin::BAIL_OUT;
518
0
                    continue;
519
0
                }
520
3.13k
            } else if(s == Collation::COMMON_WEIGHT16) {
521
0
                sec = CollationFastLatin::COMMON_SEC;
522
3.13k
            } else {
523
3.13k
                if(sec < CollationFastLatin::MIN_SEC_AFTER) {
524
2.41k
                    sec = CollationFastLatin::MIN_SEC_AFTER;
525
2.41k
                } else if(sec < CollationFastLatin::MAX_SEC_AFTER) {
526
712
                    sec += CollationFastLatin::SEC_INC;
527
712
                } else {
528
3
                    miniCEs[i] = CollationFastLatin::BAIL_OUT;
529
3
                    continue;
530
3
                }
531
3.13k
            }
532
12.5k
            prevSecondary = s;
533
12.5k
            ter = CollationFastLatin::COMMON_TER;
534
12.5k
        }
535
122k
        U_ASSERT((lower32 & Collation::CASE_MASK) == 0);  // blanked out in uniqueCEs
536
122k
        uint32_t t = lower32 & Collation::ONLY_TERTIARY_MASK;
537
122k
        if(t > Collation::COMMON_WEIGHT16) {
538
30.1k
            if(ter < CollationFastLatin::MAX_TER_AFTER) {
539
30.1k
                ++ter;
540
30.1k
            } else {
541
17
                miniCEs[i] = CollationFastLatin::BAIL_OUT;
542
17
                continue;
543
17
            }
544
30.1k
        }
545
122k
        if(CollationFastLatin::MIN_LONG <= pri && pri <= CollationFastLatin::MAX_LONG) {
546
58.5k
            U_ASSERT(sec == CollationFastLatin::COMMON_SEC);
547
58.5k
            miniCEs[i] = (uint16_t)(pri | ter);
548
64.1k
        } else {
549
64.1k
            miniCEs[i] = (uint16_t)(pri | sec | ter);
550
64.1k
        }
551
122k
    }
552
#if DEBUG_COLLATION_FAST_LATIN_BUILDER
553
    printf("last mini primary: %04x\n", pri);
554
#endif
555
#if DEBUG_COLLATION_FAST_LATIN_BUILDER >= 2
556
    for(int32_t i = 0; i < uniqueCEs.size(); ++i) {
557
        int64_t ce = uniqueCEs.elementAti(i);
558
        printf("unique CE 0x%016lx -> 0x%04x\n", ce, miniCEs[i]);
559
    }
560
#endif
561
608
    return U_SUCCESS(errorCode);
562
608
}
563
564
UBool
565
529
CollationFastLatinBuilder::encodeCharCEs(UErrorCode &errorCode) {
566
529
    if(U_FAILURE(errorCode)) { return false; }
567
529
    int32_t miniCEsStart = result.length();
568
237k
    for(int32_t i = 0; i < CollationFastLatin::NUM_FAST_CHARS; ++i) {
569
236k
        result.append((UChar)0);  // initialize to completely ignorable
570
236k
    }
571
529
    int32_t indexBase = result.length();
572
237k
    for(int32_t i = 0; i < CollationFastLatin::NUM_FAST_CHARS; ++i) {
573
236k
        int64_t ce = charCEs[i][0];
574
236k
        if(isContractionCharCE(ce)) { continue; }  // defer contraction
575
234k
        uint32_t miniCE = encodeTwoCEs(ce, charCEs[i][1]);
576
234k
        if(miniCE > 0xffff) {
577
            // Note: There is a chance that this new expansion is the same as a previous one,
578
            // and if so, then we could reuse the other expansion.
579
            // However, that seems unlikely.
580
9.15k
            int32_t expansionIndex = result.length() - indexBase;
581
9.15k
            if(expansionIndex > (int32_t)CollationFastLatin::INDEX_MASK) {
582
0
                miniCE = CollationFastLatin::BAIL_OUT;
583
9.15k
            } else {
584
9.15k
                result.append((UChar)(miniCE >> 16)).append((UChar)miniCE);
585
9.15k
                miniCE = CollationFastLatin::EXPANSION | expansionIndex;
586
9.15k
            }
587
9.15k
        }
588
234k
        result.setCharAt(miniCEsStart + i, (UChar)miniCE);
589
234k
    }
590
529
    return U_SUCCESS(errorCode);
591
529
}
592
593
UBool
594
529
CollationFastLatinBuilder::encodeContractions(UErrorCode &errorCode) {
595
    // We encode all contraction lists so that the first word of a list
596
    // terminates the previous list, and we only need one additional terminator at the end.
597
529
    if(U_FAILURE(errorCode)) { return false; }
598
529
    int32_t indexBase = headerLength + CollationFastLatin::NUM_FAST_CHARS;
599
529
    int32_t firstContractionIndex = result.length();
600
237k
    for(int32_t i = 0; i < CollationFastLatin::NUM_FAST_CHARS; ++i) {
601
236k
        int64_t ce = charCEs[i][0];
602
236k
        if(!isContractionCharCE(ce)) { continue; }
603
2.15k
        int32_t contractionIndex = result.length() - indexBase;
604
2.15k
        if(contractionIndex > (int32_t)CollationFastLatin::INDEX_MASK) {
605
0
            result.setCharAt(headerLength + i, CollationFastLatin::BAIL_OUT);
606
0
            continue;
607
0
        }
608
2.15k
        UBool firstTriple = true;
609
7.17k
        for(int32_t index = (int32_t)ce & 0x7fffffff;; index += 3) {
610
7.17k
            int32_t x = static_cast<int32_t>(contractionCEs.elementAti(index));
611
7.17k
            if((uint32_t)x == CollationFastLatin::CONTR_CHAR_MASK && !firstTriple) { break; }
612
5.02k
            int64_t cce0 = contractionCEs.elementAti(index + 1);
613
5.02k
            int64_t cce1 = contractionCEs.elementAti(index + 2);
614
5.02k
            uint32_t miniCE = encodeTwoCEs(cce0, cce1);
615
5.02k
            if(miniCE == CollationFastLatin::BAIL_OUT) {
616
1.16k
                result.append((UChar)(x | (1 << CollationFastLatin::CONTR_LENGTH_SHIFT)));
617
3.86k
            } else if(miniCE <= 0xffff) {
618
3.28k
                result.append((UChar)(x | (2 << CollationFastLatin::CONTR_LENGTH_SHIFT)));
619
3.28k
                result.append((UChar)miniCE);
620
3.28k
            } else {
621
581
                result.append((UChar)(x | (3 << CollationFastLatin::CONTR_LENGTH_SHIFT)));
622
581
                result.append((UChar)(miniCE >> 16)).append((UChar)miniCE);
623
581
            }
624
5.02k
            firstTriple = false;
625
5.02k
        }
626
        // Note: There is a chance that this new contraction list is the same as a previous one,
627
        // and if so, then we could truncate the result and reuse the other list.
628
        // However, that seems unlikely.
629
2.15k
        result.setCharAt(headerLength + i,
630
2.15k
                         (UChar)(CollationFastLatin::CONTRACTION | contractionIndex));
631
2.15k
    }
632
529
    if(result.length() > firstContractionIndex) {
633
        // Terminate the last contraction list.
634
529
        result.append((UChar)CollationFastLatin::CONTR_CHAR_MASK);
635
529
    }
636
529
    if(result.isBogus()) {
637
0
        errorCode = U_MEMORY_ALLOCATION_ERROR;
638
0
        return false;
639
0
    }
640
#if DEBUG_COLLATION_FAST_LATIN_BUILDER
641
    printf("** fast Latin %d * 2 = %d bytes\n", result.length(), result.length() * 2);
642
    puts("   header & below-digit groups map");
643
    int32_t i = 0;
644
    for(; i < headerLength; ++i) {
645
        printf(" %04x", result[i]);
646
    }
647
    printf("\n   char mini CEs");
648
    U_ASSERT(CollationFastLatin::NUM_FAST_CHARS % 16 == 0);
649
    for(; i < indexBase; i += 16) {
650
        UChar32 c = i - headerLength;
651
        if(c >= CollationFastLatin::LATIN_LIMIT) {
652
            c = CollationFastLatin::PUNCT_START + c - CollationFastLatin::LATIN_LIMIT;
653
        }
654
        printf("\n %04x:", c);
655
        for(int32_t j = 0; j < 16; ++j) {
656
            printf(" %04x", result[i + j]);
657
        }
658
    }
659
    printf("\n   expansions & contractions");
660
    for(; i < result.length(); ++i) {
661
        if((i - indexBase) % 16 == 0) { puts(""); }
662
        printf(" %04x", result[i]);
663
    }
664
    puts("");
665
#endif
666
529
    return true;
667
529
}
668
669
uint32_t
670
239k
CollationFastLatinBuilder::encodeTwoCEs(int64_t first, int64_t second) const {
671
239k
    if(first == 0) {
672
34.9k
        return 0;  // completely ignorable
673
34.9k
    }
674
204k
    if(first == Collation::NO_CE) {
675
11.8k
        return CollationFastLatin::BAIL_OUT;
676
11.8k
    }
677
193k
    U_ASSERT((uint32_t)(first >> 32) != Collation::NO_CE_PRIMARY);
678
679
193k
    uint32_t miniCE = getMiniCE(first);
680
193k
    if(miniCE == CollationFastLatin::BAIL_OUT) { return miniCE; }
681
193k
    if(miniCE >= CollationFastLatin::MIN_SHORT) {
682
        // Extract & copy the case bits.
683
        // Shift them from normal CE bits 15..14 to mini CE bits 4..3.
684
134k
        uint32_t c = (((uint32_t)first & Collation::CASE_MASK) >> (14 - 3));
685
        // Only in mini CEs: Ignorable case bits = 0, lowercase = 1.
686
134k
        c += CollationFastLatin::LOWER_CASE;
687
134k
        miniCE |= c;
688
134k
    }
689
193k
    if(second == 0) { return miniCE; }
690
691
95.7k
    uint32_t miniCE1 = getMiniCE(second);
692
95.7k
    if(miniCE1 == CollationFastLatin::BAIL_OUT) { return miniCE1; }
693
694
95.5k
    uint32_t case1 = (uint32_t)second & Collation::CASE_MASK;
695
95.5k
    if(miniCE >= CollationFastLatin::MIN_SHORT &&
696
95.5k
            (miniCE & CollationFastLatin::SECONDARY_MASK) == CollationFastLatin::COMMON_SEC) {
697
        // Try to combine the two mini CEs into one.
698
90.2k
        uint32_t sec1 = miniCE1 & CollationFastLatin::SECONDARY_MASK;
699
90.2k
        uint32_t ter1 = miniCE1 & CollationFastLatin::TERTIARY_MASK;
700
90.2k
        if(sec1 >= CollationFastLatin::MIN_SEC_HIGH && case1 == 0 &&
701
90.2k
                ter1 == CollationFastLatin::COMMON_TER) {
702
            // sec1>=sec_high implies pri1==0.
703
85.7k
            return (miniCE & ~CollationFastLatin::SECONDARY_MASK) | sec1;
704
85.7k
        }
705
90.2k
    }
706
707
9.73k
    if(miniCE1 <= CollationFastLatin::SECONDARY_MASK || CollationFastLatin::MIN_SHORT <= miniCE1) {
708
        // Secondary CE, or a CE with a short primary, copy the case bits.
709
7.35k
        case1 = (case1 >> (14 - 3)) + CollationFastLatin::LOWER_CASE;
710
7.35k
        miniCE1 |= case1;
711
7.35k
    }
712
9.73k
    return (miniCE << 16) | miniCE1;
713
95.5k
}
714
715
U_NAMESPACE_END
716
717
#endif  // !UCONFIG_NO_COLLATION