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