Coverage Report

Created: 2018-09-25 14:53

/src/mozilla-central/intl/icu/source/common/normalizer2impl.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
*
6
*   Copyright (C) 2009-2014, International Business Machines
7
*   Corporation and others.  All Rights Reserved.
8
*
9
*******************************************************************************
10
*   file name:  normalizer2impl.cpp
11
*   encoding:   UTF-8
12
*   tab size:   8 (not used)
13
*   indentation:4
14
*
15
*   created on: 2009nov22
16
*   created by: Markus W. Scherer
17
*/
18
19
#include "unicode/utypes.h"
20
21
#if !UCONFIG_NO_NORMALIZATION
22
23
#include "unicode/bytestream.h"
24
#include "unicode/edits.h"
25
#include "unicode/normalizer2.h"
26
#include "unicode/stringoptions.h"
27
#include "unicode/udata.h"
28
#include "unicode/ustring.h"
29
#include "unicode/utf16.h"
30
#include "unicode/utf8.h"
31
#include "bytesinkutil.h"
32
#include "cmemory.h"
33
#include "mutex.h"
34
#include "normalizer2impl.h"
35
#include "putilimp.h"
36
#include "uassert.h"
37
#include "uset_imp.h"
38
#include "utrie2.h"
39
#include "uvector.h"
40
41
U_NAMESPACE_BEGIN
42
43
namespace {
44
45
/**
46
 * UTF-8 lead byte for minNoMaybeCP.
47
 * Can be lower than the actual lead byte for c.
48
 * Typically U+0300 for NFC/NFD, U+00A0 for NFKC/NFKD, U+0041 for NFKC_Casefold.
49
 */
50
0
inline uint8_t leadByteForCP(UChar32 c) {
51
0
    if (c <= 0x7f) {
52
0
        return (uint8_t)c;
53
0
    } else if (c <= 0x7ff) {
54
0
        return (uint8_t)(0xc0+(c>>6));
55
0
    } else {
56
0
        // Should not occur because ccc(U+0300)!=0.
57
0
        return 0xe0;
58
0
    }
59
0
}
60
61
/**
62
 * Returns the code point from one single well-formed UTF-8 byte sequence
63
 * between cpStart and cpLimit.
64
 *
65
 * UTrie2 UTF-8 macros do not assemble whole code points (for efficiency).
66
 * When we do need the code point, we call this function.
67
 * We should not need it for normalization-inert data (norm16==0).
68
 * Illegal sequences yield the error value norm16==0 just like real normalization-inert code points.
69
 */
70
0
UChar32 codePointFromValidUTF8(const uint8_t *cpStart, const uint8_t *cpLimit) {
71
0
    // Similar to U8_NEXT_UNSAFE(s, i, c).
72
0
    U_ASSERT(cpStart < cpLimit);
73
0
    uint8_t c = *cpStart;
74
0
    switch(cpLimit-cpStart) {
75
0
    case 1:
76
0
        return c;
77
0
    case 2:
78
0
        return ((c&0x1f)<<6) | (cpStart[1]&0x3f);
79
0
    case 3:
80
0
        // no need for (c&0xf) because the upper bits are truncated after <<12 in the cast to (UChar)
81
0
        return (UChar)((c<<12) | ((cpStart[1]&0x3f)<<6) | (cpStart[2]&0x3f));
82
0
    case 4:
83
0
        return ((c&7)<<18) | ((cpStart[1]&0x3f)<<12) | ((cpStart[2]&0x3f)<<6) | (cpStart[3]&0x3f);
84
0
    default:
85
0
        U_ASSERT(FALSE);  // Should not occur.
86
0
        return U_SENTINEL;
87
0
    }
88
0
}
89
90
/**
91
 * Returns the last code point in [start, p[ if it is valid and in U+1000..U+D7FF.
92
 * Otherwise returns a negative value.
93
 */
94
0
UChar32 previousHangulOrJamo(const uint8_t *start, const uint8_t *p) {
95
0
    if ((p - start) >= 3) {
96
0
        p -= 3;
97
0
        uint8_t l = *p;
98
0
        uint8_t t1, t2;
99
0
        if (0xe1 <= l && l <= 0xed &&
100
0
                (t1 = (uint8_t)(p[1] - 0x80)) <= 0x3f &&
101
0
                (t2 = (uint8_t)(p[2] - 0x80)) <= 0x3f &&
102
0
                (l < 0xed || t1 <= 0x1f)) {
103
0
            return ((l & 0xf) << 12) | (t1 << 6) | t2;
104
0
        }
105
0
    }
106
0
    return U_SENTINEL;
107
0
}
108
109
/**
110
 * Returns the offset from the Jamo T base if [src, limit[ starts with a single Jamo T code point.
111
 * Otherwise returns a negative value.
112
 */
113
0
int32_t getJamoTMinusBase(const uint8_t *src, const uint8_t *limit) {
114
0
    // Jamo T: E1 86 A8..E1 87 82
115
0
    if ((limit - src) >= 3 && *src == 0xe1) {
116
0
        if (src[1] == 0x86) {
117
0
            uint8_t t = src[2];
118
0
            // The first Jamo T is U+11A8 but JAMO_T_BASE is 11A7.
119
0
            // Offset 0 does not correspond to any conjoining Jamo.
120
0
            if (0xa8 <= t && t <= 0xbf) {
121
0
                return t - 0xa7;
122
0
            }
123
0
        } else if (src[1] == 0x87) {
124
0
            uint8_t t = src[2];
125
0
            if ((int8_t)t <= (int8_t)0x82) {
126
0
                return t - (0xa7 - 0x40);
127
0
            }
128
0
        }
129
0
    }
130
0
    return -1;
131
0
}
132
133
void
134
appendCodePointDelta(const uint8_t *cpStart, const uint8_t *cpLimit, int32_t delta,
135
0
                     ByteSink &sink, Edits *edits) {
136
0
    char buffer[U8_MAX_LENGTH];
137
0
    int32_t length;
138
0
    int32_t cpLength = (int32_t)(cpLimit - cpStart);
139
0
    if (cpLength == 1) {
140
0
        // The builder makes ASCII map to ASCII.
141
0
        buffer[0] = (uint8_t)(*cpStart + delta);
142
0
        length = 1;
143
0
    } else {
144
0
        int32_t trail = *(cpLimit-1) + delta;
145
0
        if (0x80 <= trail && trail <= 0xbf) {
146
0
            // The delta only changes the last trail byte.
147
0
            --cpLimit;
148
0
            length = 0;
149
0
            do { buffer[length++] = *cpStart++; } while (cpStart < cpLimit);
150
0
            buffer[length++] = (uint8_t)trail;
151
0
        } else {
152
0
            // Decode the code point, add the delta, re-encode.
153
0
            UChar32 c = codePointFromValidUTF8(cpStart, cpLimit) + delta;
154
0
            length = 0;
155
0
            U8_APPEND_UNSAFE(buffer, length, c);
156
0
        }
157
0
    }
158
0
    if (edits != nullptr) {
159
0
        edits->addReplace(cpLength, length);
160
0
    }
161
0
    sink.Append(buffer, length);
162
0
}
163
164
}  // namespace
165
166
// ReorderingBuffer -------------------------------------------------------- ***
167
168
ReorderingBuffer::ReorderingBuffer(const Normalizer2Impl &ni, UnicodeString &dest,
169
                                   UErrorCode &errorCode) :
170
        impl(ni), str(dest),
171
        start(str.getBuffer(8)), reorderStart(start), limit(start),
172
0
        remainingCapacity(str.getCapacity()), lastCC(0) {
173
0
    if (start == nullptr && U_SUCCESS(errorCode)) {
174
0
        // getBuffer() already did str.setToBogus()
175
0
        errorCode = U_MEMORY_ALLOCATION_ERROR;
176
0
    }
177
0
}
178
179
91.3k
UBool ReorderingBuffer::init(int32_t destCapacity, UErrorCode &errorCode) {
180
91.3k
    int32_t length=str.length();
181
91.3k
    start=str.getBuffer(destCapacity);
182
91.3k
    if(start==NULL) {
183
0
        // getBuffer() already did str.setToBogus()
184
0
        errorCode=U_MEMORY_ALLOCATION_ERROR;
185
0
        return FALSE;
186
0
    }
187
91.3k
    limit=start+length;
188
91.3k
    remainingCapacity=str.getCapacity()-length;
189
91.3k
    reorderStart=start;
190
91.3k
    if(start==limit) {
191
37.5k
        lastCC=0;
192
53.8k
    } else {
193
53.8k
        setIterator();
194
53.8k
        lastCC=previousCC();
195
53.8k
        // Set reorderStart after the last code point with cc<=1 if there is one.
196
53.8k
        if(lastCC>1) {
197
0
            while(previousCC()>1) {}
198
0
        }
199
53.8k
        reorderStart=codePointLimit;
200
53.8k
    }
201
91.3k
    return TRUE;
202
91.3k
}
203
204
0
UBool ReorderingBuffer::equals(const UChar *otherStart, const UChar *otherLimit) const {
205
0
    int32_t length=(int32_t)(limit-start);
206
0
    return
207
0
        length==(int32_t)(otherLimit-otherStart) &&
208
0
        0==u_memcmp(start, otherStart, length);
209
0
}
210
211
0
UBool ReorderingBuffer::equals(const uint8_t *otherStart, const uint8_t *otherLimit) const {
212
0
    U_ASSERT((otherLimit - otherStart) <= INT32_MAX);  // ensured by caller
213
0
    int32_t length = (int32_t)(limit - start);
214
0
    int32_t otherLength = (int32_t)(otherLimit - otherStart);
215
0
    // For equal strings, UTF-8 is at least as long as UTF-16, and at most three times as long.
216
0
    if (otherLength < length || (otherLength / 3) > length) {
217
0
        return FALSE;
218
0
    }
219
0
    // Compare valid strings from between normalization boundaries.
220
0
    // (Invalid sequences are normalization-inert.)
221
0
    for (int32_t i = 0, j = 0;;) {
222
0
        if (i >= length) {
223
0
            return j >= otherLength;
224
0
        } else if (j >= otherLength) {
225
0
            return FALSE;
226
0
        }
227
0
        // Not at the end of either string yet.
228
0
        UChar32 c, other;
229
0
        U16_NEXT_UNSAFE(start, i, c);
230
0
        U8_NEXT_UNSAFE(otherStart, j, other);
231
0
        if (c != other) {
232
0
            return FALSE;
233
0
        }
234
0
    }
235
0
}
236
237
0
UBool ReorderingBuffer::appendSupplementary(UChar32 c, uint8_t cc, UErrorCode &errorCode) {
238
0
    if(remainingCapacity<2 && !resize(2, errorCode)) {
239
0
        return FALSE;
240
0
    }
241
0
    if(lastCC<=cc || cc==0) {
242
0
        limit[0]=U16_LEAD(c);
243
0
        limit[1]=U16_TRAIL(c);
244
0
        limit+=2;
245
0
        lastCC=cc;
246
0
        if(cc<=1) {
247
0
            reorderStart=limit;
248
0
        }
249
0
    } else {
250
0
        insert(c, cc);
251
0
    }
252
0
    remainingCapacity-=2;
253
0
    return TRUE;
254
0
}
255
256
UBool ReorderingBuffer::append(const UChar *s, int32_t length,
257
                               uint8_t leadCC, uint8_t trailCC,
258
128
                               UErrorCode &errorCode) {
259
128
    if(length==0) {
260
109
        return TRUE;
261
109
    }
262
19
    if(remainingCapacity<length && !resize(length, errorCode)) {
263
0
        return FALSE;
264
0
    }
265
19
    remainingCapacity-=length;
266
19
    if(lastCC<=leadCC || leadCC==0) {
267
19
        if(trailCC<=1) {
268
0
            reorderStart=limit+length;
269
19
        } else if(leadCC<=1) {
270
19
            reorderStart=limit+1;  // Ok if not a code point boundary.
271
19
        }
272
19
        const UChar *sLimit=s+length;
273
38
        do { *limit++=*s++; } while(s!=sLimit);
274
19
        lastCC=trailCC;
275
19
    } else {
276
0
        int32_t i=0;
277
0
        UChar32 c;
278
0
        U16_NEXT(s, i, length, c);
279
0
        insert(c, leadCC);  // insert first code point
280
0
        while(i<length) {
281
0
            U16_NEXT(s, i, length, c);
282
0
            if(i<length) {
283
0
                // s must be in NFD, otherwise we need to use getCC().
284
0
                leadCC=Normalizer2Impl::getCCFromYesOrMaybe(impl.getNorm16(c));
285
0
            } else {
286
0
                leadCC=trailCC;
287
0
            }
288
0
            append(c, leadCC, errorCode);
289
0
        }
290
0
    }
291
19
    return TRUE;
292
19
}
293
294
0
UBool ReorderingBuffer::appendZeroCC(UChar32 c, UErrorCode &errorCode) {
295
0
    int32_t cpLength=U16_LENGTH(c);
296
0
    if(remainingCapacity<cpLength && !resize(cpLength, errorCode)) {
297
0
        return FALSE;
298
0
    }
299
0
    remainingCapacity-=cpLength;
300
0
    if(cpLength==1) {
301
0
        *limit++=(UChar)c;
302
0
    } else {
303
0
        limit[0]=U16_LEAD(c);
304
0
        limit[1]=U16_TRAIL(c);
305
0
        limit+=2;
306
0
    }
307
0
    lastCC=0;
308
0
    reorderStart=limit;
309
0
    return TRUE;
310
0
}
311
312
206k
UBool ReorderingBuffer::appendZeroCC(const UChar *s, const UChar *sLimit, UErrorCode &errorCode) {
313
206k
    if(s==sLimit) {
314
0
        return TRUE;
315
0
    }
316
206k
    int32_t length=(int32_t)(sLimit-s);
317
206k
    if(remainingCapacity<length && !resize(length, errorCode)) {
318
0
        return FALSE;
319
0
    }
320
206k
    u_memcpy(limit, s, length);
321
206k
    limit+=length;
322
206k
    remainingCapacity-=length;
323
206k
    lastCC=0;
324
206k
    reorderStart=limit;
325
206k
    return TRUE;
326
206k
}
327
328
0
void ReorderingBuffer::remove() {
329
0
    reorderStart=limit=start;
330
0
    remainingCapacity=str.getCapacity();
331
0
    lastCC=0;
332
0
}
333
334
1.10k
void ReorderingBuffer::removeSuffix(int32_t suffixLength) {
335
1.10k
    if(suffixLength<(limit-start)) {
336
1.09k
        limit-=suffixLength;
337
1.09k
        remainingCapacity+=suffixLength;
338
1.09k
    } else {
339
12
        limit=start;
340
12
        remainingCapacity=str.getCapacity();
341
12
    }
342
1.10k
    lastCC=0;
343
1.10k
    reorderStart=limit;
344
1.10k
}
345
346
1.80k
UBool ReorderingBuffer::resize(int32_t appendLength, UErrorCode &errorCode) {
347
1.80k
    int32_t reorderStartIndex=(int32_t)(reorderStart-start);
348
1.80k
    int32_t length=(int32_t)(limit-start);
349
1.80k
    str.releaseBuffer(length);
350
1.80k
    int32_t newCapacity=length+appendLength;
351
1.80k
    int32_t doubleCapacity=2*str.getCapacity();
352
1.80k
    if(newCapacity<doubleCapacity) {
353
1.80k
        newCapacity=doubleCapacity;
354
1.80k
    }
355
1.80k
    if(newCapacity<256) {
356
1.79k
        newCapacity=256;
357
1.79k
    }
358
1.80k
    start=str.getBuffer(newCapacity);
359
1.80k
    if(start==NULL) {
360
0
        // getBuffer() already did str.setToBogus()
361
0
        errorCode=U_MEMORY_ALLOCATION_ERROR;
362
0
        return FALSE;
363
0
    }
364
1.80k
    reorderStart=start+reorderStartIndex;
365
1.80k
    limit=start+length;
366
1.80k
    remainingCapacity=str.getCapacity()-length;
367
1.80k
    return TRUE;
368
1.80k
}
369
370
0
void ReorderingBuffer::skipPrevious() {
371
0
    codePointLimit=codePointStart;
372
0
    UChar c=*--codePointStart;
373
0
    if(U16_IS_TRAIL(c) && start<codePointStart && U16_IS_LEAD(*(codePointStart-1))) {
374
0
        --codePointStart;
375
0
    }
376
0
}
377
378
53.8k
uint8_t ReorderingBuffer::previousCC() {
379
53.8k
    codePointLimit=codePointStart;
380
53.8k
    if(reorderStart>=codePointStart) {
381
0
        return 0;
382
0
    }
383
53.8k
    UChar32 c=*--codePointStart;
384
53.8k
    UChar c2;
385
53.8k
    if(U16_IS_TRAIL(c) && start<codePointStart && U16_IS_LEAD(c2=*(codePointStart-1))) {
386
0
        --codePointStart;
387
0
        c=U16_GET_SUPPLEMENTARY(c2, c);
388
0
    }
389
53.8k
    return impl.getCCFromYesOrMaybeCP(c);
390
53.8k
}
391
392
// Inserts c somewhere before the last character.
393
// Requires 0<cc<lastCC which implies reorderStart<limit.
394
0
void ReorderingBuffer::insert(UChar32 c, uint8_t cc) {
395
0
    for(setIterator(), skipPrevious(); previousCC()>cc;) {}
396
0
    // insert c at codePointLimit, after the character with prevCC<=cc
397
0
    UChar *q=limit;
398
0
    UChar *r=limit+=U16_LENGTH(c);
399
0
    do {
400
0
        *--r=*--q;
401
0
    } while(codePointLimit!=q);
402
0
    writeCodePoint(q, c);
403
0
    if(cc<=1) {
404
0
        reorderStart=r;
405
0
    }
406
0
}
407
408
// Normalizer2Impl --------------------------------------------------------- ***
409
410
struct CanonIterData : public UMemory {
411
    CanonIterData(UErrorCode &errorCode);
412
    ~CanonIterData();
413
    void addToStartSet(UChar32 origin, UChar32 decompLead, UErrorCode &errorCode);
414
    UTrie2 *trie;
415
    UVector canonStartSets;  // contains UnicodeSet *
416
};
417
418
0
Normalizer2Impl::~Normalizer2Impl() {
419
0
    delete fCanonIterData;
420
0
}
421
422
void
423
Normalizer2Impl::init(const int32_t *inIndexes, const UTrie2 *inTrie,
424
3
                      const uint16_t *inExtraData, const uint8_t *inSmallFCD) {
425
3
    minDecompNoCP=inIndexes[IX_MIN_DECOMP_NO_CP];
426
3
    minCompNoMaybeCP=inIndexes[IX_MIN_COMP_NO_MAYBE_CP];
427
3
    minLcccCP=inIndexes[IX_MIN_LCCC_CP];
428
3
429
3
    minYesNo=inIndexes[IX_MIN_YES_NO];
430
3
    minYesNoMappingsOnly=inIndexes[IX_MIN_YES_NO_MAPPINGS_ONLY];
431
3
    minNoNo=inIndexes[IX_MIN_NO_NO];
432
3
    minNoNoCompBoundaryBefore=inIndexes[IX_MIN_NO_NO_COMP_BOUNDARY_BEFORE];
433
3
    minNoNoCompNoMaybeCC=inIndexes[IX_MIN_NO_NO_COMP_NO_MAYBE_CC];
434
3
    minNoNoEmpty=inIndexes[IX_MIN_NO_NO_EMPTY];
435
3
    limitNoNo=inIndexes[IX_LIMIT_NO_NO];
436
3
    minMaybeYes=inIndexes[IX_MIN_MAYBE_YES];
437
3
    U_ASSERT((minMaybeYes&7)==0);  // 8-aligned for noNoDelta bit fields
438
3
    centerNoNoDelta=(minMaybeYes>>DELTA_SHIFT)-MAX_DELTA-1;
439
3
440
3
    normTrie=inTrie;
441
3
442
3
    maybeYesCompositions=inExtraData;
443
3
    extraData=maybeYesCompositions+((MIN_NORMAL_MAYBE_YES-minMaybeYes)>>OFFSET_SHIFT);
444
3
445
3
    smallFCD=inSmallFCD;
446
3
}
447
448
class LcccContext {
449
public:
450
0
    LcccContext(const Normalizer2Impl &ni, UnicodeSet &s) : impl(ni), set(s) {}
451
452
0
    void handleRange(UChar32 start, UChar32 end, uint16_t norm16) {
453
0
        if (norm16 > Normalizer2Impl::MIN_NORMAL_MAYBE_YES &&
454
0
                norm16 != Normalizer2Impl::JAMO_VT) {
455
0
            set.add(start, end);
456
0
        } else if (impl.minNoNoCompNoMaybeCC <= norm16 && norm16 < impl.limitNoNo) {
457
0
            uint16_t fcd16=impl.getFCD16(start);
458
0
            if(fcd16>0xff) { set.add(start, end); }
459
0
        }
460
0
    }
461
462
private:
463
    const Normalizer2Impl &impl;
464
    UnicodeSet &set;
465
};
466
467
namespace {
468
469
struct PropertyStartsContext {
470
    PropertyStartsContext(const Normalizer2Impl &ni, const USetAdder *adder)
471
0
            : impl(ni), sa(adder) {}
472
473
    const Normalizer2Impl &impl;
474
    const USetAdder *sa;
475
};
476
477
}  // namespace
478
479
U_CDECL_BEGIN
480
481
static UBool U_CALLCONV
482
0
enumLcccRange(const void *context, UChar32 start, UChar32 end, uint32_t value) {
483
0
    ((LcccContext *)context)->handleRange(start, end, (uint16_t)value);
484
0
    return TRUE;
485
0
}
486
487
static UBool U_CALLCONV
488
0
enumNorm16PropertyStartsRange(const void *context, UChar32 start, UChar32 end, uint32_t value) {
489
0
    /* add the start code point to the USet */
490
0
    const PropertyStartsContext *ctx=(const PropertyStartsContext *)context;
491
0
    const USetAdder *sa=ctx->sa;
492
0
    sa->add(sa->set, start);
493
0
    if (start != end && ctx->impl.isAlgorithmicNoNo((uint16_t)value) &&
494
0
            (value & Normalizer2Impl::DELTA_TCCC_MASK) > Normalizer2Impl::DELTA_TCCC_1) {
495
0
        // Range of code points with same-norm16-value algorithmic decompositions.
496
0
        // They might have different non-zero FCD16 values.
497
0
        uint16_t prevFCD16=ctx->impl.getFCD16(start);
498
0
        while(++start<=end) {
499
0
            uint16_t fcd16=ctx->impl.getFCD16(start);
500
0
            if(fcd16!=prevFCD16) {
501
0
                sa->add(sa->set, start);
502
0
                prevFCD16=fcd16;
503
0
            }
504
0
        }
505
0
    }
506
0
    return TRUE;
507
0
}
508
509
static UBool U_CALLCONV
510
0
enumPropertyStartsRange(const void *context, UChar32 start, UChar32 /*end*/, uint32_t /*value*/) {
511
0
    /* add the start code point to the USet */
512
0
    const USetAdder *sa=(const USetAdder *)context;
513
0
    sa->add(sa->set, start);
514
0
    return TRUE;
515
0
}
516
517
static uint32_t U_CALLCONV
518
0
segmentStarterMapper(const void * /*context*/, uint32_t value) {
519
0
    return value&CANON_NOT_SEGMENT_STARTER;
520
0
}
521
522
U_CDECL_END
523
524
void
525
0
Normalizer2Impl::addLcccChars(UnicodeSet &set) const {
526
0
    LcccContext context(*this, set);
527
0
    utrie2_enum(normTrie, NULL, enumLcccRange, &context);
528
0
}
529
530
void
531
0
Normalizer2Impl::addPropertyStarts(const USetAdder *sa, UErrorCode & /*errorCode*/) const {
532
0
    /* add the start code point of each same-value range of each trie */
533
0
    PropertyStartsContext context(*this, sa);
534
0
    utrie2_enum(normTrie, NULL, enumNorm16PropertyStartsRange, &context);
535
0
536
0
    /* add Hangul LV syllables and LV+1 because of skippables */
537
0
    for(UChar c=Hangul::HANGUL_BASE; c<Hangul::HANGUL_LIMIT; c+=Hangul::JAMO_T_COUNT) {
538
0
        sa->add(sa->set, c);
539
0
        sa->add(sa->set, c+1);
540
0
    }
541
0
    sa->add(sa->set, Hangul::HANGUL_LIMIT); /* add Hangul+1 to continue with other properties */
542
0
}
543
544
void
545
0
Normalizer2Impl::addCanonIterPropertyStarts(const USetAdder *sa, UErrorCode &errorCode) const {
546
0
    /* add the start code point of each same-value range of the canonical iterator data trie */
547
0
    if(ensureCanonIterData(errorCode)) {
548
0
        // currently only used for the SEGMENT_STARTER property
549
0
        utrie2_enum(fCanonIterData->trie, segmentStarterMapper, enumPropertyStartsRange, sa);
550
0
    }
551
0
}
552
553
const UChar *
554
Normalizer2Impl::copyLowPrefixFromNulTerminated(const UChar *src,
555
                                                UChar32 minNeedDataCP,
556
                                                ReorderingBuffer *buffer,
557
0
                                                UErrorCode &errorCode) const {
558
0
    // Make some effort to support NUL-terminated strings reasonably.
559
0
    // Take the part of the fast quick check loop that does not look up
560
0
    // data and check the first part of the string.
561
0
    // After this prefix, determine the string length to simplify the rest
562
0
    // of the code.
563
0
    const UChar *prevSrc=src;
564
0
    UChar c;
565
0
    while((c=*src++)<minNeedDataCP && c!=0) {}
566
0
    // Back out the last character for full processing.
567
0
    // Copy this prefix.
568
0
    if(--src!=prevSrc) {
569
0
        if(buffer!=NULL) {
570
0
            buffer->appendZeroCC(prevSrc, src, errorCode);
571
0
        }
572
0
    }
573
0
    return src;
574
0
}
575
576
UnicodeString &
577
Normalizer2Impl::decompose(const UnicodeString &src, UnicodeString &dest,
578
0
                           UErrorCode &errorCode) const {
579
0
    if(U_FAILURE(errorCode)) {
580
0
        dest.setToBogus();
581
0
        return dest;
582
0
    }
583
0
    const UChar *sArray=src.getBuffer();
584
0
    if(&dest==&src || sArray==NULL) {
585
0
        errorCode=U_ILLEGAL_ARGUMENT_ERROR;
586
0
        dest.setToBogus();
587
0
        return dest;
588
0
    }
589
0
    decompose(sArray, sArray+src.length(), dest, src.length(), errorCode);
590
0
    return dest;
591
0
}
592
593
void
594
Normalizer2Impl::decompose(const UChar *src, const UChar *limit,
595
                           UnicodeString &dest,
596
                           int32_t destLengthEstimate,
597
0
                           UErrorCode &errorCode) const {
598
0
    if(destLengthEstimate<0 && limit!=NULL) {
599
0
        destLengthEstimate=(int32_t)(limit-src);
600
0
    }
601
0
    dest.remove();
602
0
    ReorderingBuffer buffer(*this, dest);
603
0
    if(buffer.init(destLengthEstimate, errorCode)) {
604
0
        decompose(src, limit, &buffer, errorCode);
605
0
    }
606
0
}
607
608
// Dual functionality:
609
// buffer!=NULL: normalize
610
// buffer==NULL: isNormalized/spanQuickCheckYes
611
const UChar *
612
Normalizer2Impl::decompose(const UChar *src, const UChar *limit,
613
                           ReorderingBuffer *buffer,
614
0
                           UErrorCode &errorCode) const {
615
0
    UChar32 minNoCP=minDecompNoCP;
616
0
    if(limit==NULL) {
617
0
        src=copyLowPrefixFromNulTerminated(src, minNoCP, buffer, errorCode);
618
0
        if(U_FAILURE(errorCode)) {
619
0
            return src;
620
0
        }
621
0
        limit=u_strchr(src, 0);
622
0
    }
623
0
624
0
    const UChar *prevSrc;
625
0
    UChar32 c=0;
626
0
    uint16_t norm16=0;
627
0
628
0
    // only for quick check
629
0
    const UChar *prevBoundary=src;
630
0
    uint8_t prevCC=0;
631
0
632
0
    for(;;) {
633
0
        // count code units below the minimum or with irrelevant data for the quick check
634
0
        for(prevSrc=src; src!=limit;) {
635
0
            if( (c=*src)<minNoCP ||
636
0
                isMostDecompYesAndZeroCC(norm16=UTRIE2_GET16_FROM_U16_SINGLE_LEAD(normTrie, c))
637
0
            ) {
638
0
                ++src;
639
0
            } else if(!U16_IS_SURROGATE(c)) {
640
0
                break;
641
0
            } else {
642
0
                UChar c2;
643
0
                if(U16_IS_SURROGATE_LEAD(c)) {
644
0
                    if((src+1)!=limit && U16_IS_TRAIL(c2=src[1])) {
645
0
                        c=U16_GET_SUPPLEMENTARY(c, c2);
646
0
                    }
647
0
                } else /* trail surrogate */ {
648
0
                    if(prevSrc<src && U16_IS_LEAD(c2=*(src-1))) {
649
0
                        --src;
650
0
                        c=U16_GET_SUPPLEMENTARY(c2, c);
651
0
                    }
652
0
                }
653
0
                if(isMostDecompYesAndZeroCC(norm16=getNorm16(c))) {
654
0
                    src+=U16_LENGTH(c);
655
0
                } else {
656
0
                    break;
657
0
                }
658
0
            }
659
0
        }
660
0
        // copy these code units all at once
661
0
        if(src!=prevSrc) {
662
0
            if(buffer!=NULL) {
663
0
                if(!buffer->appendZeroCC(prevSrc, src, errorCode)) {
664
0
                    break;
665
0
                }
666
0
            } else {
667
0
                prevCC=0;
668
0
                prevBoundary=src;
669
0
            }
670
0
        }
671
0
        if(src==limit) {
672
0
            break;
673
0
        }
674
0
675
0
        // Check one above-minimum, relevant code point.
676
0
        src+=U16_LENGTH(c);
677
0
        if(buffer!=NULL) {
678
0
            if(!decompose(c, norm16, *buffer, errorCode)) {
679
0
                break;
680
0
            }
681
0
        } else {
682
0
            if(isDecompYes(norm16)) {
683
0
                uint8_t cc=getCCFromYesOrMaybe(norm16);
684
0
                if(prevCC<=cc || cc==0) {
685
0
                    prevCC=cc;
686
0
                    if(cc<=1) {
687
0
                        prevBoundary=src;
688
0
                    }
689
0
                    continue;
690
0
                }
691
0
            }
692
0
            return prevBoundary;  // "no" or cc out of order
693
0
        }
694
0
    }
695
0
    return src;
696
0
}
697
698
// Decompose a short piece of text which is likely to contain characters that
699
// fail the quick check loop and/or where the quick check loop's overhead
700
// is unlikely to be amortized.
701
// Called by the compose() and makeFCD() implementations.
702
const UChar *
703
Normalizer2Impl::decomposeShort(const UChar *src, const UChar *limit,
704
                                UBool stopAtCompBoundary, UBool onlyContiguous,
705
13.5k
                                ReorderingBuffer &buffer, UErrorCode &errorCode) const {
706
13.5k
    if (U_FAILURE(errorCode)) {
707
0
        return nullptr;
708
0
    }
709
20.4k
    while(src<limit) {
710
12.8k
        if (stopAtCompBoundary && *src < minCompNoMaybeCP) {
711
200
            return src;
712
200
        }
713
12.6k
        const UChar *prevSrc = src;
714
12.6k
        UChar32 c;
715
12.6k
        uint16_t norm16;
716
12.6k
        UTRIE2_U16_NEXT16(normTrie, src, limit, c, norm16);
717
12.6k
        if (stopAtCompBoundary && norm16HasCompBoundaryBefore(norm16)) {
718
5.74k
            return prevSrc;
719
5.74k
        }
720
6.89k
        if(!decompose(c, norm16, buffer, errorCode)) {
721
0
            return nullptr;
722
0
        }
723
6.89k
        if (stopAtCompBoundary && norm16HasCompBoundaryAfter(norm16, onlyContiguous)) {
724
0
            return src;
725
0
        }
726
6.89k
    }
727
13.5k
    return src;
728
13.5k
}
729
730
UBool Normalizer2Impl::decompose(UChar32 c, uint16_t norm16,
731
                                 ReorderingBuffer &buffer,
732
6.89k
                                 UErrorCode &errorCode) const {
733
6.89k
    // get the decomposition and the lead and trail cc's
734
6.89k
    if (norm16 >= limitNoNo) {
735
6.78k
        if (isMaybeOrNonZeroCC(norm16)) {
736
6.76k
            return buffer.append(c, getCCFromYesOrMaybe(norm16), errorCode);
737
6.76k
        }
738
18
        // Maps to an isCompYesAndZeroCC.
739
18
        c=mapAlgorithmic(c, norm16);
740
18
        norm16=getNorm16(c);
741
18
    }
742
6.89k
    if (norm16 < minYesNo) {
743
1
        // c does not decompose
744
1
        return buffer.append(c, 0, errorCode);
745
128
    } else if(isHangulLV(norm16) || isHangulLVT(norm16)) {
746
0
        // Hangul syllable: decompose algorithmically
747
0
        UChar jamos[3];
748
0
        return buffer.appendZeroCC(jamos, jamos+Hangul::decompose(c, jamos), errorCode);
749
0
    }
750
128
    // c decomposes, get everything from the variable-length extra data
751
128
    const uint16_t *mapping=getMapping(norm16);
752
128
    uint16_t firstUnit=*mapping;
753
128
    int32_t length=firstUnit&MAPPING_LENGTH_MASK;
754
128
    uint8_t leadCC, trailCC;
755
128
    trailCC=(uint8_t)(firstUnit>>8);
756
128
    if(firstUnit&MAPPING_HAS_CCC_LCCC_WORD) {
757
109
        leadCC=(uint8_t)(*(mapping-1)>>8);
758
109
    } else {
759
19
        leadCC=0;
760
19
    }
761
128
    return buffer.append((const UChar *)mapping+1, length, leadCC, trailCC, errorCode);
762
128
}
763
764
const uint8_t *
765
Normalizer2Impl::decomposeShort(const uint8_t *src, const uint8_t *limit,
766
                                UBool stopAtCompBoundary, UBool onlyContiguous,
767
0
                                ReorderingBuffer &buffer, UErrorCode &errorCode) const {
768
0
    if (U_FAILURE(errorCode)) {
769
0
        return nullptr;
770
0
    }
771
0
    while (src < limit) {
772
0
        const uint8_t *prevSrc = src;
773
0
        uint16_t norm16;
774
0
        UTRIE2_U8_NEXT16(normTrie, src, limit, norm16);
775
0
        // Get the decomposition and the lead and trail cc's.
776
0
        UChar32 c = U_SENTINEL;
777
0
        if (norm16 >= limitNoNo) {
778
0
            if (isMaybeOrNonZeroCC(norm16)) {
779
0
                // No boundaries around this character.
780
0
                c = codePointFromValidUTF8(prevSrc, src);
781
0
                if (!buffer.append(c, getCCFromYesOrMaybe(norm16), errorCode)) {
782
0
                    return nullptr;
783
0
                }
784
0
                continue;
785
0
            }
786
0
            // Maps to an isCompYesAndZeroCC.
787
0
            if (stopAtCompBoundary) {
788
0
                return prevSrc;
789
0
            }
790
0
            c = codePointFromValidUTF8(prevSrc, src);
791
0
            c = mapAlgorithmic(c, norm16);
792
0
            norm16 = getNorm16(c);
793
0
        } else if (stopAtCompBoundary && norm16 < minNoNoCompNoMaybeCC) {
794
0
            return prevSrc;
795
0
        }
796
0
        // norm16!=INERT guarantees that [prevSrc, src[ is valid UTF-8.
797
0
        // We do not see invalid UTF-8 here because
798
0
        // its norm16==INERT is normalization-inert,
799
0
        // so it gets copied unchanged in the fast path,
800
0
        // and we stop the slow path where invalid UTF-8 begins.
801
0
        U_ASSERT(norm16 != INERT);
802
0
        if (norm16 < minYesNo) {
803
0
            if (c < 0) {
804
0
                c = codePointFromValidUTF8(prevSrc, src);
805
0
            }
806
0
            // does not decompose
807
0
            if (!buffer.append(c, 0, errorCode)) {
808
0
                return nullptr;
809
0
            }
810
0
        } else if (isHangulLV(norm16) || isHangulLVT(norm16)) {
811
0
            // Hangul syllable: decompose algorithmically
812
0
            if (c < 0) {
813
0
                c = codePointFromValidUTF8(prevSrc, src);
814
0
            }
815
0
            char16_t jamos[3];
816
0
            if (!buffer.appendZeroCC(jamos, jamos+Hangul::decompose(c, jamos), errorCode)) {
817
0
                return nullptr;
818
0
            }
819
0
        } else {
820
0
            // The character decomposes, get everything from the variable-length extra data.
821
0
            const uint16_t *mapping = getMapping(norm16);
822
0
            uint16_t firstUnit = *mapping;
823
0
            int32_t length = firstUnit & MAPPING_LENGTH_MASK;
824
0
            uint8_t trailCC = (uint8_t)(firstUnit >> 8);
825
0
            uint8_t leadCC;
826
0
            if (firstUnit & MAPPING_HAS_CCC_LCCC_WORD) {
827
0
                leadCC = (uint8_t)(*(mapping-1) >> 8);
828
0
            } else {
829
0
                leadCC = 0;
830
0
            }
831
0
            if (!buffer.append((const char16_t *)mapping+1, length, leadCC, trailCC, errorCode)) {
832
0
                return nullptr;
833
0
            }
834
0
        }
835
0
        if (stopAtCompBoundary && norm16HasCompBoundaryAfter(norm16, onlyContiguous)) {
836
0
            return src;
837
0
        }
838
0
    }
839
0
    return src;
840
0
}
841
842
const UChar *
843
0
Normalizer2Impl::getDecomposition(UChar32 c, UChar buffer[4], int32_t &length) const {
844
0
    uint16_t norm16;
845
0
    if(c<minDecompNoCP || isMaybeOrNonZeroCC(norm16=getNorm16(c))) {
846
0
        // c does not decompose
847
0
        return nullptr;
848
0
    }
849
0
    const UChar *decomp = nullptr;
850
0
    if(isDecompNoAlgorithmic(norm16)) {
851
0
        // Maps to an isCompYesAndZeroCC.
852
0
        c=mapAlgorithmic(c, norm16);
853
0
        decomp=buffer;
854
0
        length=0;
855
0
        U16_APPEND_UNSAFE(buffer, length, c);
856
0
        // The mapping might decompose further.
857
0
        norm16 = getNorm16(c);
858
0
    }
859
0
    if (norm16 < minYesNo) {
860
0
        return decomp;
861
0
    } else if(isHangulLV(norm16) || isHangulLVT(norm16)) {
862
0
        // Hangul syllable: decompose algorithmically
863
0
        length=Hangul::decompose(c, buffer);
864
0
        return buffer;
865
0
    }
866
0
    // c decomposes, get everything from the variable-length extra data
867
0
    const uint16_t *mapping=getMapping(norm16);
868
0
    length=*mapping&MAPPING_LENGTH_MASK;
869
0
    return (const UChar *)mapping+1;
870
0
}
871
872
// The capacity of the buffer must be 30=MAPPING_LENGTH_MASK-1
873
// so that a raw mapping fits that consists of one unit ("rm0")
874
// plus all but the first two code units of the normal mapping.
875
// The maximum length of a normal mapping is 31=MAPPING_LENGTH_MASK.
876
const UChar *
877
0
Normalizer2Impl::getRawDecomposition(UChar32 c, UChar buffer[30], int32_t &length) const {
878
0
    uint16_t norm16;
879
0
    if(c<minDecompNoCP || isDecompYes(norm16=getNorm16(c))) {
880
0
        // c does not decompose
881
0
        return NULL;
882
0
    } else if(isHangulLV(norm16) || isHangulLVT(norm16)) {
883
0
        // Hangul syllable: decompose algorithmically
884
0
        Hangul::getRawDecomposition(c, buffer);
885
0
        length=2;
886
0
        return buffer;
887
0
    } else if(isDecompNoAlgorithmic(norm16)) {
888
0
        c=mapAlgorithmic(c, norm16);
889
0
        length=0;
890
0
        U16_APPEND_UNSAFE(buffer, length, c);
891
0
        return buffer;
892
0
    }
893
0
    // c decomposes, get everything from the variable-length extra data
894
0
    const uint16_t *mapping=getMapping(norm16);
895
0
    uint16_t firstUnit=*mapping;
896
0
    int32_t mLength=firstUnit&MAPPING_LENGTH_MASK;  // length of normal mapping
897
0
    if(firstUnit&MAPPING_HAS_RAW_MAPPING) {
898
0
        // Read the raw mapping from before the firstUnit and before the optional ccc/lccc word.
899
0
        // Bit 7=MAPPING_HAS_CCC_LCCC_WORD
900
0
        const uint16_t *rawMapping=mapping-((firstUnit>>7)&1)-1;
901
0
        uint16_t rm0=*rawMapping;
902
0
        if(rm0<=MAPPING_LENGTH_MASK) {
903
0
            length=rm0;
904
0
            return (const UChar *)rawMapping-rm0;
905
0
        } else {
906
0
            // Copy the normal mapping and replace its first two code units with rm0.
907
0
            buffer[0]=(UChar)rm0;
908
0
            u_memcpy(buffer+1, (const UChar *)mapping+1+2, mLength-2);
909
0
            length=mLength-1;
910
0
            return buffer;
911
0
        }
912
0
    } else {
913
0
        length=mLength;
914
0
        return (const UChar *)mapping+1;
915
0
    }
916
0
}
917
918
void Normalizer2Impl::decomposeAndAppend(const UChar *src, const UChar *limit,
919
                                         UBool doDecompose,
920
                                         UnicodeString &safeMiddle,
921
                                         ReorderingBuffer &buffer,
922
0
                                         UErrorCode &errorCode) const {
923
0
    buffer.copyReorderableSuffixTo(safeMiddle);
924
0
    if(doDecompose) {
925
0
        decompose(src, limit, &buffer, errorCode);
926
0
        return;
927
0
    }
928
0
    // Just merge the strings at the boundary.
929
0
    ForwardUTrie2StringIterator iter(normTrie, src, limit);
930
0
    uint8_t firstCC, prevCC, cc;
931
0
    firstCC=prevCC=cc=getCC(iter.next16());
932
0
    while(cc!=0) {
933
0
        prevCC=cc;
934
0
        cc=getCC(iter.next16());
935
0
    };
936
0
    if(limit==NULL) {  // appendZeroCC() needs limit!=NULL
937
0
        limit=u_strchr(iter.codePointStart, 0);
938
0
    }
939
0
940
0
    if (buffer.append(src, (int32_t)(iter.codePointStart-src), firstCC, prevCC, errorCode)) {
941
0
        buffer.appendZeroCC(iter.codePointStart, limit, errorCode);
942
0
    }
943
0
}
944
945
0
UBool Normalizer2Impl::hasDecompBoundaryBefore(UChar32 c) const {
946
0
    return c < minLcccCP || (c <= 0xffff && !singleLeadMightHaveNonZeroFCD16(c)) ||
947
0
        norm16HasDecompBoundaryBefore(getNorm16(c));
948
0
}
949
950
0
UBool Normalizer2Impl::norm16HasDecompBoundaryBefore(uint16_t norm16) const {
951
0
    if (norm16 < minNoNoCompNoMaybeCC) {
952
0
        return TRUE;
953
0
    }
954
0
    if (norm16 >= limitNoNo) {
955
0
        return norm16 <= MIN_NORMAL_MAYBE_YES || norm16 == JAMO_VT;
956
0
    }
957
0
    // c decomposes, get everything from the variable-length extra data
958
0
    const uint16_t *mapping=getMapping(norm16);
959
0
    uint16_t firstUnit=*mapping;
960
0
    // TRUE if leadCC==0 (hasFCDBoundaryBefore())
961
0
    return (firstUnit&MAPPING_HAS_CCC_LCCC_WORD)==0 || (*(mapping-1)&0xff00)==0;
962
0
}
963
964
0
UBool Normalizer2Impl::hasDecompBoundaryAfter(UChar32 c) const {
965
0
    if (c < minDecompNoCP) {
966
0
        return TRUE;
967
0
    }
968
0
    if (c <= 0xffff && !singleLeadMightHaveNonZeroFCD16(c)) {
969
0
        return TRUE;
970
0
    }
971
0
    return norm16HasDecompBoundaryAfter(getNorm16(c));
972
0
}
973
974
0
UBool Normalizer2Impl::norm16HasDecompBoundaryAfter(uint16_t norm16) const {
975
0
    if(norm16 <= minYesNo || isHangulLVT(norm16)) {
976
0
        return TRUE;
977
0
    }
978
0
    if (norm16 >= limitNoNo) {
979
0
        if (isMaybeOrNonZeroCC(norm16)) {
980
0
            return norm16 <= MIN_NORMAL_MAYBE_YES || norm16 == JAMO_VT;
981
0
        }
982
0
        // Maps to an isCompYesAndZeroCC.
983
0
        return (norm16 & DELTA_TCCC_MASK) <= DELTA_TCCC_1;
984
0
    }
985
0
    // c decomposes, get everything from the variable-length extra data
986
0
    const uint16_t *mapping=getMapping(norm16);
987
0
    uint16_t firstUnit=*mapping;
988
0
    // decomp after-boundary: same as hasFCDBoundaryAfter(),
989
0
    // fcd16<=1 || trailCC==0
990
0
    if(firstUnit>0x1ff) {
991
0
        return FALSE;  // trailCC>1
992
0
    }
993
0
    if(firstUnit<=0xff) {
994
0
        return TRUE;  // trailCC==0
995
0
    }
996
0
    // if(trailCC==1) test leadCC==0, same as checking for before-boundary
997
0
    // TRUE if leadCC==0 (hasFCDBoundaryBefore())
998
0
    return (firstUnit&MAPPING_HAS_CCC_LCCC_WORD)==0 || (*(mapping-1)&0xff00)==0;
999
0
}
1000
1001
/*
1002
 * Finds the recomposition result for
1003
 * a forward-combining "lead" character,
1004
 * specified with a pointer to its compositions list,
1005
 * and a backward-combining "trail" character.
1006
 *
1007
 * If the lead and trail characters combine, then this function returns
1008
 * the following "compositeAndFwd" value:
1009
 * Bits 21..1  composite character
1010
 * Bit      0  set if the composite is a forward-combining starter
1011
 * otherwise it returns -1.
1012
 *
1013
 * The compositions list has (trail, compositeAndFwd) pair entries,
1014
 * encoded as either pairs or triples of 16-bit units.
1015
 * The last entry has the high bit of its first unit set.
1016
 *
1017
 * The list is sorted by ascending trail characters (there are no duplicates).
1018
 * A linear search is used.
1019
 *
1020
 * See normalizer2impl.h for a more detailed description
1021
 * of the compositions list format.
1022
 */
1023
18
int32_t Normalizer2Impl::combine(const uint16_t *list, UChar32 trail) {
1024
18
    uint16_t key1, firstUnit;
1025
18
    if(trail<COMP_1_TRAIL_LIMIT) {
1026
18
        // trail character is 0..33FF
1027
18
        // result entry may have 2 or 3 units
1028
18
        key1=(uint16_t)(trail<<1);
1029
36
        while(key1>(firstUnit=*list)) {
1030
18
            list+=2+(firstUnit&COMP_1_TRIPLE);
1031
18
        }
1032
18
        if(key1==(firstUnit&COMP_1_TRAIL_MASK)) {
1033
18
            if(firstUnit&COMP_1_TRIPLE) {
1034
0
                return ((int32_t)list[1]<<16)|list[2];
1035
18
            } else {
1036
18
                return list[1];
1037
18
            }
1038
0
        }
1039
0
    } else {
1040
0
        // trail character is 3400..10FFFF
1041
0
        // result entry has 3 units
1042
0
        key1=(uint16_t)(COMP_1_TRAIL_LIMIT+
1043
0
                        (((trail>>COMP_1_TRAIL_SHIFT))&
1044
0
                          ~COMP_1_TRIPLE));
1045
0
        uint16_t key2=(uint16_t)(trail<<COMP_2_TRAIL_SHIFT);
1046
0
        uint16_t secondUnit;
1047
0
        for(;;) {
1048
0
            if(key1>(firstUnit=*list)) {
1049
0
                list+=2+(firstUnit&COMP_1_TRIPLE);
1050
0
            } else if(key1==(firstUnit&COMP_1_TRAIL_MASK)) {
1051
0
                if(key2>(secondUnit=list[1])) {
1052
0
                    if(firstUnit&COMP_1_LAST_TUPLE) {
1053
0
                        break;
1054
0
                    } else {
1055
0
                        list+=3;
1056
0
                    }
1057
0
                } else if(key2==(secondUnit&COMP_2_TRAIL_MASK)) {
1058
0
                    return ((int32_t)(secondUnit&~COMP_2_TRAIL_MASK)<<16)|list[2];
1059
0
                } else {
1060
0
                    break;
1061
0
                }
1062
0
            } else {
1063
0
                break;
1064
0
            }
1065
0
        }
1066
0
    }
1067
18
    return -1;
1068
18
}
1069
1070
/**
1071
  * @param list some character's compositions list
1072
  * @param set recursively receives the composites from these compositions
1073
  */
1074
0
void Normalizer2Impl::addComposites(const uint16_t *list, UnicodeSet &set) const {
1075
0
    uint16_t firstUnit;
1076
0
    int32_t compositeAndFwd;
1077
0
    do {
1078
0
        firstUnit=*list;
1079
0
        if((firstUnit&COMP_1_TRIPLE)==0) {
1080
0
            compositeAndFwd=list[1];
1081
0
            list+=2;
1082
0
        } else {
1083
0
            compositeAndFwd=(((int32_t)list[1]&~COMP_2_TRAIL_MASK)<<16)|list[2];
1084
0
            list+=3;
1085
0
        }
1086
0
        UChar32 composite=compositeAndFwd>>1;
1087
0
        if((compositeAndFwd&1)!=0) {
1088
0
            addComposites(getCompositionsListForComposite(getNorm16(composite)), set);
1089
0
        }
1090
0
        set.add(composite);
1091
0
    } while((firstUnit&COMP_1_LAST_TUPLE)==0);
1092
0
}
1093
1094
/*
1095
 * Recomposes the buffer text starting at recomposeStartIndex
1096
 * (which is in NFD - decomposed and canonically ordered),
1097
 * and truncates the buffer contents.
1098
 *
1099
 * Note that recomposition never lengthens the text:
1100
 * Any character consists of either one or two code units;
1101
 * a composition may contain at most one more code unit than the original starter,
1102
 * while the combining mark that is removed has at least one code unit.
1103
 */
1104
void Normalizer2Impl::recompose(ReorderingBuffer &buffer, int32_t recomposeStartIndex,
1105
6.78k
                                UBool onlyContiguous) const {
1106
6.78k
    UChar *p=buffer.getStart()+recomposeStartIndex;
1107
6.78k
    UChar *limit=buffer.getLimit();
1108
6.78k
    if(p==limit) {
1109
0
        return;
1110
0
    }
1111
6.78k
1112
6.78k
    UChar *starter, *pRemove, *q, *r;
1113
6.78k
    const uint16_t *compositionsList;
1114
6.78k
    UChar32 c, compositeAndFwd;
1115
6.78k
    uint16_t norm16;
1116
6.78k
    uint8_t cc, prevCC;
1117
6.78k
    UBool starterIsSupplementary;
1118
6.78k
1119
6.78k
    // Some of the following variables are not used until we have a forward-combining starter
1120
6.78k
    // and are only initialized now to avoid compiler warnings.
1121
6.78k
    compositionsList=NULL;  // used as indicator for whether we have a forward-combining starter
1122
6.78k
    starter=NULL;
1123
6.78k
    starterIsSupplementary=FALSE;
1124
6.78k
    prevCC=0;
1125
6.78k
1126
6.80k
    for(;;) {
1127
6.80k
        UTRIE2_U16_NEXT16(normTrie, p, limit, c, norm16);
1128
6.80k
        cc=getCCFromYesOrMaybe(norm16);
1129
6.80k
        if( // this character combines backward and
1130
6.80k
            isMaybe(norm16) &&
1131
6.80k
            // we have seen a starter that combines forward and
1132
6.80k
            compositionsList!=NULL &&
1133
6.80k
            // the backward-combining character is not blocked
1134
6.80k
            (prevCC<cc || prevCC==0)
1135
18
        ) {
1136
18
            if(isJamoVT(norm16)) {
1137
0
                // c is a Jamo V/T, see if we can compose it with the previous character.
1138
0
                if(c<Hangul::JAMO_T_BASE) {
1139
0
                    // c is a Jamo Vowel, compose with previous Jamo L and following Jamo T.
1140
0
                    UChar prev=(UChar)(*starter-Hangul::JAMO_L_BASE);
1141
0
                    if(prev<Hangul::JAMO_L_COUNT) {
1142
0
                        pRemove=p-1;
1143
0
                        UChar syllable=(UChar)
1144
0
                            (Hangul::HANGUL_BASE+
1145
0
                             (prev*Hangul::JAMO_V_COUNT+(c-Hangul::JAMO_V_BASE))*
1146
0
                             Hangul::JAMO_T_COUNT);
1147
0
                        UChar t;
1148
0
                        if(p!=limit && (t=(UChar)(*p-Hangul::JAMO_T_BASE))<Hangul::JAMO_T_COUNT) {
1149
0
                            ++p;
1150
0
                            syllable+=t;  // The next character was a Jamo T.
1151
0
                        }
1152
0
                        *starter=syllable;
1153
0
                        // remove the Jamo V/T
1154
0
                        q=pRemove;
1155
0
                        r=p;
1156
0
                        while(r<limit) {
1157
0
                            *q++=*r++;
1158
0
                        }
1159
0
                        limit=q;
1160
0
                        p=pRemove;
1161
0
                    }
1162
0
                }
1163
0
                /*
1164
0
                 * No "else" for Jamo T:
1165
0
                 * Since the input is in NFD, there are no Hangul LV syllables that
1166
0
                 * a Jamo T could combine with.
1167
0
                 * All Jamo Ts are combined above when handling Jamo Vs.
1168
0
                 */
1169
0
                if(p==limit) {
1170
0
                    break;
1171
0
                }
1172
0
                compositionsList=NULL;
1173
0
                continue;
1174
18
            } else if((compositeAndFwd=combine(compositionsList, c))>=0) {
1175
18
                // The starter and the combining mark (c) do combine.
1176
18
                UChar32 composite=compositeAndFwd>>1;
1177
18
1178
18
                // Replace the starter with the composite, remove the combining mark.
1179
18
                pRemove=p-U16_LENGTH(c);  // pRemove & p: start & limit of the combining mark
1180
18
                if(starterIsSupplementary) {
1181
0
                    if(U_IS_SUPPLEMENTARY(composite)) {
1182
0
                        // both are supplementary
1183
0
                        starter[0]=U16_LEAD(composite);
1184
0
                        starter[1]=U16_TRAIL(composite);
1185
0
                    } else {
1186
0
                        *starter=(UChar)composite;
1187
0
                        // The composite is shorter than the starter,
1188
0
                        // move the intermediate characters forward one.
1189
0
                        starterIsSupplementary=FALSE;
1190
0
                        q=starter+1;
1191
0
                        r=q+1;
1192
0
                        while(r<pRemove) {
1193
0
                            *q++=*r++;
1194
0
                        }
1195
0
                        --pRemove;
1196
0
                    }
1197
18
                } else if(U_IS_SUPPLEMENTARY(composite)) {
1198
0
                    // The composite is longer than the starter,
1199
0
                    // move the intermediate characters back one.
1200
0
                    starterIsSupplementary=TRUE;
1201
0
                    ++starter;  // temporarily increment for the loop boundary
1202
0
                    q=pRemove;
1203
0
                    r=++pRemove;
1204
0
                    while(starter<q) {
1205
0
                        *--r=*--q;
1206
0
                    }
1207
0
                    *starter=U16_TRAIL(composite);
1208
0
                    *--starter=U16_LEAD(composite);  // undo the temporary increment
1209
18
                } else {
1210
18
                    // both are on the BMP
1211
18
                    *starter=(UChar)composite;
1212
18
                }
1213
18
1214
18
                /* remove the combining mark by moving the following text over it */
1215
18
                if(pRemove<p) {
1216
18
                    q=pRemove;
1217
18
                    r=p;
1218
18
                    while(r<limit) {
1219
0
                        *q++=*r++;
1220
0
                    }
1221
18
                    limit=q;
1222
18
                    p=pRemove;
1223
18
                }
1224
18
                // Keep prevCC because we removed the combining mark.
1225
18
1226
18
                if(p==limit) {
1227
18
                    break;
1228
18
                }
1229
0
                // Is the composite a starter that combines forward?
1230
0
                if(compositeAndFwd&1) {
1231
0
                    compositionsList=
1232
0
                        getCompositionsListForComposite(getNorm16(composite));
1233
0
                } else {
1234
0
                    compositionsList=NULL;
1235
0
                }
1236
0
1237
0
                // We combined; continue with looking for compositions.
1238
0
                continue;
1239
0
            }
1240
18
        }
1241
6.78k
1242
6.78k
        // no combination this time
1243
6.78k
        prevCC=cc;
1244
6.78k
        if(p==limit) {
1245
6.76k
            break;
1246
6.76k
        }
1247
19
1248
19
        // If c did not combine, then check if it is a starter.
1249
19
        if(cc==0) {
1250
19
            // Found a new starter.
1251
19
            if((compositionsList=getCompositionsListForDecompYes(norm16))!=NULL) {
1252
18
                // It may combine with something, prepare for it.
1253
18
                if(U_IS_BMP(c)) {
1254
18
                    starterIsSupplementary=FALSE;
1255
18
                    starter=p-1;
1256
18
                } else {
1257
0
                    starterIsSupplementary=TRUE;
1258
0
                    starter=p-2;
1259
0
                }
1260
18
            }
1261
19
        } else if(onlyContiguous) {
1262
0
            // FCC: no discontiguous compositions; any intervening character blocks.
1263
0
            compositionsList=NULL;
1264
0
        }
1265
19
    }
1266
6.78k
    buffer.setReorderingLimit(limit);
1267
6.78k
}
1268
1269
UChar32
1270
0
Normalizer2Impl::composePair(UChar32 a, UChar32 b) const {
1271
0
    uint16_t norm16=getNorm16(a);  // maps an out-of-range 'a' to inert norm16=0
1272
0
    const uint16_t *list;
1273
0
    if(isInert(norm16)) {
1274
0
        return U_SENTINEL;
1275
0
    } else if(norm16<minYesNoMappingsOnly) {
1276
0
        // a combines forward.
1277
0
        if(isJamoL(norm16)) {
1278
0
            b-=Hangul::JAMO_V_BASE;
1279
0
            if(0<=b && b<Hangul::JAMO_V_COUNT) {
1280
0
                return
1281
0
                    (Hangul::HANGUL_BASE+
1282
0
                     ((a-Hangul::JAMO_L_BASE)*Hangul::JAMO_V_COUNT+b)*
1283
0
                     Hangul::JAMO_T_COUNT);
1284
0
            } else {
1285
0
                return U_SENTINEL;
1286
0
            }
1287
0
        } else if(isHangulLV(norm16)) {
1288
0
            b-=Hangul::JAMO_T_BASE;
1289
0
            if(0<b && b<Hangul::JAMO_T_COUNT) {  // not b==0!
1290
0
                return a+b;
1291
0
            } else {
1292
0
                return U_SENTINEL;
1293
0
            }
1294
0
        } else {
1295
0
            // 'a' has a compositions list in extraData
1296
0
            list=getMapping(norm16);
1297
0
            if(norm16>minYesNo) {  // composite 'a' has both mapping & compositions list
1298
0
                list+=  // mapping pointer
1299
0
                    1+  // +1 to skip the first unit with the mapping length
1300
0
                    (*list&MAPPING_LENGTH_MASK);  // + mapping length
1301
0
            }
1302
0
        }
1303
0
    } else if(norm16<minMaybeYes || MIN_NORMAL_MAYBE_YES<=norm16) {
1304
0
        return U_SENTINEL;
1305
0
    } else {
1306
0
        list=getCompositionsListForMaybe(norm16);
1307
0
    }
1308
0
    if(b<0 || 0x10ffff<b) {  // combine(list, b) requires a valid code point b
1309
0
        return U_SENTINEL;
1310
0
    }
1311
0
#if U_SIGNED_RIGHT_SHIFT_IS_ARITHMETIC
1312
0
    return combine(list, b)>>1;
1313
#else
1314
    int32_t compositeAndFwd=combine(list, b);
1315
    return compositeAndFwd>=0 ? compositeAndFwd>>1 : U_SENTINEL;
1316
#endif
1317
}
1318
1319
// Very similar to composeQuickCheck(): Make the same changes in both places if relevant.
1320
// doCompose: normalize
1321
// !doCompose: isNormalized (buffer must be empty and initialized)
1322
UBool
1323
Normalizer2Impl::compose(const UChar *src, const UChar *limit,
1324
                         UBool onlyContiguous,
1325
                         UBool doCompose,
1326
                         ReorderingBuffer &buffer,
1327
92.4k
                         UErrorCode &errorCode) const {
1328
92.4k
    const UChar *prevBoundary=src;
1329
92.4k
    UChar32 minNoMaybeCP=minCompNoMaybeCP;
1330
92.4k
    if(limit==NULL) {
1331
0
        src=copyLowPrefixFromNulTerminated(src, minNoMaybeCP,
1332
0
                                           doCompose ? &buffer : NULL,
1333
0
                                           errorCode);
1334
0
        if(U_FAILURE(errorCode)) {
1335
0
            return FALSE;
1336
0
        }
1337
0
        limit=u_strchr(src, 0);
1338
0
        if (prevBoundary != src) {
1339
0
            if (hasCompBoundaryAfter(*(src-1), onlyContiguous)) {
1340
0
                prevBoundary = src;
1341
0
            } else {
1342
0
                buffer.removeSuffix(1);
1343
0
                prevBoundary = --src;
1344
0
            }
1345
0
        }
1346
0
    }
1347
92.4k
1348
233k
    for (;;) {
1349
233k
        // Fast path: Scan over a sequence of characters below the minimum "no or maybe" code point,
1350
233k
        // or with (compYes && ccc==0) properties.
1351
233k
        const UChar *prevSrc;
1352
233k
        UChar32 c = 0;
1353
233k
        uint16_t norm16 = 0;
1354
1.12M
        for (;;) {
1355
1.12M
            if (src == limit) {
1356
92.4k
                if (prevBoundary != limit && doCompose) {
1357
76.0k
                    buffer.appendZeroCC(prevBoundary, limit, errorCode);
1358
76.0k
                }
1359
92.4k
                return TRUE;
1360
92.4k
            }
1361
1.03M
            if( (c=*src)<minNoMaybeCP ||
1362
1.03M
                isCompYesAndZeroCC(norm16=UTRIE2_GET16_FROM_U16_SINGLE_LEAD(normTrie, c))
1363
889k
            ) {
1364
889k
                ++src;
1365
889k
            } else {
1366
141k
                prevSrc = src++;
1367
141k
                if(!U16_IS_SURROGATE(c)) {
1368
141k
                    break;
1369
141k
                } else {
1370
34
                    UChar c2;
1371
34
                    if(U16_IS_SURROGATE_LEAD(c)) {
1372
34
                        if(src!=limit && U16_IS_TRAIL(c2=*src)) {
1373
34
                            ++src;
1374
34
                            c=U16_GET_SUPPLEMENTARY(c, c2);
1375
34
                        }
1376
34
                    } else /* trail surrogate */ {
1377
0
                        if(prevBoundary<prevSrc && U16_IS_LEAD(c2=*(prevSrc-1))) {
1378
0
                            --prevSrc;
1379
0
                            c=U16_GET_SUPPLEMENTARY(c2, c);
1380
0
                        }
1381
0
                    }
1382
34
                    if(!isCompYesAndZeroCC(norm16=getNorm16(c))) {
1383
0
                        break;
1384
0
                    }
1385
34
                }
1386
141k
            }
1387
1.03M
        }
1388
233k
        // isCompYesAndZeroCC(norm16) is false, that is, norm16>=minNoNo.
1389
233k
        // The current character is either a "noNo" (has a mapping)
1390
233k
        // or a "maybeYes" (combines backward)
1391
233k
        // or a "yesYes" with ccc!=0.
1392
233k
        // It is not a Hangul syllable or Jamo L because those have "yes" properties.
1393
233k
1394
233k
        // Medium-fast path: Handle cases that do not require full decomposition and recomposition.
1395
233k
        if (!isMaybeOrNonZeroCC(norm16)) {  // minNoNo <= norm16 < minMaybeYes
1396
134k
            if (!doCompose) {
1397
0
                return FALSE;
1398
0
            }
1399
134k
            // Fast path for mapping a character that is immediately surrounded by boundaries.
1400
134k
            // In this case, we need not decompose around the current character.
1401
134k
            if (isDecompNoAlgorithmic(norm16)) {
1402
36.2k
                // Maps to a single isCompYesAndZeroCC character
1403
36.2k
                // which also implies hasCompBoundaryBefore.
1404
36.2k
                if (norm16HasCompBoundaryAfter(norm16, onlyContiguous) ||
1405
36.2k
                        hasCompBoundaryBefore(src, limit)) {
1406
36.2k
                    if (prevBoundary != prevSrc && !buffer.appendZeroCC(prevBoundary, prevSrc, errorCode)) {
1407
0
                        break;
1408
0
                    }
1409
36.2k
                    if(!buffer.append(mapAlgorithmic(c, norm16), 0, errorCode)) {
1410
0
                        break;
1411
0
                    }
1412
36.2k
                    prevBoundary = src;
1413
36.2k
                    continue;
1414
36.2k
                }
1415
98.2k
            } else if (norm16 < minNoNoCompBoundaryBefore) {
1416
96.9k
                // The mapping is comp-normalized which also implies hasCompBoundaryBefore.
1417
96.9k
                if (norm16HasCompBoundaryAfter(norm16, onlyContiguous) ||
1418
96.9k
                        hasCompBoundaryBefore(src, limit)) {
1419
96.9k
                    if (prevBoundary != prevSrc && !buffer.appendZeroCC(prevBoundary, prevSrc, errorCode)) {
1420
0
                        break;
1421
0
                    }
1422
96.9k
                    const UChar *mapping = reinterpret_cast<const UChar *>(getMapping(norm16));
1423
96.9k
                    int32_t length = *mapping++ & MAPPING_LENGTH_MASK;
1424
96.9k
                    if(!buffer.appendZeroCC(mapping, mapping + length, errorCode)) {
1425
0
                        break;
1426
0
                    }
1427
96.9k
                    prevBoundary = src;
1428
96.9k
                    continue;
1429
96.9k
                }
1430
1.34k
            } else if (norm16 >= minNoNoEmpty) {
1431
1.34k
                // The current character maps to nothing.
1432
1.34k
                // Simply omit it from the output if there is a boundary before _or_ after it.
1433
1.34k
                // The character itself implies no boundaries.
1434
1.34k
                if (hasCompBoundaryBefore(src, limit) ||
1435
1.34k
                        hasCompBoundaryAfter(prevBoundary, prevSrc, onlyContiguous)) {
1436
1.34k
                    if (prevBoundary != prevSrc && !buffer.appendZeroCC(prevBoundary, prevSrc, errorCode)) {
1437
0
                        break;
1438
0
                    }
1439
1.34k
                    prevBoundary = src;
1440
1.34k
                    continue;
1441
1.34k
                }
1442
1.34k
            }
1443
6.76k
            // Other "noNo" type, or need to examine more text around this character:
1444
6.76k
            // Fall through to the slow path.
1445
6.76k
        } else if (isJamoVT(norm16) && prevBoundary != prevSrc) {
1446
0
            UChar prev=*(prevSrc-1);
1447
0
            if(c<Hangul::JAMO_T_BASE) {
1448
0
                // The current character is a Jamo Vowel,
1449
0
                // compose with previous Jamo L and following Jamo T.
1450
0
                UChar l = (UChar)(prev-Hangul::JAMO_L_BASE);
1451
0
                if(l<Hangul::JAMO_L_COUNT) {
1452
0
                    if (!doCompose) {
1453
0
                        return FALSE;
1454
0
                    }
1455
0
                    int32_t t;
1456
0
                    if (src != limit &&
1457
0
                            0 < (t = ((int32_t)*src - Hangul::JAMO_T_BASE)) &&
1458
0
                            t < Hangul::JAMO_T_COUNT) {
1459
0
                        // The next character is a Jamo T.
1460
0
                        ++src;
1461
0
                    } else if (hasCompBoundaryBefore(src, limit)) {
1462
0
                        // No Jamo T follows, not even via decomposition.
1463
0
                        t = 0;
1464
0
                    } else {
1465
0
                        t = -1;
1466
0
                    }
1467
0
                    if (t >= 0) {
1468
0
                        UChar32 syllable = Hangul::HANGUL_BASE +
1469
0
                            (l*Hangul::JAMO_V_COUNT + (c-Hangul::JAMO_V_BASE)) *
1470
0
                            Hangul::JAMO_T_COUNT + t;
1471
0
                        --prevSrc;  // Replace the Jamo L as well.
1472
0
                        if (prevBoundary != prevSrc && !buffer.appendZeroCC(prevBoundary, prevSrc, errorCode)) {
1473
0
                            break;
1474
0
                        }
1475
0
                        if(!buffer.appendBMP((UChar)syllable, 0, errorCode)) {
1476
0
                            break;
1477
0
                        }
1478
0
                        prevBoundary = src;
1479
0
                        continue;
1480
0
                    }
1481
0
                    // If we see L+V+x where x!=T then we drop to the slow path,
1482
0
                    // decompose and recompose.
1483
0
                    // This is to deal with NFKC finding normal L and V but a
1484
0
                    // compatibility variant of a T.
1485
0
                    // We need to either fully compose that combination here
1486
0
                    // (which would complicate the code and may not work with strange custom data)
1487
0
                    // or use the slow path.
1488
0
                }
1489
0
            } else if (Hangul::isHangulLV(prev)) {
1490
0
                // The current character is a Jamo Trailing consonant,
1491
0
                // compose with previous Hangul LV that does not contain a Jamo T.
1492
0
                if (!doCompose) {
1493
0
                    return FALSE;
1494
0
                }
1495
0
                UChar32 syllable = prev + c - Hangul::JAMO_T_BASE;
1496
0
                --prevSrc;  // Replace the Hangul LV as well.
1497
0
                if (prevBoundary != prevSrc && !buffer.appendZeroCC(prevBoundary, prevSrc, errorCode)) {
1498
0
                    break;
1499
0
                }
1500
0
                if(!buffer.appendBMP((UChar)syllable, 0, errorCode)) {
1501
0
                    break;
1502
0
                }
1503
0
                prevBoundary = src;
1504
0
                continue;
1505
0
            }
1506
6.76k
            // No matching context, or may need to decompose surrounding text first:
1507
6.76k
            // Fall through to the slow path.
1508
6.76k
        } else if (norm16 > JAMO_VT) {  // norm16 >= MIN_YES_YES_WITH_CC
1509
1
            // One or more combining marks that do not combine-back:
1510
1
            // Check for canonical order, copy unchanged if ok and
1511
1
            // if followed by a character with a boundary-before.
1512
1
            uint8_t cc = getCCFromNormalYesOrMaybe(norm16);  // cc!=0
1513
1
            if (onlyContiguous /* FCC */ && getPreviousTrailCC(prevBoundary, prevSrc) > cc) {
1514
0
                // Fails FCD test, need to decompose and contiguously recompose.
1515
0
                if (!doCompose) {
1516
0
                    return FALSE;
1517
0
                }
1518
1
            } else {
1519
1
                // If !onlyContiguous (not FCC), then we ignore the tccc of
1520
1
                // the previous character which passed the quick check "yes && ccc==0" test.
1521
1
                const UChar *nextSrc;
1522
1
                uint16_t n16;
1523
1
                for (;;) {
1524
1
                    if (src == limit) {
1525
1
                        if (doCompose) {
1526
1
                            buffer.appendZeroCC(prevBoundary, limit, errorCode);
1527
1
                        }
1528
1
                        return TRUE;
1529
1
                    }
1530
0
                    uint8_t prevCC = cc;
1531
0
                    nextSrc = src;
1532
0
                    UTRIE2_U16_NEXT16(normTrie, nextSrc, limit, c, n16);
1533
0
                    if (n16 >= MIN_YES_YES_WITH_CC) {
1534
0
                        cc = getCCFromNormalYesOrMaybe(n16);
1535
0
                        if (prevCC > cc) {
1536
0
                            if (!doCompose) {
1537
0
                                return FALSE;
1538
0
                            }
1539
0
                            break;
1540
0
                        }
1541
0
                    } else {
1542
0
                        break;
1543
0
                    }
1544
0
                    src = nextSrc;
1545
0
                }
1546
1
                // src is after the last in-order combining mark.
1547
1
                // If there is a boundary here, then we continue with no change.
1548
1
                if (norm16HasCompBoundaryBefore(n16)) {
1549
0
                    if (isCompYesAndZeroCC(n16)) {
1550
0
                        src = nextSrc;
1551
0
                    }
1552
0
                    continue;
1553
0
                }
1554
6.78k
                // Use the slow path. There is no boundary in [prevSrc, src[.
1555
6.78k
            }
1556
1
        }
1557
6.78k
1558
6.78k
        // Slow path: Find the nearest boundaries around the current character,
1559
6.78k
        // decompose and recompose.
1560
6.78k
        if (prevBoundary != prevSrc && !norm16HasCompBoundaryBefore(norm16)) {
1561
6.12k
            const UChar *p = prevSrc;
1562
6.12k
            UTRIE2_U16_PREV16(normTrie, prevBoundary, p, c, norm16);
1563
6.12k
            if (!norm16HasCompBoundaryAfter(norm16, onlyContiguous)) {
1564
1
                prevSrc = p;
1565
1
            }
1566
6.12k
        }
1567
6.78k
        if (doCompose && prevBoundary != prevSrc && !buffer.appendZeroCC(prevBoundary, prevSrc, errorCode)) {
1568
0
            break;
1569
0
        }
1570
6.78k
        int32_t recomposeStartIndex=buffer.length();
1571
6.78k
        // We know there is not a boundary here.
1572
6.78k
        decomposeShort(prevSrc, src, FALSE /* !stopAtCompBoundary */, onlyContiguous,
1573
6.78k
                       buffer, errorCode);
1574
6.78k
        // Decompose until the next boundary.
1575
6.78k
        src = decomposeShort(src, limit, TRUE /* stopAtCompBoundary */, onlyContiguous,
1576
6.78k
                             buffer, errorCode);
1577
6.78k
        if (U_FAILURE(errorCode)) {
1578
0
            break;
1579
0
        }
1580
6.78k
        if ((src - prevSrc) > INT32_MAX) {  // guard before buffer.equals()
1581
0
            errorCode = U_INDEX_OUTOFBOUNDS_ERROR;
1582
0
            return TRUE;
1583
0
        }
1584
6.78k
        recompose(buffer, recomposeStartIndex, onlyContiguous);
1585
6.78k
        if(!doCompose) {
1586
0
            if(!buffer.equals(prevSrc, src)) {
1587
0
                return FALSE;
1588
0
            }
1589
0
            buffer.remove();
1590
0
        }
1591
6.78k
        prevBoundary=src;
1592
6.78k
    }
1593
92.4k
    return TRUE;
1594
92.4k
}
1595
1596
// Very similar to compose(): Make the same changes in both places if relevant.
1597
// pQCResult==NULL: spanQuickCheckYes
1598
// pQCResult!=NULL: quickCheck (*pQCResult must be UNORM_YES)
1599
const UChar *
1600
Normalizer2Impl::composeQuickCheck(const UChar *src, const UChar *limit,
1601
                                   UBool onlyContiguous,
1602
0
                                   UNormalizationCheckResult *pQCResult) const {
1603
0
    const UChar *prevBoundary=src;
1604
0
    UChar32 minNoMaybeCP=minCompNoMaybeCP;
1605
0
    if(limit==NULL) {
1606
0
        UErrorCode errorCode=U_ZERO_ERROR;
1607
0
        src=copyLowPrefixFromNulTerminated(src, minNoMaybeCP, NULL, errorCode);
1608
0
        limit=u_strchr(src, 0);
1609
0
        if (prevBoundary != src) {
1610
0
            if (hasCompBoundaryAfter(*(src-1), onlyContiguous)) {
1611
0
                prevBoundary = src;
1612
0
            } else {
1613
0
                prevBoundary = --src;
1614
0
            }
1615
0
        }
1616
0
    }
1617
0
1618
0
    for(;;) {
1619
0
        // Fast path: Scan over a sequence of characters below the minimum "no or maybe" code point,
1620
0
        // or with (compYes && ccc==0) properties.
1621
0
        const UChar *prevSrc;
1622
0
        UChar32 c = 0;
1623
0
        uint16_t norm16 = 0;
1624
0
        for (;;) {
1625
0
            if(src==limit) {
1626
0
                return src;
1627
0
            }
1628
0
            if( (c=*src)<minNoMaybeCP ||
1629
0
                isCompYesAndZeroCC(norm16=UTRIE2_GET16_FROM_U16_SINGLE_LEAD(normTrie, c))
1630
0
            ) {
1631
0
                ++src;
1632
0
            } else {
1633
0
                prevSrc = src++;
1634
0
                if(!U16_IS_SURROGATE(c)) {
1635
0
                    break;
1636
0
                } else {
1637
0
                    UChar c2;
1638
0
                    if(U16_IS_SURROGATE_LEAD(c)) {
1639
0
                        if(src!=limit && U16_IS_TRAIL(c2=*src)) {
1640
0
                            ++src;
1641
0
                            c=U16_GET_SUPPLEMENTARY(c, c2);
1642
0
                        }
1643
0
                    } else /* trail surrogate */ {
1644
0
                        if(prevBoundary<prevSrc && U16_IS_LEAD(c2=*(prevSrc-1))) {
1645
0
                            --prevSrc;
1646
0
                            c=U16_GET_SUPPLEMENTARY(c2, c);
1647
0
                        }
1648
0
                    }
1649
0
                    if(!isCompYesAndZeroCC(norm16=getNorm16(c))) {
1650
0
                        break;
1651
0
                    }
1652
0
                }
1653
0
            }
1654
0
        }
1655
0
        // isCompYesAndZeroCC(norm16) is false, that is, norm16>=minNoNo.
1656
0
        // The current character is either a "noNo" (has a mapping)
1657
0
        // or a "maybeYes" (combines backward)
1658
0
        // or a "yesYes" with ccc!=0.
1659
0
        // It is not a Hangul syllable or Jamo L because those have "yes" properties.
1660
0
1661
0
        uint16_t prevNorm16 = INERT;
1662
0
        if (prevBoundary != prevSrc) {
1663
0
            if (norm16HasCompBoundaryBefore(norm16)) {
1664
0
                prevBoundary = prevSrc;
1665
0
            } else {
1666
0
                const UChar *p = prevSrc;
1667
0
                uint16_t n16;
1668
0
                UTRIE2_U16_PREV16(normTrie, prevBoundary, p, c, n16);
1669
0
                if (norm16HasCompBoundaryAfter(n16, onlyContiguous)) {
1670
0
                    prevBoundary = prevSrc;
1671
0
                } else {
1672
0
                    prevBoundary = p;
1673
0
                    prevNorm16 = n16;
1674
0
                }
1675
0
            }
1676
0
        }
1677
0
1678
0
        if(isMaybeOrNonZeroCC(norm16)) {
1679
0
            uint8_t cc=getCCFromYesOrMaybe(norm16);
1680
0
            if (onlyContiguous /* FCC */ && cc != 0 &&
1681
0
                    getTrailCCFromCompYesAndZeroCC(prevNorm16) > cc) {
1682
0
                // The [prevBoundary..prevSrc[ character
1683
0
                // passed the quick check "yes && ccc==0" test
1684
0
                // but is out of canonical order with the current combining mark.
1685
0
            } else {
1686
0
                // If !onlyContiguous (not FCC), then we ignore the tccc of
1687
0
                // the previous character which passed the quick check "yes && ccc==0" test.
1688
0
                const UChar *nextSrc;
1689
0
                for (;;) {
1690
0
                    if (norm16 < MIN_YES_YES_WITH_CC) {
1691
0
                        if (pQCResult != nullptr) {
1692
0
                            *pQCResult = UNORM_MAYBE;
1693
0
                        } else {
1694
0
                            return prevBoundary;
1695
0
                        }
1696
0
                    }
1697
0
                    if (src == limit) {
1698
0
                        return src;
1699
0
                    }
1700
0
                    uint8_t prevCC = cc;
1701
0
                    nextSrc = src;
1702
0
                    UTRIE2_U16_NEXT16(normTrie, nextSrc, limit, c, norm16);
1703
0
                    if (isMaybeOrNonZeroCC(norm16)) {
1704
0
                        cc = getCCFromYesOrMaybe(norm16);
1705
0
                        if (!(prevCC <= cc || cc == 0)) {
1706
0
                            break;
1707
0
                        }
1708
0
                    } else {
1709
0
                        break;
1710
0
                    }
1711
0
                    src = nextSrc;
1712
0
                }
1713
0
                // src is after the last in-order combining mark.
1714
0
                if (isCompYesAndZeroCC(norm16)) {
1715
0
                    prevBoundary = src;
1716
0
                    src = nextSrc;
1717
0
                    continue;
1718
0
                }
1719
0
            }
1720
0
        }
1721
0
        if(pQCResult!=NULL) {
1722
0
            *pQCResult=UNORM_NO;
1723
0
        }
1724
0
        return prevBoundary;
1725
0
    }
1726
0
}
1727
1728
void Normalizer2Impl::composeAndAppend(const UChar *src, const UChar *limit,
1729
                                       UBool doCompose,
1730
                                       UBool onlyContiguous,
1731
                                       UnicodeString &safeMiddle,
1732
                                       ReorderingBuffer &buffer,
1733
53.8k
                                       UErrorCode &errorCode) const {
1734
53.8k
    if(!buffer.isEmpty()) {
1735
53.8k
        const UChar *firstStarterInSrc=findNextCompBoundary(src, limit, onlyContiguous);
1736
53.8k
        if(src!=firstStarterInSrc) {
1737
1.10k
            const UChar *lastStarterInDest=findPreviousCompBoundary(buffer.getStart(),
1738
1.10k
                                                                    buffer.getLimit(), onlyContiguous);
1739
1.10k
            int32_t destSuffixLength=(int32_t)(buffer.getLimit()-lastStarterInDest);
1740
1.10k
            UnicodeString middle(lastStarterInDest, destSuffixLength);
1741
1.10k
            buffer.removeSuffix(destSuffixLength);
1742
1.10k
            safeMiddle=middle;
1743
1.10k
            middle.append(src, (int32_t)(firstStarterInSrc-src));
1744
1.10k
            const UChar *middleStart=middle.getBuffer();
1745
1.10k
            compose(middleStart, middleStart+middle.length(), onlyContiguous,
1746
1.10k
                    TRUE, buffer, errorCode);
1747
1.10k
            if(U_FAILURE(errorCode)) {
1748
0
                return;
1749
0
            }
1750
1.10k
            src=firstStarterInSrc;
1751
1.10k
        }
1752
53.8k
    }
1753
53.8k
    if(doCompose) {
1754
53.8k
        compose(src, limit, onlyContiguous, TRUE, buffer, errorCode);
1755
53.8k
    } else {
1756
0
        if(limit==NULL) {  // appendZeroCC() needs limit!=NULL
1757
0
            limit=u_strchr(src, 0);
1758
0
        }
1759
0
        buffer.appendZeroCC(src, limit, errorCode);
1760
0
    }
1761
53.8k
}
1762
1763
UBool
1764
Normalizer2Impl::composeUTF8(uint32_t options, UBool onlyContiguous,
1765
                             const uint8_t *src, const uint8_t *limit,
1766
0
                             ByteSink *sink, Edits *edits, UErrorCode &errorCode) const {
1767
0
    U_ASSERT(limit != nullptr);
1768
0
    UnicodeString s16;
1769
0
    uint8_t minNoMaybeLead = leadByteForCP(minCompNoMaybeCP);
1770
0
    const uint8_t *prevBoundary = src;
1771
0
1772
0
    for (;;) {
1773
0
        // Fast path: Scan over a sequence of characters below the minimum "no or maybe" code point,
1774
0
        // or with (compYes && ccc==0) properties.
1775
0
        const uint8_t *prevSrc;
1776
0
        uint16_t norm16 = 0;
1777
0
        for (;;) {
1778
0
            if (src == limit) {
1779
0
                if (prevBoundary != limit && sink != nullptr) {
1780
0
                    ByteSinkUtil::appendUnchanged(prevBoundary, limit,
1781
0
                                                  *sink, options, edits, errorCode);
1782
0
                }
1783
0
                return TRUE;
1784
0
            }
1785
0
            if (*src < minNoMaybeLead) {
1786
0
                ++src;
1787
0
            } else {
1788
0
                prevSrc = src;
1789
0
                UTRIE2_U8_NEXT16(normTrie, src, limit, norm16);
1790
0
                if (!isCompYesAndZeroCC(norm16)) {
1791
0
                    break;
1792
0
                }
1793
0
            }
1794
0
        }
1795
0
        // isCompYesAndZeroCC(norm16) is false, that is, norm16>=minNoNo.
1796
0
        // The current character is either a "noNo" (has a mapping)
1797
0
        // or a "maybeYes" (combines backward)
1798
0
        // or a "yesYes" with ccc!=0.
1799
0
        // It is not a Hangul syllable or Jamo L because those have "yes" properties.
1800
0
1801
0
        // Medium-fast path: Handle cases that do not require full decomposition and recomposition.
1802
0
        if (!isMaybeOrNonZeroCC(norm16)) {  // minNoNo <= norm16 < minMaybeYes
1803
0
            if (sink == nullptr) {
1804
0
                return FALSE;
1805
0
            }
1806
0
            // Fast path for mapping a character that is immediately surrounded by boundaries.
1807
0
            // In this case, we need not decompose around the current character.
1808
0
            if (isDecompNoAlgorithmic(norm16)) {
1809
0
                // Maps to a single isCompYesAndZeroCC character
1810
0
                // which also implies hasCompBoundaryBefore.
1811
0
                if (norm16HasCompBoundaryAfter(norm16, onlyContiguous) ||
1812
0
                        hasCompBoundaryBefore(src, limit)) {
1813
0
                    if (prevBoundary != prevSrc &&
1814
0
                            !ByteSinkUtil::appendUnchanged(prevBoundary, prevSrc,
1815
0
                                                           *sink, options, edits, errorCode)) {
1816
0
                        break;
1817
0
                    }
1818
0
                    appendCodePointDelta(prevSrc, src, getAlgorithmicDelta(norm16), *sink, edits);
1819
0
                    prevBoundary = src;
1820
0
                    continue;
1821
0
                }
1822
0
            } else if (norm16 < minNoNoCompBoundaryBefore) {
1823
0
                // The mapping is comp-normalized which also implies hasCompBoundaryBefore.
1824
0
                if (norm16HasCompBoundaryAfter(norm16, onlyContiguous) ||
1825
0
                        hasCompBoundaryBefore(src, limit)) {
1826
0
                    if (prevBoundary != prevSrc &&
1827
0
                            !ByteSinkUtil::appendUnchanged(prevBoundary, prevSrc,
1828
0
                                                           *sink, options, edits, errorCode)) {
1829
0
                        break;
1830
0
                    }
1831
0
                    const uint16_t *mapping = getMapping(norm16);
1832
0
                    int32_t length = *mapping++ & MAPPING_LENGTH_MASK;
1833
0
                    if (!ByteSinkUtil::appendChange(prevSrc, src, (const UChar *)mapping, length,
1834
0
                                                    *sink, edits, errorCode)) {
1835
0
                        break;
1836
0
                    }
1837
0
                    prevBoundary = src;
1838
0
                    continue;
1839
0
                }
1840
0
            } else if (norm16 >= minNoNoEmpty) {
1841
0
                // The current character maps to nothing.
1842
0
                // Simply omit it from the output if there is a boundary before _or_ after it.
1843
0
                // The character itself implies no boundaries.
1844
0
                if (hasCompBoundaryBefore(src, limit) ||
1845
0
                        hasCompBoundaryAfter(prevBoundary, prevSrc, onlyContiguous)) {
1846
0
                    if (prevBoundary != prevSrc &&
1847
0
                            !ByteSinkUtil::appendUnchanged(prevBoundary, prevSrc,
1848
0
                                                           *sink, options, edits, errorCode)) {
1849
0
                        break;
1850
0
                    }
1851
0
                    if (edits != nullptr) {
1852
0
                        edits->addReplace((int32_t)(src - prevSrc), 0);
1853
0
                    }
1854
0
                    prevBoundary = src;
1855
0
                    continue;
1856
0
                }
1857
0
            }
1858
0
            // Other "noNo" type, or need to examine more text around this character:
1859
0
            // Fall through to the slow path.
1860
0
        } else if (isJamoVT(norm16)) {
1861
0
            // Jamo L: E1 84 80..92
1862
0
            // Jamo V: E1 85 A1..B5
1863
0
            // Jamo T: E1 86 A8..E1 87 82
1864
0
            U_ASSERT((src - prevSrc) == 3 && *prevSrc == 0xe1);
1865
0
            UChar32 prev = previousHangulOrJamo(prevBoundary, prevSrc);
1866
0
            if (prevSrc[1] == 0x85) {
1867
0
                // The current character is a Jamo Vowel,
1868
0
                // compose with previous Jamo L and following Jamo T.
1869
0
                UChar32 l = prev - Hangul::JAMO_L_BASE;
1870
0
                if ((uint32_t)l < Hangul::JAMO_L_COUNT) {
1871
0
                    if (sink == nullptr) {
1872
0
                        return FALSE;
1873
0
                    }
1874
0
                    int32_t t = getJamoTMinusBase(src, limit);
1875
0
                    if (t >= 0) {
1876
0
                        // The next character is a Jamo T.
1877
0
                        src += 3;
1878
0
                    } else if (hasCompBoundaryBefore(src, limit)) {
1879
0
                        // No Jamo T follows, not even via decomposition.
1880
0
                        t = 0;
1881
0
                    }
1882
0
                    if (t >= 0) {
1883
0
                        UChar32 syllable = Hangul::HANGUL_BASE +
1884
0
                            (l*Hangul::JAMO_V_COUNT + (prevSrc[2]-0xa1)) *
1885
0
                            Hangul::JAMO_T_COUNT + t;
1886
0
                        prevSrc -= 3;  // Replace the Jamo L as well.
1887
0
                        if (prevBoundary != prevSrc &&
1888
0
                                !ByteSinkUtil::appendUnchanged(prevBoundary, prevSrc,
1889
0
                                                               *sink, options, edits, errorCode)) {
1890
0
                            break;
1891
0
                        }
1892
0
                        ByteSinkUtil::appendCodePoint(prevSrc, src, syllable, *sink, edits);
1893
0
                        prevBoundary = src;
1894
0
                        continue;
1895
0
                    }
1896
0
                    // If we see L+V+x where x!=T then we drop to the slow path,
1897
0
                    // decompose and recompose.
1898
0
                    // This is to deal with NFKC finding normal L and V but a
1899
0
                    // compatibility variant of a T.
1900
0
                    // We need to either fully compose that combination here
1901
0
                    // (which would complicate the code and may not work with strange custom data)
1902
0
                    // or use the slow path.
1903
0
                }
1904
0
            } else if (Hangul::isHangulLV(prev)) {
1905
0
                // The current character is a Jamo Trailing consonant,
1906
0
                // compose with previous Hangul LV that does not contain a Jamo T.
1907
0
                if (sink == nullptr) {
1908
0
                    return FALSE;
1909
0
                }
1910
0
                UChar32 syllable = prev + getJamoTMinusBase(prevSrc, src);
1911
0
                prevSrc -= 3;  // Replace the Hangul LV as well.
1912
0
                if (prevBoundary != prevSrc &&
1913
0
                        !ByteSinkUtil::appendUnchanged(prevBoundary, prevSrc,
1914
0
                                                       *sink, options, edits, errorCode)) {
1915
0
                    break;
1916
0
                }
1917
0
                ByteSinkUtil::appendCodePoint(prevSrc, src, syllable, *sink, edits);
1918
0
                prevBoundary = src;
1919
0
                continue;
1920
0
            }
1921
0
            // No matching context, or may need to decompose surrounding text first:
1922
0
            // Fall through to the slow path.
1923
0
        } else if (norm16 > JAMO_VT) {  // norm16 >= MIN_YES_YES_WITH_CC
1924
0
            // One or more combining marks that do not combine-back:
1925
0
            // Check for canonical order, copy unchanged if ok and
1926
0
            // if followed by a character with a boundary-before.
1927
0
            uint8_t cc = getCCFromNormalYesOrMaybe(norm16);  // cc!=0
1928
0
            if (onlyContiguous /* FCC */ && getPreviousTrailCC(prevBoundary, prevSrc) > cc) {
1929
0
                // Fails FCD test, need to decompose and contiguously recompose.
1930
0
                if (sink == nullptr) {
1931
0
                    return FALSE;
1932
0
                }
1933
0
            } else {
1934
0
                // If !onlyContiguous (not FCC), then we ignore the tccc of
1935
0
                // the previous character which passed the quick check "yes && ccc==0" test.
1936
0
                const uint8_t *nextSrc;
1937
0
                uint16_t n16;
1938
0
                for (;;) {
1939
0
                    if (src == limit) {
1940
0
                        if (sink != nullptr) {
1941
0
                            ByteSinkUtil::appendUnchanged(prevBoundary, limit,
1942
0
                                                          *sink, options, edits, errorCode);
1943
0
                        }
1944
0
                        return TRUE;
1945
0
                    }
1946
0
                    uint8_t prevCC = cc;
1947
0
                    nextSrc = src;
1948
0
                    UTRIE2_U8_NEXT16(normTrie, nextSrc, limit, n16);
1949
0
                    if (n16 >= MIN_YES_YES_WITH_CC) {
1950
0
                        cc = getCCFromNormalYesOrMaybe(n16);
1951
0
                        if (prevCC > cc) {
1952
0
                            if (sink == nullptr) {
1953
0
                                return FALSE;
1954
0
                            }
1955
0
                            break;
1956
0
                        }
1957
0
                    } else {
1958
0
                        break;
1959
0
                    }
1960
0
                    src = nextSrc;
1961
0
                }
1962
0
                // src is after the last in-order combining mark.
1963
0
                // If there is a boundary here, then we continue with no change.
1964
0
                if (norm16HasCompBoundaryBefore(n16)) {
1965
0
                    if (isCompYesAndZeroCC(n16)) {
1966
0
                        src = nextSrc;
1967
0
                    }
1968
0
                    continue;
1969
0
                }
1970
0
                // Use the slow path. There is no boundary in [prevSrc, src[.
1971
0
            }
1972
0
        }
1973
0
1974
0
        // Slow path: Find the nearest boundaries around the current character,
1975
0
        // decompose and recompose.
1976
0
        if (prevBoundary != prevSrc && !norm16HasCompBoundaryBefore(norm16)) {
1977
0
            const uint8_t *p = prevSrc;
1978
0
            UTRIE2_U8_PREV16(normTrie, prevBoundary, p, norm16);
1979
0
            if (!norm16HasCompBoundaryAfter(norm16, onlyContiguous)) {
1980
0
                prevSrc = p;
1981
0
            }
1982
0
        }
1983
0
        ReorderingBuffer buffer(*this, s16, errorCode);
1984
0
        if (U_FAILURE(errorCode)) {
1985
0
            break;
1986
0
        }
1987
0
        // We know there is not a boundary here.
1988
0
        decomposeShort(prevSrc, src, FALSE /* !stopAtCompBoundary */, onlyContiguous,
1989
0
                       buffer, errorCode);
1990
0
        // Decompose until the next boundary.
1991
0
        src = decomposeShort(src, limit, TRUE /* stopAtCompBoundary */, onlyContiguous,
1992
0
                             buffer, errorCode);
1993
0
        if (U_FAILURE(errorCode)) {
1994
0
            break;
1995
0
        }
1996
0
        if ((src - prevSrc) > INT32_MAX) {  // guard before buffer.equals()
1997
0
            errorCode = U_INDEX_OUTOFBOUNDS_ERROR;
1998
0
            return TRUE;
1999
0
        }
2000
0
        recompose(buffer, 0, onlyContiguous);
2001
0
        if (!buffer.equals(prevSrc, src)) {
2002
0
            if (sink == nullptr) {
2003
0
                return FALSE;
2004
0
            }
2005
0
            if (prevBoundary != prevSrc &&
2006
0
                    !ByteSinkUtil::appendUnchanged(prevBoundary, prevSrc,
2007
0
                                                   *sink, options, edits, errorCode)) {
2008
0
                break;
2009
0
            }
2010
0
            if (!ByteSinkUtil::appendChange(prevSrc, src, buffer.getStart(), buffer.length(),
2011
0
                                            *sink, edits, errorCode)) {
2012
0
                break;
2013
0
            }
2014
0
            prevBoundary = src;
2015
0
        }
2016
0
    }
2017
0
    return TRUE;
2018
0
}
2019
2020
46.2k
UBool Normalizer2Impl::hasCompBoundaryBefore(const UChar *src, const UChar *limit) const {
2021
46.2k
    if (src == limit || *src < minCompNoMaybeCP) {
2022
18.5k
        return TRUE;
2023
18.5k
    }
2024
27.7k
    UChar32 c;
2025
27.7k
    uint16_t norm16;
2026
27.7k
    UTRIE2_U16_NEXT16(normTrie, src, limit, c, norm16);
2027
27.7k
    return norm16HasCompBoundaryBefore(norm16);
2028
27.7k
}
2029
2030
0
UBool Normalizer2Impl::hasCompBoundaryBefore(const uint8_t *src, const uint8_t *limit) const {
2031
0
    if (src == limit) {
2032
0
        return TRUE;
2033
0
    }
2034
0
    uint16_t norm16;
2035
0
    UTRIE2_U8_NEXT16(normTrie, src, limit, norm16);
2036
0
    return norm16HasCompBoundaryBefore(norm16);
2037
0
}
2038
2039
UBool Normalizer2Impl::hasCompBoundaryAfter(const UChar *start, const UChar *p,
2040
93
                                            UBool onlyContiguous) const {
2041
93
    if (start == p) {
2042
89
        return TRUE;
2043
89
    }
2044
4
    UChar32 c;
2045
4
    uint16_t norm16;
2046
4
    UTRIE2_U16_PREV16(normTrie, start, p, c, norm16);
2047
4
    return norm16HasCompBoundaryAfter(norm16, onlyContiguous);
2048
4
}
2049
2050
UBool Normalizer2Impl::hasCompBoundaryAfter(const uint8_t *start, const uint8_t *p,
2051
0
                                            UBool onlyContiguous) const {
2052
0
    if (start == p) {
2053
0
        return TRUE;
2054
0
    }
2055
0
    uint16_t norm16;
2056
0
    UTRIE2_U8_PREV16(normTrie, start, p, norm16);
2057
0
    return norm16HasCompBoundaryAfter(norm16, onlyContiguous);
2058
0
}
2059
2060
const UChar *Normalizer2Impl::findPreviousCompBoundary(const UChar *start, const UChar *p,
2061
1.10k
                                                       UBool onlyContiguous) const {
2062
1.10k
    BackwardUTrie2StringIterator iter(normTrie, start, p);
2063
1.10k
    for(;;) {
2064
1.10k
        uint16_t norm16=iter.previous16();
2065
1.10k
        if (norm16HasCompBoundaryAfter(norm16, onlyContiguous)) {
2066
1.09k
            return iter.codePointLimit;
2067
1.09k
        }
2068
12
        if (hasCompBoundaryBefore(iter.codePoint, norm16)) {
2069
12
            return iter.codePointStart;
2070
12
        }
2071
12
    }
2072
1.10k
}
2073
2074
const UChar *Normalizer2Impl::findNextCompBoundary(const UChar *p, const UChar *limit,
2075
53.8k
                                                   UBool onlyContiguous) const {
2076
53.8k
    ForwardUTrie2StringIterator iter(normTrie, p, limit);
2077
54.9k
    for(;;) {
2078
54.9k
        uint16_t norm16=iter.next16();
2079
54.9k
        if (hasCompBoundaryBefore(iter.codePoint, norm16)) {
2080
53.8k
            return iter.codePointStart;
2081
53.8k
        }
2082
1.11k
        if (norm16HasCompBoundaryAfter(norm16, onlyContiguous)) {
2083
0
            return iter.codePointLimit;
2084
0
        }
2085
1.11k
    }
2086
53.8k
}
2087
2088
0
uint8_t Normalizer2Impl::getPreviousTrailCC(const UChar *start, const UChar *p) const {
2089
0
    if (start == p) {
2090
0
        return 0;
2091
0
    }
2092
0
    int32_t i = (int32_t)(p - start);
2093
0
    UChar32 c;
2094
0
    U16_PREV(start, 0, i, c);
2095
0
    return (uint8_t)getFCD16(c);
2096
0
}
2097
2098
0
uint8_t Normalizer2Impl::getPreviousTrailCC(const uint8_t *start, const uint8_t *p) const {
2099
0
    if (start == p) {
2100
0
        return 0;
2101
0
    }
2102
0
    int32_t i = (int32_t)(p - start);
2103
0
    UChar32 c;
2104
0
    U8_PREV(start, 0, i, c);
2105
0
    return (uint8_t)getFCD16(c);
2106
0
}
2107
2108
// Note: normalizer2impl.cpp r30982 (2011-nov-27)
2109
// still had getFCDTrie() which built and cached an FCD trie.
2110
// That provided faster access to FCD data than getFCD16FromNormData()
2111
// but required synchronization and consumed some 10kB of heap memory
2112
// in any process that uses FCD (e.g., via collation).
2113
// minDecompNoCP etc. and smallFCD[] are intended to help with any loss of performance,
2114
// at least for ASCII & CJK.
2115
2116
// Gets the FCD value from the regular normalization data.
2117
0
uint16_t Normalizer2Impl::getFCD16FromNormData(UChar32 c) const {
2118
0
    uint16_t norm16=getNorm16(c);
2119
0
    if (norm16 >= limitNoNo) {
2120
0
        if(norm16>=MIN_NORMAL_MAYBE_YES) {
2121
0
            // combining mark
2122
0
            norm16=getCCFromNormalYesOrMaybe(norm16);
2123
0
            return norm16|(norm16<<8);
2124
0
        } else if(norm16>=minMaybeYes) {
2125
0
            return 0;
2126
0
        } else {  // isDecompNoAlgorithmic(norm16)
2127
0
            uint16_t deltaTrailCC = norm16 & DELTA_TCCC_MASK;
2128
0
            if (deltaTrailCC <= DELTA_TCCC_1) {
2129
0
                return deltaTrailCC >> OFFSET_SHIFT;
2130
0
            }
2131
0
            // Maps to an isCompYesAndZeroCC.
2132
0
            c=mapAlgorithmic(c, norm16);
2133
0
            norm16=getNorm16(c);
2134
0
        }
2135
0
    }
2136
0
    if(norm16<=minYesNo || isHangulLVT(norm16)) {
2137
0
        // no decomposition or Hangul syllable, all zeros
2138
0
        return 0;
2139
0
    }
2140
0
    // c decomposes, get everything from the variable-length extra data
2141
0
    const uint16_t *mapping=getMapping(norm16);
2142
0
    uint16_t firstUnit=*mapping;
2143
0
    norm16=firstUnit>>8;  // tccc
2144
0
    if(firstUnit&MAPPING_HAS_CCC_LCCC_WORD) {
2145
0
        norm16|=*(mapping-1)&0xff00;  // lccc
2146
0
    }
2147
0
    return norm16;
2148
0
}
2149
2150
// Dual functionality:
2151
// buffer!=NULL: normalize
2152
// buffer==NULL: isNormalized/quickCheck/spanQuickCheckYes
2153
const UChar *
2154
Normalizer2Impl::makeFCD(const UChar *src, const UChar *limit,
2155
                         ReorderingBuffer *buffer,
2156
0
                         UErrorCode &errorCode) const {
2157
0
    // Tracks the last FCD-safe boundary, before lccc=0 or after properly-ordered tccc<=1.
2158
0
    // Similar to the prevBoundary in the compose() implementation.
2159
0
    const UChar *prevBoundary=src;
2160
0
    int32_t prevFCD16=0;
2161
0
    if(limit==NULL) {
2162
0
        src=copyLowPrefixFromNulTerminated(src, minLcccCP, buffer, errorCode);
2163
0
        if(U_FAILURE(errorCode)) {
2164
0
            return src;
2165
0
        }
2166
0
        if(prevBoundary<src) {
2167
0
            prevBoundary=src;
2168
0
            // We know that the previous character's lccc==0.
2169
0
            // Fetching the fcd16 value was deferred for this below-U+0300 code point.
2170
0
            prevFCD16=getFCD16(*(src-1));
2171
0
            if(prevFCD16>1) {
2172
0
                --prevBoundary;
2173
0
            }
2174
0
        }
2175
0
        limit=u_strchr(src, 0);
2176
0
    }
2177
0
2178
0
    // Note: In this function we use buffer->appendZeroCC() because we track
2179
0
    // the lead and trail combining classes here, rather than leaving it to
2180
0
    // the ReorderingBuffer.
2181
0
    // The exception is the call to decomposeShort() which uses the buffer
2182
0
    // in the normal way.
2183
0
2184
0
    const UChar *prevSrc;
2185
0
    UChar32 c=0;
2186
0
    uint16_t fcd16=0;
2187
0
2188
0
    for(;;) {
2189
0
        // count code units with lccc==0
2190
0
        for(prevSrc=src; src!=limit;) {
2191
0
            if((c=*src)<minLcccCP) {
2192
0
                prevFCD16=~c;
2193
0
                ++src;
2194
0
            } else if(!singleLeadMightHaveNonZeroFCD16(c)) {
2195
0
                prevFCD16=0;
2196
0
                ++src;
2197
0
            } else {
2198
0
                if(U16_IS_SURROGATE(c)) {
2199
0
                    UChar c2;
2200
0
                    if(U16_IS_SURROGATE_LEAD(c)) {
2201
0
                        if((src+1)!=limit && U16_IS_TRAIL(c2=src[1])) {
2202
0
                            c=U16_GET_SUPPLEMENTARY(c, c2);
2203
0
                        }
2204
0
                    } else /* trail surrogate */ {
2205
0
                        if(prevSrc<src && U16_IS_LEAD(c2=*(src-1))) {
2206
0
                            --src;
2207
0
                            c=U16_GET_SUPPLEMENTARY(c2, c);
2208
0
                        }
2209
0
                    }
2210
0
                }
2211
0
                if((fcd16=getFCD16FromNormData(c))<=0xff) {
2212
0
                    prevFCD16=fcd16;
2213
0
                    src+=U16_LENGTH(c);
2214
0
                } else {
2215
0
                    break;
2216
0
                }
2217
0
            }
2218
0
        }
2219
0
        // copy these code units all at once
2220
0
        if(src!=prevSrc) {
2221
0
            if(buffer!=NULL && !buffer->appendZeroCC(prevSrc, src, errorCode)) {
2222
0
                break;
2223
0
            }
2224
0
            if(src==limit) {
2225
0
                break;
2226
0
            }
2227
0
            prevBoundary=src;
2228
0
            // We know that the previous character's lccc==0.
2229
0
            if(prevFCD16<0) {
2230
0
                // Fetching the fcd16 value was deferred for this below-minLcccCP code point.
2231
0
                UChar32 prev=~prevFCD16;
2232
0
                if(prev<minDecompNoCP) {
2233
0
                    prevFCD16=0;
2234
0
                } else {
2235
0
                    prevFCD16=getFCD16FromNormData(prev);
2236
0
                    if(prevFCD16>1) {
2237
0
                        --prevBoundary;
2238
0
                    }
2239
0
                }
2240
0
            } else {
2241
0
                const UChar *p=src-1;
2242
0
                if(U16_IS_TRAIL(*p) && prevSrc<p && U16_IS_LEAD(*(p-1))) {
2243
0
                    --p;
2244
0
                    // Need to fetch the previous character's FCD value because
2245
0
                    // prevFCD16 was just for the trail surrogate code point.
2246
0
                    prevFCD16=getFCD16FromNormData(U16_GET_SUPPLEMENTARY(p[0], p[1]));
2247
0
                    // Still known to have lccc==0 because its lead surrogate unit had lccc==0.
2248
0
                }
2249
0
                if(prevFCD16>1) {
2250
0
                    prevBoundary=p;
2251
0
                }
2252
0
            }
2253
0
            // The start of the current character (c).
2254
0
            prevSrc=src;
2255
0
        } else if(src==limit) {
2256
0
            break;
2257
0
        }
2258
0
2259
0
        src+=U16_LENGTH(c);
2260
0
        // The current character (c) at [prevSrc..src[ has a non-zero lead combining class.
2261
0
        // Check for proper order, and decompose locally if necessary.
2262
0
        if((prevFCD16&0xff)<=(fcd16>>8)) {
2263
0
            // proper order: prev tccc <= current lccc
2264
0
            if((fcd16&0xff)<=1) {
2265
0
                prevBoundary=src;
2266
0
            }
2267
0
            if(buffer!=NULL && !buffer->appendZeroCC(c, errorCode)) {
2268
0
                break;
2269
0
            }
2270
0
            prevFCD16=fcd16;
2271
0
            continue;
2272
0
        } else if(buffer==NULL) {
2273
0
            return prevBoundary;  // quick check "no"
2274
0
        } else {
2275
0
            /*
2276
0
             * Back out the part of the source that we copied or appended
2277
0
             * already but is now going to be decomposed.
2278
0
             * prevSrc is set to after what was copied/appended.
2279
0
             */
2280
0
            buffer->removeSuffix((int32_t)(prevSrc-prevBoundary));
2281
0
            /*
2282
0
             * Find the part of the source that needs to be decomposed,
2283
0
             * up to the next safe boundary.
2284
0
             */
2285
0
            src=findNextFCDBoundary(src, limit);
2286
0
            /*
2287
0
             * The source text does not fulfill the conditions for FCD.
2288
0
             * Decompose and reorder a limited piece of the text.
2289
0
             */
2290
0
            decomposeShort(prevBoundary, src, FALSE, FALSE, *buffer, errorCode);
2291
0
            if (U_FAILURE(errorCode)) {
2292
0
                break;
2293
0
            }
2294
0
            prevBoundary=src;
2295
0
            prevFCD16=0;
2296
0
        }
2297
0
    }
2298
0
    return src;
2299
0
}
2300
2301
void Normalizer2Impl::makeFCDAndAppend(const UChar *src, const UChar *limit,
2302
                                       UBool doMakeFCD,
2303
                                       UnicodeString &safeMiddle,
2304
                                       ReorderingBuffer &buffer,
2305
0
                                       UErrorCode &errorCode) const {
2306
0
    if(!buffer.isEmpty()) {
2307
0
        const UChar *firstBoundaryInSrc=findNextFCDBoundary(src, limit);
2308
0
        if(src!=firstBoundaryInSrc) {
2309
0
            const UChar *lastBoundaryInDest=findPreviousFCDBoundary(buffer.getStart(),
2310
0
                                                                    buffer.getLimit());
2311
0
            int32_t destSuffixLength=(int32_t)(buffer.getLimit()-lastBoundaryInDest);
2312
0
            UnicodeString middle(lastBoundaryInDest, destSuffixLength);
2313
0
            buffer.removeSuffix(destSuffixLength);
2314
0
            safeMiddle=middle;
2315
0
            middle.append(src, (int32_t)(firstBoundaryInSrc-src));
2316
0
            const UChar *middleStart=middle.getBuffer();
2317
0
            makeFCD(middleStart, middleStart+middle.length(), &buffer, errorCode);
2318
0
            if(U_FAILURE(errorCode)) {
2319
0
                return;
2320
0
            }
2321
0
            src=firstBoundaryInSrc;
2322
0
        }
2323
0
    }
2324
0
    if(doMakeFCD) {
2325
0
        makeFCD(src, limit, &buffer, errorCode);
2326
0
    } else {
2327
0
        if(limit==NULL) {  // appendZeroCC() needs limit!=NULL
2328
0
            limit=u_strchr(src, 0);
2329
0
        }
2330
0
        buffer.appendZeroCC(src, limit, errorCode);
2331
0
    }
2332
0
}
2333
2334
0
const UChar *Normalizer2Impl::findPreviousFCDBoundary(const UChar *start, const UChar *p) const {
2335
0
    while(start<p) {
2336
0
        const UChar *codePointLimit = p;
2337
0
        UChar32 c;
2338
0
        uint16_t norm16;
2339
0
        UTRIE2_U16_PREV16(normTrie, start, p, c, norm16);
2340
0
        if (c < minDecompNoCP || norm16HasDecompBoundaryAfter(norm16)) {
2341
0
            return codePointLimit;
2342
0
        }
2343
0
        if (norm16HasDecompBoundaryBefore(norm16)) {
2344
0
            return p;
2345
0
        }
2346
0
    }
2347
0
    return p;
2348
0
}
2349
2350
0
const UChar *Normalizer2Impl::findNextFCDBoundary(const UChar *p, const UChar *limit) const {
2351
0
    while(p<limit) {
2352
0
        const UChar *codePointStart=p;
2353
0
        UChar32 c;
2354
0
        uint16_t norm16;
2355
0
        UTRIE2_U16_NEXT16(normTrie, p, limit, c, norm16);
2356
0
        if (c < minLcccCP || norm16HasDecompBoundaryBefore(norm16)) {
2357
0
            return codePointStart;
2358
0
        }
2359
0
        if (norm16HasDecompBoundaryAfter(norm16)) {
2360
0
            return p;
2361
0
        }
2362
0
    }
2363
0
    return p;
2364
0
}
2365
2366
// CanonicalIterator data -------------------------------------------------- ***
2367
2368
CanonIterData::CanonIterData(UErrorCode &errorCode) :
2369
        trie(utrie2_open(0, 0, &errorCode)),
2370
0
        canonStartSets(uprv_deleteUObject, NULL, errorCode) {}
2371
2372
0
CanonIterData::~CanonIterData() {
2373
0
    utrie2_close(trie);
2374
0
}
2375
2376
0
void CanonIterData::addToStartSet(UChar32 origin, UChar32 decompLead, UErrorCode &errorCode) {
2377
0
    uint32_t canonValue=utrie2_get32(trie, decompLead);
2378
0
    if((canonValue&(CANON_HAS_SET|CANON_VALUE_MASK))==0 && origin!=0) {
2379
0
        // origin is the first character whose decomposition starts with
2380
0
        // the character for which we are setting the value.
2381
0
        utrie2_set32(trie, decompLead, canonValue|origin, &errorCode);
2382
0
    } else {
2383
0
        // origin is not the first character, or it is U+0000.
2384
0
        UnicodeSet *set;
2385
0
        if((canonValue&CANON_HAS_SET)==0) {
2386
0
            set=new UnicodeSet;
2387
0
            if(set==NULL) {
2388
0
                errorCode=U_MEMORY_ALLOCATION_ERROR;
2389
0
                return;
2390
0
            }
2391
0
            UChar32 firstOrigin=(UChar32)(canonValue&CANON_VALUE_MASK);
2392
0
            canonValue=(canonValue&~CANON_VALUE_MASK)|CANON_HAS_SET|(uint32_t)canonStartSets.size();
2393
0
            utrie2_set32(trie, decompLead, canonValue, &errorCode);
2394
0
            canonStartSets.addElement(set, errorCode);
2395
0
            if(firstOrigin!=0) {
2396
0
                set->add(firstOrigin);
2397
0
            }
2398
0
        } else {
2399
0
            set=(UnicodeSet *)canonStartSets[(int32_t)(canonValue&CANON_VALUE_MASK)];
2400
0
        }
2401
0
        set->add(origin);
2402
0
    }
2403
0
}
2404
2405
// C++ class for friend access to private Normalizer2Impl members.
2406
class InitCanonIterData {
2407
public:
2408
    static void doInit(Normalizer2Impl *impl, UErrorCode &errorCode);
2409
    static void handleRange(Normalizer2Impl *impl, UChar32 start, UChar32 end, uint16_t value, UErrorCode &errorCode);
2410
};
2411
2412
U_CDECL_BEGIN
2413
2414
// UInitOnce instantiation function for CanonIterData
2415
static void U_CALLCONV
2416
0
initCanonIterData(Normalizer2Impl *impl, UErrorCode &errorCode) {
2417
0
    InitCanonIterData::doInit(impl, errorCode);
2418
0
}
2419
2420
// Call Normalizer2Impl::makeCanonIterDataFromNorm16() for a range of same-norm16 characters.
2421
//     context: the Normalizer2Impl
2422
static UBool U_CALLCONV
2423
0
enumCIDRangeHandler(const void *context, UChar32 start, UChar32 end, uint32_t value) {
2424
0
    UErrorCode errorCode = U_ZERO_ERROR;
2425
0
    if (value != Normalizer2Impl::INERT) {
2426
0
        Normalizer2Impl *impl = (Normalizer2Impl *)context;
2427
0
        InitCanonIterData::handleRange(impl, start, end, (uint16_t)value, errorCode);
2428
0
    }
2429
0
    return U_SUCCESS(errorCode);
2430
0
}
2431
2432
U_CDECL_END
2433
2434
0
void InitCanonIterData::doInit(Normalizer2Impl *impl, UErrorCode &errorCode) {
2435
0
    U_ASSERT(impl->fCanonIterData == NULL);
2436
0
    impl->fCanonIterData = new CanonIterData(errorCode);
2437
0
    if (impl->fCanonIterData == NULL) {
2438
0
        errorCode=U_MEMORY_ALLOCATION_ERROR;
2439
0
    }
2440
0
    if (U_SUCCESS(errorCode)) {
2441
0
        utrie2_enum(impl->normTrie, NULL, enumCIDRangeHandler, impl);
2442
0
        utrie2_freeze(impl->fCanonIterData->trie, UTRIE2_32_VALUE_BITS, &errorCode);
2443
0
    }
2444
0
    if (U_FAILURE(errorCode)) {
2445
0
        delete impl->fCanonIterData;
2446
0
        impl->fCanonIterData = NULL;
2447
0
    }
2448
0
}
2449
2450
void InitCanonIterData::handleRange(
2451
0
        Normalizer2Impl *impl, UChar32 start, UChar32 end, uint16_t value, UErrorCode &errorCode) {
2452
0
    impl->makeCanonIterDataFromNorm16(start, end, value, *impl->fCanonIterData, errorCode);
2453
0
}
2454
2455
void Normalizer2Impl::makeCanonIterDataFromNorm16(UChar32 start, UChar32 end, const uint16_t norm16,
2456
                                                  CanonIterData &newData,
2457
0
                                                  UErrorCode &errorCode) const {
2458
0
    if(isInert(norm16) || (minYesNo<=norm16 && norm16<minNoNo)) {
2459
0
        // Inert, or 2-way mapping (including Hangul syllable).
2460
0
        // We do not write a canonStartSet for any yesNo character.
2461
0
        // Composites from 2-way mappings are added at runtime from the
2462
0
        // starter's compositions list, and the other characters in
2463
0
        // 2-way mappings get CANON_NOT_SEGMENT_STARTER set because they are
2464
0
        // "maybe" characters.
2465
0
        return;
2466
0
    }
2467
0
    for(UChar32 c=start; c<=end; ++c) {
2468
0
        uint32_t oldValue=utrie2_get32(newData.trie, c);
2469
0
        uint32_t newValue=oldValue;
2470
0
        if(isMaybeOrNonZeroCC(norm16)) {
2471
0
            // not a segment starter if it occurs in a decomposition or has cc!=0
2472
0
            newValue|=CANON_NOT_SEGMENT_STARTER;
2473
0
            if(norm16<MIN_NORMAL_MAYBE_YES) {
2474
0
                newValue|=CANON_HAS_COMPOSITIONS;
2475
0
            }
2476
0
        } else if(norm16<minYesNo) {
2477
0
            newValue|=CANON_HAS_COMPOSITIONS;
2478
0
        } else {
2479
0
            // c has a one-way decomposition
2480
0
            UChar32 c2=c;
2481
0
            // Do not modify the whole-range norm16 value.
2482
0
            uint16_t norm16_2=norm16;
2483
0
            if (isDecompNoAlgorithmic(norm16_2)) {
2484
0
                // Maps to an isCompYesAndZeroCC.
2485
0
                c2 = mapAlgorithmic(c2, norm16_2);
2486
0
                norm16_2 = getNorm16(c2);
2487
0
                // No compatibility mappings for the CanonicalIterator.
2488
0
                U_ASSERT(!(isHangulLV(norm16_2) || isHangulLVT(norm16_2)));
2489
0
            }
2490
0
            if (norm16_2 > minYesNo) {
2491
0
                // c decomposes, get everything from the variable-length extra data
2492
0
                const uint16_t *mapping=getMapping(norm16_2);
2493
0
                uint16_t firstUnit=*mapping;
2494
0
                int32_t length=firstUnit&MAPPING_LENGTH_MASK;
2495
0
                if((firstUnit&MAPPING_HAS_CCC_LCCC_WORD)!=0) {
2496
0
                    if(c==c2 && (*(mapping-1)&0xff)!=0) {
2497
0
                        newValue|=CANON_NOT_SEGMENT_STARTER;  // original c has cc!=0
2498
0
                    }
2499
0
                }
2500
0
                // Skip empty mappings (no characters in the decomposition).
2501
0
                if(length!=0) {
2502
0
                    ++mapping;  // skip over the firstUnit
2503
0
                    // add c to first code point's start set
2504
0
                    int32_t i=0;
2505
0
                    U16_NEXT_UNSAFE(mapping, i, c2);
2506
0
                    newData.addToStartSet(c, c2, errorCode);
2507
0
                    // Set CANON_NOT_SEGMENT_STARTER for each remaining code point of a
2508
0
                    // one-way mapping. A 2-way mapping is possible here after
2509
0
                    // intermediate algorithmic mapping.
2510
0
                    if(norm16_2>=minNoNo) {
2511
0
                        while(i<length) {
2512
0
                            U16_NEXT_UNSAFE(mapping, i, c2);
2513
0
                            uint32_t c2Value=utrie2_get32(newData.trie, c2);
2514
0
                            if((c2Value&CANON_NOT_SEGMENT_STARTER)==0) {
2515
0
                                utrie2_set32(newData.trie, c2, c2Value|CANON_NOT_SEGMENT_STARTER,
2516
0
                                             &errorCode);
2517
0
                            }
2518
0
                        }
2519
0
                    }
2520
0
                }
2521
0
            } else {
2522
0
                // c decomposed to c2 algorithmically; c has cc==0
2523
0
                newData.addToStartSet(c, c2, errorCode);
2524
0
            }
2525
0
        }
2526
0
        if(newValue!=oldValue) {
2527
0
            utrie2_set32(newData.trie, c, newValue, &errorCode);
2528
0
        }
2529
0
    }
2530
0
}
2531
2532
0
UBool Normalizer2Impl::ensureCanonIterData(UErrorCode &errorCode) const {
2533
0
    // Logically const: Synchronized instantiation.
2534
0
    Normalizer2Impl *me=const_cast<Normalizer2Impl *>(this);
2535
0
    umtx_initOnce(me->fCanonIterDataInitOnce, &initCanonIterData, me, errorCode);
2536
0
    return U_SUCCESS(errorCode);
2537
0
}
2538
2539
0
int32_t Normalizer2Impl::getCanonValue(UChar32 c) const {
2540
0
    return (int32_t)utrie2_get32(fCanonIterData->trie, c);
2541
0
}
2542
2543
0
const UnicodeSet &Normalizer2Impl::getCanonStartSet(int32_t n) const {
2544
0
    return *(const UnicodeSet *)fCanonIterData->canonStartSets[n];
2545
0
}
2546
2547
0
UBool Normalizer2Impl::isCanonSegmentStarter(UChar32 c) const {
2548
0
    return getCanonValue(c)>=0;
2549
0
}
2550
2551
0
UBool Normalizer2Impl::getCanonStartSet(UChar32 c, UnicodeSet &set) const {
2552
0
    int32_t canonValue=getCanonValue(c)&~CANON_NOT_SEGMENT_STARTER;
2553
0
    if(canonValue==0) {
2554
0
        return FALSE;
2555
0
    }
2556
0
    set.clear();
2557
0
    int32_t value=canonValue&CANON_VALUE_MASK;
2558
0
    if((canonValue&CANON_HAS_SET)!=0) {
2559
0
        set.addAll(getCanonStartSet(value));
2560
0
    } else if(value!=0) {
2561
0
        set.add(value);
2562
0
    }
2563
0
    if((canonValue&CANON_HAS_COMPOSITIONS)!=0) {
2564
0
        uint16_t norm16=getNorm16(c);
2565
0
        if(norm16==JAMO_L) {
2566
0
            UChar32 syllable=
2567
0
                (UChar32)(Hangul::HANGUL_BASE+(c-Hangul::JAMO_L_BASE)*Hangul::JAMO_VT_COUNT);
2568
0
            set.add(syllable, syllable+Hangul::JAMO_VT_COUNT-1);
2569
0
        } else {
2570
0
            addComposites(getCompositionsList(norm16), set);
2571
0
        }
2572
0
    }
2573
0
    return TRUE;
2574
0
}
2575
2576
U_NAMESPACE_END
2577
2578
// Normalizer2 data swapping ----------------------------------------------- ***
2579
2580
U_NAMESPACE_USE
2581
2582
U_CAPI int32_t U_EXPORT2
2583
unorm2_swap(const UDataSwapper *ds,
2584
            const void *inData, int32_t length, void *outData,
2585
0
            UErrorCode *pErrorCode) {
2586
0
    const UDataInfo *pInfo;
2587
0
    int32_t headerSize;
2588
0
2589
0
    const uint8_t *inBytes;
2590
0
    uint8_t *outBytes;
2591
0
2592
0
    const int32_t *inIndexes;
2593
0
    int32_t indexes[Normalizer2Impl::IX_TOTAL_SIZE+1];
2594
0
2595
0
    int32_t i, offset, nextOffset, size;
2596
0
2597
0
    /* udata_swapDataHeader checks the arguments */
2598
0
    headerSize=udata_swapDataHeader(ds, inData, length, outData, pErrorCode);
2599
0
    if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
2600
0
        return 0;
2601
0
    }
2602
0
2603
0
    /* check data format and format version */
2604
0
    pInfo=(const UDataInfo *)((const char *)inData+4);
2605
0
    uint8_t formatVersion0=pInfo->formatVersion[0];
2606
0
    if(!(
2607
0
        pInfo->dataFormat[0]==0x4e &&   /* dataFormat="Nrm2" */
2608
0
        pInfo->dataFormat[1]==0x72 &&
2609
0
        pInfo->dataFormat[2]==0x6d &&
2610
0
        pInfo->dataFormat[3]==0x32 &&
2611
0
        (1<=formatVersion0 && formatVersion0<=3)
2612
0
    )) {
2613
0
        udata_printError(ds, "unorm2_swap(): data format %02x.%02x.%02x.%02x (format version %02x) is not recognized as Normalizer2 data\n",
2614
0
                         pInfo->dataFormat[0], pInfo->dataFormat[1],
2615
0
                         pInfo->dataFormat[2], pInfo->dataFormat[3],
2616
0
                         pInfo->formatVersion[0]);
2617
0
        *pErrorCode=U_UNSUPPORTED_ERROR;
2618
0
        return 0;
2619
0
    }
2620
0
2621
0
    inBytes=(const uint8_t *)inData+headerSize;
2622
0
    outBytes=(uint8_t *)outData+headerSize;
2623
0
2624
0
    inIndexes=(const int32_t *)inBytes;
2625
0
    int32_t minIndexesLength;
2626
0
    if(formatVersion0==1) {
2627
0
        minIndexesLength=Normalizer2Impl::IX_MIN_MAYBE_YES+1;
2628
0
    } else if(formatVersion0==2) {
2629
0
        minIndexesLength=Normalizer2Impl::IX_MIN_YES_NO_MAPPINGS_ONLY+1;
2630
0
    } else {
2631
0
        minIndexesLength=Normalizer2Impl::IX_MIN_LCCC_CP+1;
2632
0
    }
2633
0
2634
0
    if(length>=0) {
2635
0
        length-=headerSize;
2636
0
        if(length<minIndexesLength*4) {
2637
0
            udata_printError(ds, "unorm2_swap(): too few bytes (%d after header) for Normalizer2 data\n",
2638
0
                             length);
2639
0
            *pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR;
2640
0
            return 0;
2641
0
        }
2642
0
    }
2643
0
2644
0
    /* read the first few indexes */
2645
0
    for(i=0; i<UPRV_LENGTHOF(indexes); ++i) {
2646
0
        indexes[i]=udata_readInt32(ds, inIndexes[i]);
2647
0
    }
2648
0
2649
0
    /* get the total length of the data */
2650
0
    size=indexes[Normalizer2Impl::IX_TOTAL_SIZE];
2651
0
2652
0
    if(length>=0) {
2653
0
        if(length<size) {
2654
0
            udata_printError(ds, "unorm2_swap(): too few bytes (%d after header) for all of Normalizer2 data\n",
2655
0
                             length);
2656
0
            *pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR;
2657
0
            return 0;
2658
0
        }
2659
0
2660
0
        /* copy the data for inaccessible bytes */
2661
0
        if(inBytes!=outBytes) {
2662
0
            uprv_memcpy(outBytes, inBytes, size);
2663
0
        }
2664
0
2665
0
        offset=0;
2666
0
2667
0
        /* swap the int32_t indexes[] */
2668
0
        nextOffset=indexes[Normalizer2Impl::IX_NORM_TRIE_OFFSET];
2669
0
        ds->swapArray32(ds, inBytes, nextOffset-offset, outBytes, pErrorCode);
2670
0
        offset=nextOffset;
2671
0
2672
0
        /* swap the UTrie2 */
2673
0
        nextOffset=indexes[Normalizer2Impl::IX_EXTRA_DATA_OFFSET];
2674
0
        utrie2_swap(ds, inBytes+offset, nextOffset-offset, outBytes+offset, pErrorCode);
2675
0
        offset=nextOffset;
2676
0
2677
0
        /* swap the uint16_t extraData[] */
2678
0
        nextOffset=indexes[Normalizer2Impl::IX_SMALL_FCD_OFFSET];
2679
0
        ds->swapArray16(ds, inBytes+offset, nextOffset-offset, outBytes+offset, pErrorCode);
2680
0
        offset=nextOffset;
2681
0
2682
0
        /* no need to swap the uint8_t smallFCD[] (new in formatVersion 2) */
2683
0
        nextOffset=indexes[Normalizer2Impl::IX_SMALL_FCD_OFFSET+1];
2684
0
        offset=nextOffset;
2685
0
2686
0
        U_ASSERT(offset==size);
2687
0
    }
2688
0
2689
0
    return headerSize+size;
2690
0
}
2691
2692
#endif  // !UCONFIG_NO_NORMALIZATION