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.h
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#ifndef __NORMALIZER2IMPL_H__
20#define __NORMALIZER2IMPL_H__
21
22#include "unicode/utypes.h"
23
24#if !UCONFIG_NO_NORMALIZATION
25
26#include "unicode/normalizer2.h"
27#include "unicode/ucptrie.h"
28#include "unicode/unistr.h"
29#include "unicode/unorm.h"
30#include "unicode/utf.h"
31#include "unicode/utf16.h"
32#include "mutex.h"
33#include "udataswp.h"
34#include "uset_imp.h"
35
36// When the nfc.nrm data is *not* hardcoded into the common library
37// (with this constant set to 0),
38// then it needs to be built into the data package:
39// Add nfc.nrm to icu4c/source/data/Makefile.in DAT_FILES_SHORT
40#define NORM2_HARDCODE_NFC_DATA 1
41
42U_NAMESPACE_BEGIN
43
44struct CanonIterData;
45
46class ByteSink;
47class Edits;
48class InitCanonIterData;
49class LcccContext;
50
51class U_COMMON_API Hangul {
52public:
53 /* Korean Hangul and Jamo constants */
54 enum {
55 JAMO_L_BASE=0x1100, /* "lead" jamo */
56 JAMO_L_END=0x1112,
57 JAMO_V_BASE=0x1161, /* "vowel" jamo */
58 JAMO_V_END=0x1175,
59 JAMO_T_BASE=0x11a7, /* "trail" jamo */
60 JAMO_T_END=0x11c2,
61
62 HANGUL_BASE=0xac00,
63 HANGUL_END=0xd7a3,
64
65 JAMO_L_COUNT=19,
66 JAMO_V_COUNT=21,
67 JAMO_T_COUNT=28,
68
69 JAMO_VT_COUNT=JAMO_V_COUNT*JAMO_T_COUNT,
70
71 HANGUL_COUNT=JAMO_L_COUNT*JAMO_V_COUNT*JAMO_T_COUNT,
72 HANGUL_LIMIT=HANGUL_BASE+HANGUL_COUNT
73 };
74
75 static inline UBool isHangul(UChar32 c) {
76 return HANGUL_BASE<=c && c<HANGUL_LIMIT;
77 }
78 static inline UBool
79 isHangulLV(UChar32 c) {
80 c-=HANGUL_BASE;
81 return 0<=c && c<HANGUL_COUNT && c%JAMO_T_COUNT==0;
82 }
83 static inline UBool isJamoL(UChar32 c) {
84 return (uint32_t)(c-JAMO_L_BASE)<JAMO_L_COUNT;
85 }
86 static inline UBool isJamoV(UChar32 c) {
87 return (uint32_t)(c-JAMO_V_BASE)<JAMO_V_COUNT;
88 }
89 static inline UBool isJamoT(UChar32 c) {
90 int32_t t=c-JAMO_T_BASE;
91 return 0<t && t<JAMO_T_COUNT; // not JAMO_T_BASE itself
92 }
93 static UBool isJamo(UChar32 c) {
94 return JAMO_L_BASE<=c && c<=JAMO_T_END &&
95 (c<=JAMO_L_END || (JAMO_V_BASE<=c && c<=JAMO_V_END) || JAMO_T_BASE<c);
96 }
97
98 /**
99 * Decomposes c, which must be a Hangul syllable, into buffer
100 * and returns the length of the decomposition (2 or 3).
101 */
102 static inline int32_t decompose(UChar32 c, UChar buffer[3]) {
103 c-=HANGUL_BASE;
104 UChar32 c2=c%JAMO_T_COUNT;
105 c/=JAMO_T_COUNT;
106 buffer[0]=(UChar)(JAMO_L_BASE+c/JAMO_V_COUNT);
107 buffer[1]=(UChar)(JAMO_V_BASE+c%JAMO_V_COUNT);
108 if(c2==0) {
109 return 2;
110 } else {
111 buffer[2]=(UChar)(JAMO_T_BASE+c2);
112 return 3;
113 }
114 }
115
116 /**
117 * Decomposes c, which must be a Hangul syllable, into buffer.
118 * This is the raw, not recursive, decomposition. Its length is always 2.
119 */
120 static inline void getRawDecomposition(UChar32 c, UChar buffer[2]) {
121 UChar32 orig=c;
122 c-=HANGUL_BASE;
123 UChar32 c2=c%JAMO_T_COUNT;
124 if(c2==0) {
125 c/=JAMO_T_COUNT;
126 buffer[0]=(UChar)(JAMO_L_BASE+c/JAMO_V_COUNT);
127 buffer[1]=(UChar)(JAMO_V_BASE+c%JAMO_V_COUNT);
128 } else {
129 buffer[0]=(UChar)(orig-c2); // LV syllable
130 buffer[1]=(UChar)(JAMO_T_BASE+c2);
131 }
132 }
133private:
134 Hangul(); // no instantiation
135};
136
137class Normalizer2Impl;
138
139class U_COMMON_API ReorderingBuffer : public UMemory {
140public:
141 /** Constructs only; init() should be called. */
142 ReorderingBuffer(const Normalizer2Impl &ni, UnicodeString &dest) :
143 impl(ni), str(dest),
144 start(NULL), reorderStart(NULL), limit(NULL),
145 remainingCapacity(0), lastCC(0) {}
146 /** Constructs, removes the string contents, and initializes for a small initial capacity. */
147 ReorderingBuffer(const Normalizer2Impl &ni, UnicodeString &dest, UErrorCode &errorCode);
148 ~ReorderingBuffer() {
149 if(start!=NULL) {
150 str.releaseBuffer((int32_t)(limit-start));
151 }
152 }
153 UBool init(int32_t destCapacity, UErrorCode &errorCode);
154
155 UBool isEmpty() const { return start==limit; }
156 int32_t length() const { return (int32_t)(limit-start); }
157 UChar *getStart() { return start; }
158 UChar *getLimit() { return limit; }
159 uint8_t getLastCC() const { return lastCC; }
160
161 UBool equals(const UChar *start, const UChar *limit) const;
162 UBool equals(const uint8_t *otherStart, const uint8_t *otherLimit) const;
163
164 UBool append(UChar32 c, uint8_t cc, UErrorCode &errorCode) {
165 return (c<=0xffff) ?
166 appendBMP((UChar)c, cc, errorCode) :
167 appendSupplementary(c, cc, errorCode);
168 }
169 UBool append(const UChar *s, int32_t length, UBool isNFD,
170 uint8_t leadCC, uint8_t trailCC,
171 UErrorCode &errorCode);
172 UBool appendBMP(UChar c, uint8_t cc, UErrorCode &errorCode) {
173 if(remainingCapacity==0 && !resize(1, errorCode)) {
174 return FALSE;
175 }
176 if(lastCC<=cc || cc==0) {
177 *limit++=c;
178 lastCC=cc;
179 if(cc<=1) {
180 reorderStart=limit;
181 }
182 } else {
183 insert(c, cc);
184 }
185 --remainingCapacity;
186 return TRUE;
187 }
188 UBool appendZeroCC(UChar32 c, UErrorCode &errorCode);
189 UBool appendZeroCC(const UChar *s, const UChar *sLimit, UErrorCode &errorCode);
190 void remove();
191 void removeSuffix(int32_t suffixLength);
192 void setReorderingLimit(UChar *newLimit) {
193 remainingCapacity+=(int32_t)(limit-newLimit);
194 reorderStart=limit=newLimit;
195 lastCC=0;
196 }
197 void copyReorderableSuffixTo(UnicodeString &s) const {
198 s.setTo(ConstChar16Ptr(reorderStart), (int32_t)(limit-reorderStart));
199 }
200private:
201 /*
202 * TODO: Revisit whether it makes sense to track reorderStart.
203 * It is set to after the last known character with cc<=1,
204 * which stops previousCC() before it reads that character and looks up its cc.
205 * previousCC() is normally only called from insert().
206 * In other words, reorderStart speeds up the insertion of a combining mark
207 * into a multi-combining mark sequence where it does not belong at the end.
208 * This might not be worth the trouble.
209 * On the other hand, it's not a huge amount of trouble.
210 *
211 * We probably need it for UNORM_SIMPLE_APPEND.
212 */
213
214 UBool appendSupplementary(UChar32 c, uint8_t cc, UErrorCode &errorCode);
215 void insert(UChar32 c, uint8_t cc);
216 static void writeCodePoint(UChar *p, UChar32 c) {
217 if(c<=0xffff) {
218 *p=(UChar)c;
219 } else {
220 p[0]=U16_LEAD(c);
221 p[1]=U16_TRAIL(c);
222 }
223 }
224 UBool resize(int32_t appendLength, UErrorCode &errorCode);
225
226 const Normalizer2Impl &impl;
227 UnicodeString &str;
228 UChar *start, *reorderStart, *limit;
229 int32_t remainingCapacity;
230 uint8_t lastCC;
231
232 // private backward iterator
233 void setIterator() { codePointStart=limit; }
234 void skipPrevious(); // Requires start<codePointStart.
235 uint8_t previousCC(); // Returns 0 if there is no previous character.
236
237 UChar *codePointStart, *codePointLimit;
238};
239
240/**
241 * Low-level implementation of the Unicode Normalization Algorithm.
242 * For the data structure and details see the documentation at the end of
243 * this normalizer2impl.h and in the design doc at
244 * http://site.icu-project.org/design/normalization/custom
245 */
246class U_COMMON_API Normalizer2Impl : public UObject {
247public:
248 Normalizer2Impl() : normTrie(NULL), fCanonIterData(NULL) { }
249 virtual ~Normalizer2Impl();
250
251 void init(const int32_t *inIndexes, const UCPTrie *inTrie,
252 const uint16_t *inExtraData, const uint8_t *inSmallFCD);
253
254 void addLcccChars(UnicodeSet &set) const;
255 void addPropertyStarts(const USetAdder *sa, UErrorCode &errorCode) const;
256 void addCanonIterPropertyStarts(const USetAdder *sa, UErrorCode &errorCode) const;
257
258 // low-level properties ------------------------------------------------ ***
259
260 UBool ensureCanonIterData(UErrorCode &errorCode) const;
261
262 // The trie stores values for lead surrogate code *units*.
263 // Surrogate code *points* are inert.
264 uint16_t getNorm16(UChar32 c) const {
265 return U_IS_LEAD(c) ?
266 static_cast<uint16_t>(INERT) :
267 UCPTRIE_FAST_GET(normTrie, UCPTRIE_16, c);
268 }
269 uint16_t getRawNorm16(UChar32 c) const { return UCPTRIE_FAST_GET(normTrie, UCPTRIE_16, c); }
270
271 UNormalizationCheckResult getCompQuickCheck(uint16_t norm16) const {
272 if(norm16<minNoNo || MIN_YES_YES_WITH_CC<=norm16) {
273 return UNORM_YES;
274 } else if(minMaybeYes<=norm16) {
275 return UNORM_MAYBE;
276 } else {
277 return UNORM_NO;
278 }
279 }
280 UBool isAlgorithmicNoNo(uint16_t norm16) const { return limitNoNo<=norm16 && norm16<minMaybeYes; }
281 UBool isCompNo(uint16_t norm16) const { return minNoNo<=norm16 && norm16<minMaybeYes; }
282 UBool isDecompYes(uint16_t norm16) const { return norm16<minYesNo || minMaybeYes<=norm16; }
283
284 uint8_t getCC(uint16_t norm16) const {
285 if(norm16>=MIN_NORMAL_MAYBE_YES) {
286 return getCCFromNormalYesOrMaybe(norm16);
287 }
288 if(norm16<minNoNo || limitNoNo<=norm16) {
289 return 0;
290 }
291 return getCCFromNoNo(norm16);
292 }
293 static uint8_t getCCFromNormalYesOrMaybe(uint16_t norm16) {
294 return (uint8_t)(norm16 >> OFFSET_SHIFT);
295 }
296 static uint8_t getCCFromYesOrMaybe(uint16_t norm16) {
297 return norm16>=MIN_NORMAL_MAYBE_YES ? getCCFromNormalYesOrMaybe(norm16) : 0;
298 }
299 uint8_t getCCFromYesOrMaybeCP(UChar32 c) const {
300 if (c < minCompNoMaybeCP) { return 0; }
301 return getCCFromYesOrMaybe(getNorm16(c));
302 }
303
304 /**
305 * Returns the FCD data for code point c.
306 * @param c A Unicode code point.
307 * @return The lccc(c) in bits 15..8 and tccc(c) in bits 7..0.
308 */
309 uint16_t getFCD16(UChar32 c) const {
310 if(c<minDecompNoCP) {
311 return 0;
312 } else if(c<=0xffff) {
313 if(!singleLeadMightHaveNonZeroFCD16(c)) { return 0; }
314 }
315 return getFCD16FromNormData(c);
316 }
317 /**
318 * Returns the FCD data for the next code point (post-increment).
319 * Might skip only a lead surrogate rather than the whole surrogate pair if none of
320 * the supplementary code points associated with the lead surrogate have non-zero FCD data.
321 * @param s A valid pointer into a string. Requires s!=limit.
322 * @param limit The end of the string, or NULL.
323 * @return The lccc(c) in bits 15..8 and tccc(c) in bits 7..0.
324 */
325 uint16_t nextFCD16(const UChar *&s, const UChar *limit) const {
326 UChar32 c=*s++;
327 if(c<minDecompNoCP || !singleLeadMightHaveNonZeroFCD16(c)) {
328 return 0;
329 }
330 UChar c2;
331 if(U16_IS_LEAD(c) && s!=limit && U16_IS_TRAIL(c2=*s)) {
332 c=U16_GET_SUPPLEMENTARY(c, c2);
333 ++s;
334 }
335 return getFCD16FromNormData(c);
336 }
337 /**
338 * Returns the FCD data for the previous code point (pre-decrement).
339 * @param start The start of the string.
340 * @param s A valid pointer into a string. Requires start<s.
341 * @return The lccc(c) in bits 15..8 and tccc(c) in bits 7..0.
342 */
343 uint16_t previousFCD16(const UChar *start, const UChar *&s) const {
344 UChar32 c=*--s;
345 if(c<minDecompNoCP) {
346 return 0;
347 }
348 if(!U16_IS_TRAIL(c)) {
349 if(!singleLeadMightHaveNonZeroFCD16(c)) {
350 return 0;
351 }
352 } else {
353 UChar c2;
354 if(start<s && U16_IS_LEAD(c2=*(s-1))) {
355 c=U16_GET_SUPPLEMENTARY(c2, c);
356 --s;
357 }
358 }
359 return getFCD16FromNormData(c);
360 }
361
362 /** Returns TRUE if the single-or-lead code unit c might have non-zero FCD data. */
363 UBool singleLeadMightHaveNonZeroFCD16(UChar32 lead) const {
364 // 0<=lead<=0xffff
365 uint8_t bits=smallFCD[lead>>8];
366 if(bits==0) { return false; }
367 return (UBool)((bits>>((lead>>5)&7))&1);
368 }
369 /** Returns the FCD value from the regular normalization data. */
370 uint16_t getFCD16FromNormData(UChar32 c) const;
371
372 /**
373 * Gets the decomposition for one code point.
374 * @param c code point
375 * @param buffer out-only buffer for algorithmic decompositions
376 * @param length out-only, takes the length of the decomposition, if any
377 * @return pointer to the decomposition, or NULL if none
378 */
379 const UChar *getDecomposition(UChar32 c, UChar buffer[4], int32_t &length) const;
380
381 /**
382 * Gets the raw decomposition for one code point.
383 * @param c code point
384 * @param buffer out-only buffer for algorithmic decompositions
385 * @param length out-only, takes the length of the decomposition, if any
386 * @return pointer to the decomposition, or NULL if none
387 */
388 const UChar *getRawDecomposition(UChar32 c, UChar buffer[30], int32_t &length) const;
389
390 UChar32 composePair(UChar32 a, UChar32 b) const;
391
392 UBool isCanonSegmentStarter(UChar32 c) const;
393 UBool getCanonStartSet(UChar32 c, UnicodeSet &set) const;
394
395 enum {
396 // Fixed norm16 values.
397 MIN_YES_YES_WITH_CC=0xfe02,
398 JAMO_VT=0xfe00,
399 MIN_NORMAL_MAYBE_YES=0xfc00,
400 JAMO_L=2, // offset=1 hasCompBoundaryAfter=FALSE
401 INERT=1, // offset=0 hasCompBoundaryAfter=TRUE
402
403 // norm16 bit 0 is comp-boundary-after.
404 HAS_COMP_BOUNDARY_AFTER=1,
405 OFFSET_SHIFT=1,
406
407 // For algorithmic one-way mappings, norm16 bits 2..1 indicate the
408 // tccc (0, 1, >1) for quick FCC boundary-after tests.
409 DELTA_TCCC_0=0,
410 DELTA_TCCC_1=2,
411 DELTA_TCCC_GT_1=4,
412 DELTA_TCCC_MASK=6,
413 DELTA_SHIFT=3,
414
415 MAX_DELTA=0x40
416 };
417
418 enum {
419 // Byte offsets from the start of the data, after the generic header.
420 IX_NORM_TRIE_OFFSET,
421 IX_EXTRA_DATA_OFFSET,
422 IX_SMALL_FCD_OFFSET,
423 IX_RESERVED3_OFFSET,
424 IX_RESERVED4_OFFSET,
425 IX_RESERVED5_OFFSET,
426 IX_RESERVED6_OFFSET,
427 IX_TOTAL_SIZE,
428
429 // Code point thresholds for quick check codes.
430 IX_MIN_DECOMP_NO_CP,
431 IX_MIN_COMP_NO_MAYBE_CP,
432
433 // Norm16 value thresholds for quick check combinations and types of extra data.
434
435 /** Mappings & compositions in [minYesNo..minYesNoMappingsOnly[. */
436 IX_MIN_YES_NO,
437 /** Mappings are comp-normalized. */
438 IX_MIN_NO_NO,
439 IX_LIMIT_NO_NO,
440 IX_MIN_MAYBE_YES,
441
442 /** Mappings only in [minYesNoMappingsOnly..minNoNo[. */
443 IX_MIN_YES_NO_MAPPINGS_ONLY,
444 /** Mappings are not comp-normalized but have a comp boundary before. */
445 IX_MIN_NO_NO_COMP_BOUNDARY_BEFORE,
446 /** Mappings do not have a comp boundary before. */
447 IX_MIN_NO_NO_COMP_NO_MAYBE_CC,
448 /** Mappings to the empty string. */
449 IX_MIN_NO_NO_EMPTY,
450
451 IX_MIN_LCCC_CP,
452 IX_RESERVED19,
453 IX_COUNT
454 };
455
456 enum {
457 MAPPING_HAS_CCC_LCCC_WORD=0x80,
458 MAPPING_HAS_RAW_MAPPING=0x40,
459 // unused bit 0x20,
460 MAPPING_LENGTH_MASK=0x1f
461 };
462
463 enum {
464 COMP_1_LAST_TUPLE=0x8000,
465 COMP_1_TRIPLE=1,
466 COMP_1_TRAIL_LIMIT=0x3400,
467 COMP_1_TRAIL_MASK=0x7ffe,
468 COMP_1_TRAIL_SHIFT=9, // 10-1 for the "triple" bit
469 COMP_2_TRAIL_SHIFT=6,
470 COMP_2_TRAIL_MASK=0xffc0
471 };
472
473 // higher-level functionality ------------------------------------------ ***
474
475 // NFD without an NFD Normalizer2 instance.
476 UnicodeString &decompose(const UnicodeString &src, UnicodeString &dest,
477 UErrorCode &errorCode) const;
478 /**
479 * Decomposes [src, limit[ and writes the result to dest.
480 * limit can be NULL if src is NUL-terminated.
481 * destLengthEstimate is the initial dest buffer capacity and can be -1.
482 */
483 void decompose(const UChar *src, const UChar *limit,
484 UnicodeString &dest, int32_t destLengthEstimate,
485 UErrorCode &errorCode) const;
486
487 const UChar *decompose(const UChar *src, const UChar *limit,
488 ReorderingBuffer *buffer, UErrorCode &errorCode) const;
489 void decomposeAndAppend(const UChar *src, const UChar *limit,
490 UBool doDecompose,
491 UnicodeString &safeMiddle,
492 ReorderingBuffer &buffer,
493 UErrorCode &errorCode) const;
494 UBool compose(const UChar *src, const UChar *limit,
495 UBool onlyContiguous,
496 UBool doCompose,
497 ReorderingBuffer &buffer,
498 UErrorCode &errorCode) const;
499 const UChar *composeQuickCheck(const UChar *src, const UChar *limit,
500 UBool onlyContiguous,
501 UNormalizationCheckResult *pQCResult) const;
502 void composeAndAppend(const UChar *src, const UChar *limit,
503 UBool doCompose,
504 UBool onlyContiguous,
505 UnicodeString &safeMiddle,
506 ReorderingBuffer &buffer,
507 UErrorCode &errorCode) const;
508
509 /** sink==nullptr: isNormalized() */
510 UBool composeUTF8(uint32_t options, UBool onlyContiguous,
511 const uint8_t *src, const uint8_t *limit,
512 ByteSink *sink, icu::Edits *edits, UErrorCode &errorCode) const;
513
514 const UChar *makeFCD(const UChar *src, const UChar *limit,
515 ReorderingBuffer *buffer, UErrorCode &errorCode) const;
516 void makeFCDAndAppend(const UChar *src, const UChar *limit,
517 UBool doMakeFCD,
518 UnicodeString &safeMiddle,
519 ReorderingBuffer &buffer,
520 UErrorCode &errorCode) const;
521
522 UBool hasDecompBoundaryBefore(UChar32 c) const;
523 UBool norm16HasDecompBoundaryBefore(uint16_t norm16) const;
524 UBool hasDecompBoundaryAfter(UChar32 c) const;
525 UBool norm16HasDecompBoundaryAfter(uint16_t norm16) const;
526 UBool isDecompInert(UChar32 c) const { return isDecompYesAndZeroCC(getNorm16(c)); }
527
528 UBool hasCompBoundaryBefore(UChar32 c) const {
529 return c<minCompNoMaybeCP || norm16HasCompBoundaryBefore(getNorm16(c));
530 }
531 UBool hasCompBoundaryAfter(UChar32 c, UBool onlyContiguous) const {
532 return norm16HasCompBoundaryAfter(getNorm16(c), onlyContiguous);
533 }
534 UBool isCompInert(UChar32 c, UBool onlyContiguous) const {
535 uint16_t norm16=getNorm16(c);
536 return isCompYesAndZeroCC(norm16) &&
537 (norm16 & HAS_COMP_BOUNDARY_AFTER) != 0 &&
538 (!onlyContiguous || isInert(norm16) || *getMapping(norm16) <= 0x1ff);
539 }
540
541 UBool hasFCDBoundaryBefore(UChar32 c) const { return hasDecompBoundaryBefore(c); }
542 UBool hasFCDBoundaryAfter(UChar32 c) const { return hasDecompBoundaryAfter(c); }
543 UBool isFCDInert(UChar32 c) const { return getFCD16(c)<=1; }
544private:
545 friend class InitCanonIterData;
546 friend class LcccContext;
547
548 UBool isMaybe(uint16_t norm16) const { return minMaybeYes<=norm16 && norm16<=JAMO_VT; }
549 UBool isMaybeOrNonZeroCC(uint16_t norm16) const { return norm16>=minMaybeYes; }
550 static UBool isInert(uint16_t norm16) { return norm16==INERT; }
551 static UBool isJamoL(uint16_t norm16) { return norm16==JAMO_L; }
552 static UBool isJamoVT(uint16_t norm16) { return norm16==JAMO_VT; }
553 uint16_t hangulLVT() const { return minYesNoMappingsOnly|HAS_COMP_BOUNDARY_AFTER; }
554 UBool isHangulLV(uint16_t norm16) const { return norm16==minYesNo; }
555 UBool isHangulLVT(uint16_t norm16) const {
556 return norm16==hangulLVT();
557 }
558 UBool isCompYesAndZeroCC(uint16_t norm16) const { return norm16<minNoNo; }
559 // UBool isCompYes(uint16_t norm16) const {
560 // return norm16>=MIN_YES_YES_WITH_CC || norm16<minNoNo;
561 // }
562 // UBool isCompYesOrMaybe(uint16_t norm16) const {
563 // return norm16<minNoNo || minMaybeYes<=norm16;
564 // }
565 // UBool hasZeroCCFromDecompYes(uint16_t norm16) const {
566 // return norm16<=MIN_NORMAL_MAYBE_YES || norm16==JAMO_VT;
567 // }
568 UBool isDecompYesAndZeroCC(uint16_t norm16) const {
569 return norm16<minYesNo ||
570 norm16==JAMO_VT ||
571 (minMaybeYes<=norm16 && norm16<=MIN_NORMAL_MAYBE_YES);
572 }
573 /**
574 * A little faster and simpler than isDecompYesAndZeroCC() but does not include
575 * the MaybeYes which combine-forward and have ccc=0.
576 * (Standard Unicode 10 normalization does not have such characters.)
577 */
578 UBool isMostDecompYesAndZeroCC(uint16_t norm16) const {
579 return norm16<minYesNo || norm16==MIN_NORMAL_MAYBE_YES || norm16==JAMO_VT;
580 }
581 UBool isDecompNoAlgorithmic(uint16_t norm16) const { return norm16>=limitNoNo; }
582
583 // For use with isCompYes().
584 // Perhaps the compiler can combine the two tests for MIN_YES_YES_WITH_CC.
585 // static uint8_t getCCFromYes(uint16_t norm16) {
586 // return norm16>=MIN_YES_YES_WITH_CC ? getCCFromNormalYesOrMaybe(norm16) : 0;
587 // }
588 uint8_t getCCFromNoNo(uint16_t norm16) const {
589 const uint16_t *mapping=getMapping(norm16);
590 if(*mapping&MAPPING_HAS_CCC_LCCC_WORD) {
591 return (uint8_t)*(mapping-1);
592 } else {
593 return 0;
594 }
595 }
596 // requires that the [cpStart..cpLimit[ character passes isCompYesAndZeroCC()
597 uint8_t getTrailCCFromCompYesAndZeroCC(uint16_t norm16) const {
598 if(norm16<=minYesNo) {
599 return 0; // yesYes and Hangul LV have ccc=tccc=0
600 } else {
601 // For Hangul LVT we harmlessly fetch a firstUnit with tccc=0 here.
602 return (uint8_t)(*getMapping(norm16)>>8); // tccc from yesNo
603 }
604 }
605 uint8_t getPreviousTrailCC(const UChar *start, const UChar *p) const;
606 uint8_t getPreviousTrailCC(const uint8_t *start, const uint8_t *p) const;
607
608 // Requires algorithmic-NoNo.
609 UChar32 mapAlgorithmic(UChar32 c, uint16_t norm16) const {
610 return c+(norm16>>DELTA_SHIFT)-centerNoNoDelta;
611 }
612 UChar32 getAlgorithmicDelta(uint16_t norm16) const {
613 return (norm16>>DELTA_SHIFT)-centerNoNoDelta;
614 }
615
616 // Requires minYesNo<norm16<limitNoNo.
617 const uint16_t *getMapping(uint16_t norm16) const { return extraData+(norm16>>OFFSET_SHIFT); }
618 const uint16_t *getCompositionsListForDecompYes(uint16_t norm16) const {
619 if(norm16<JAMO_L || MIN_NORMAL_MAYBE_YES<=norm16) {
620 return NULL;
621 } else if(norm16<minMaybeYes) {
622 return getMapping(norm16); // for yesYes; if Jamo L: harmless empty list
623 } else {
624 return maybeYesCompositions+norm16-minMaybeYes;
625 }
626 }
627 const uint16_t *getCompositionsListForComposite(uint16_t norm16) const {
628 // A composite has both mapping & compositions list.
629 const uint16_t *list=getMapping(norm16);
630 return list+ // mapping pointer
631 1+ // +1 to skip the first unit with the mapping length
632 (*list&MAPPING_LENGTH_MASK); // + mapping length
633 }
634 const uint16_t *getCompositionsListForMaybe(uint16_t norm16) const {
635 // minMaybeYes<=norm16<MIN_NORMAL_MAYBE_YES
636 return maybeYesCompositions+((norm16-minMaybeYes)>>OFFSET_SHIFT);
637 }
638 /**
639 * @param c code point must have compositions
640 * @return compositions list pointer
641 */
642 const uint16_t *getCompositionsList(uint16_t norm16) const {
643 return isDecompYes(norm16) ?
644 getCompositionsListForDecompYes(norm16) :
645 getCompositionsListForComposite(norm16);
646 }
647
648 const UChar *copyLowPrefixFromNulTerminated(const UChar *src,
649 UChar32 minNeedDataCP,
650 ReorderingBuffer *buffer,
651 UErrorCode &errorCode) const;
652 const UChar *decomposeShort(const UChar *src, const UChar *limit,
653 UBool stopAtCompBoundary, UBool onlyContiguous,
654 ReorderingBuffer &buffer, UErrorCode &errorCode) const;
655 UBool decompose(UChar32 c, uint16_t norm16,
656 ReorderingBuffer &buffer, UErrorCode &errorCode) const;
657
658 const uint8_t *decomposeShort(const uint8_t *src, const uint8_t *limit,
659 UBool stopAtCompBoundary, UBool onlyContiguous,
660 ReorderingBuffer &buffer, UErrorCode &errorCode) const;
661
662 static int32_t combine(const uint16_t *list, UChar32 trail);
663 void addComposites(const uint16_t *list, UnicodeSet &set) const;
664 void recompose(ReorderingBuffer &buffer, int32_t recomposeStartIndex,
665 UBool onlyContiguous) const;
666
667 UBool hasCompBoundaryBefore(UChar32 c, uint16_t norm16) const {
668 return c<minCompNoMaybeCP || norm16HasCompBoundaryBefore(norm16);
669 }
670 UBool norm16HasCompBoundaryBefore(uint16_t norm16) const {
671 return norm16 < minNoNoCompNoMaybeCC || isAlgorithmicNoNo(norm16);
672 }
673 UBool hasCompBoundaryBefore(const UChar *src, const UChar *limit) const;
674 UBool hasCompBoundaryBefore(const uint8_t *src, const uint8_t *limit) const;
675 UBool hasCompBoundaryAfter(const UChar *start, const UChar *p,
676 UBool onlyContiguous) const;
677 UBool hasCompBoundaryAfter(const uint8_t *start, const uint8_t *p,
678 UBool onlyContiguous) const;
679 UBool norm16HasCompBoundaryAfter(uint16_t norm16, UBool onlyContiguous) const {
680 return (norm16 & HAS_COMP_BOUNDARY_AFTER) != 0 &&
681 (!onlyContiguous || isTrailCC01ForCompBoundaryAfter(norm16));
682 }
683 /** For FCC: Given norm16 HAS_COMP_BOUNDARY_AFTER, does it have tccc<=1? */
684 UBool isTrailCC01ForCompBoundaryAfter(uint16_t norm16) const {
685 return isInert(norm16) || (isDecompNoAlgorithmic(norm16) ?
686 (norm16 & DELTA_TCCC_MASK) <= DELTA_TCCC_1 : *getMapping(norm16) <= 0x1ff);
687 }
688
689 const UChar *findPreviousCompBoundary(const UChar *start, const UChar *p, UBool onlyContiguous) const;
690 const UChar *findNextCompBoundary(const UChar *p, const UChar *limit, UBool onlyContiguous) const;
691
692 const UChar *findPreviousFCDBoundary(const UChar *start, const UChar *p) const;
693 const UChar *findNextFCDBoundary(const UChar *p, const UChar *limit) const;
694
695 void makeCanonIterDataFromNorm16(UChar32 start, UChar32 end, const uint16_t norm16,
696 CanonIterData &newData, UErrorCode &errorCode) const;
697
698 int32_t getCanonValue(UChar32 c) const;
699 const UnicodeSet &getCanonStartSet(int32_t n) const;
700
701 // UVersionInfo dataVersion;
702
703 // BMP code point thresholds for quick check loops looking at single UTF-16 code units.
704 UChar minDecompNoCP;
705 UChar minCompNoMaybeCP;
706 UChar minLcccCP;
707
708 // Norm16 value thresholds for quick check combinations and types of extra data.
709 uint16_t minYesNo;
710 uint16_t minYesNoMappingsOnly;
711 uint16_t minNoNo;
712 uint16_t minNoNoCompBoundaryBefore;
713 uint16_t minNoNoCompNoMaybeCC;
714 uint16_t minNoNoEmpty;
715 uint16_t limitNoNo;
716 uint16_t centerNoNoDelta;
717 uint16_t minMaybeYes;
718
719 const UCPTrie *normTrie;
720 const uint16_t *maybeYesCompositions;
721 const uint16_t *extraData; // mappings and/or compositions for yesYes, yesNo & noNo characters
722 const uint8_t *smallFCD; // [0x100] one bit per 32 BMP code points, set if any FCD!=0
723
724 UInitOnce fCanonIterDataInitOnce = U_INITONCE_INITIALIZER;
725 CanonIterData *fCanonIterData;
726};
727
728// bits in canonIterData
729#define CANON_NOT_SEGMENT_STARTER 0x80000000
730#define CANON_HAS_COMPOSITIONS 0x40000000
731#define CANON_HAS_SET 0x200000
732#define CANON_VALUE_MASK 0x1fffff
733
734/**
735 * ICU-internal shortcut for quick access to standard Unicode normalization.
736 */
737class U_COMMON_API Normalizer2Factory {
738public:
739 static const Normalizer2 *getFCDInstance(UErrorCode &errorCode);
740 static const Normalizer2 *getFCCInstance(UErrorCode &errorCode);
741 static const Normalizer2 *getNoopInstance(UErrorCode &errorCode);
742
743 static const Normalizer2 *getInstance(UNormalizationMode mode, UErrorCode &errorCode);
744
745 static const Normalizer2Impl *getNFCImpl(UErrorCode &errorCode);
746 static const Normalizer2Impl *getNFKCImpl(UErrorCode &errorCode);
747 static const Normalizer2Impl *getNFKC_CFImpl(UErrorCode &errorCode);
748
749 // Get the Impl instance of the Normalizer2.
750 // Must be used only when it is known that norm2 is a Normalizer2WithImpl instance.
751 static const Normalizer2Impl *getImpl(const Normalizer2 *norm2);
752private:
753 Normalizer2Factory(); // No instantiation.
754};
755
756U_NAMESPACE_END
757
758U_CAPI int32_t U_EXPORT2
759unorm2_swap(const UDataSwapper *ds,
760 const void *inData, int32_t length, void *outData,
761 UErrorCode *pErrorCode);
762
763/**
764 * Get the NF*_QC property for a code point, for u_getIntPropertyValue().
765 * @internal
766 */
767U_CFUNC UNormalizationCheckResult
768unorm_getQuickCheck(UChar32 c, UNormalizationMode mode);
769
770/**
771 * Gets the 16-bit FCD value (lead & trail CCs) for a code point, for u_getIntPropertyValue().
772 * @internal
773 */
774U_CFUNC uint16_t
775unorm_getFCD16(UChar32 c);
776
777/**
778 * Format of Normalizer2 .nrm data files.
779 * Format version 4.0.
780 *
781 * Normalizer2 .nrm data files provide data for the Unicode Normalization algorithms.
782 * ICU ships with data files for standard Unicode Normalization Forms
783 * NFC and NFD (nfc.nrm), NFKC and NFKD (nfkc.nrm) and NFKC_Casefold (nfkc_cf.nrm).
784 * Custom (application-specific) data can be built into additional .nrm files
785 * with the gennorm2 build tool.
786 * ICU ships with one such file, uts46.nrm, for the implementation of UTS #46.
787 *
788 * Normalizer2.getInstance() causes a .nrm file to be loaded, unless it has been
789 * cached already. Internally, Normalizer2Impl.load() reads the .nrm file.
790 *
791 * A .nrm file begins with a standard ICU data file header
792 * (DataHeader, see ucmndata.h and unicode/udata.h).
793 * The UDataInfo.dataVersion field usually contains the Unicode version
794 * for which the data was generated.
795 *
796 * After the header, the file contains the following parts.
797 * Constants are defined as enum values of the Normalizer2Impl class.
798 *
799 * Many details of the data structures are described in the design doc
800 * which is at http://site.icu-project.org/design/normalization/custom
801 *
802 * int32_t indexes[indexesLength]; -- indexesLength=indexes[IX_NORM_TRIE_OFFSET]/4;
803 *
804 * The first eight indexes are byte offsets in ascending order.
805 * Each byte offset marks the start of the next part in the data file,
806 * and the end of the previous one.
807 * When two consecutive byte offsets are the same, then the corresponding part is empty.
808 * Byte offsets are offsets from after the header,
809 * that is, from the beginning of the indexes[].
810 * Each part starts at an offset with proper alignment for its data.
811 * If necessary, the previous part may include padding bytes to achieve this alignment.
812 *
813 * minDecompNoCP=indexes[IX_MIN_DECOMP_NO_CP] is the lowest code point
814 * with a decomposition mapping, that is, with NF*D_QC=No.
815 * minCompNoMaybeCP=indexes[IX_MIN_COMP_NO_MAYBE_CP] is the lowest code point
816 * with NF*C_QC=No (has a one-way mapping) or Maybe (combines backward).
817 * minLcccCP=indexes[IX_MIN_LCCC_CP] (index 18, new in formatVersion 3)
818 * is the lowest code point with lccc!=0.
819 *
820 * The next eight indexes are thresholds of 16-bit trie values for ranges of
821 * values indicating multiple normalization properties.
822 * They are listed here in threshold order, not in the order they are stored in the indexes.
823 * minYesNo=indexes[IX_MIN_YES_NO];
824 * minYesNoMappingsOnly=indexes[IX_MIN_YES_NO_MAPPINGS_ONLY];
825 * minNoNo=indexes[IX_MIN_NO_NO];
826 * minNoNoCompBoundaryBefore=indexes[IX_MIN_NO_NO_COMP_BOUNDARY_BEFORE];
827 * minNoNoCompNoMaybeCC=indexes[IX_MIN_NO_NO_COMP_NO_MAYBE_CC];
828 * minNoNoEmpty=indexes[IX_MIN_NO_NO_EMPTY];
829 * limitNoNo=indexes[IX_LIMIT_NO_NO];
830 * minMaybeYes=indexes[IX_MIN_MAYBE_YES];
831 * See the normTrie description below and the design doc for details.
832 *
833 * UCPTrie normTrie; -- see ucptrie_impl.h and ucptrie.h, same as Java CodePointTrie
834 *
835 * The trie holds the main normalization data. Each code point is mapped to a 16-bit value.
836 * Rather than using independent bits in the value (which would require more than 16 bits),
837 * information is extracted primarily via range checks.
838 * Except, format version 3 uses bit 0 for hasCompBoundaryAfter().
839 * For example, a 16-bit value norm16 in the range minYesNo<=norm16<minNoNo
840 * means that the character has NF*C_QC=Yes and NF*D_QC=No properties,
841 * which means it has a two-way (round-trip) decomposition mapping.
842 * Values in the range 2<=norm16<limitNoNo are also directly indexes into the extraData
843 * pointing to mappings, compositions lists, or both.
844 * Value norm16==INERT (0 in versions 1 & 2, 1 in version 3)
845 * means that the character is normalization-inert, that is,
846 * it does not have a mapping, does not participate in composition, has a zero
847 * canonical combining class, and forms a boundary where text before it and after it
848 * can be normalized independently.
849 * For details about how multiple properties are encoded in 16-bit values
850 * see the design doc.
851 * Note that the encoding cannot express all combinations of the properties involved;
852 * it only supports those combinations that are allowed by
853 * the Unicode Normalization algorithms. Details are in the design doc as well.
854 * The gennorm2 tool only builds .nrm files for data that conforms to the limitations.
855 *
856 * The trie has a value for each lead surrogate code unit representing the "worst case"
857 * properties of the 1024 supplementary characters whose UTF-16 form starts with
858 * the lead surrogate. If all of the 1024 supplementary characters are normalization-inert,
859 * then their lead surrogate code unit has the trie value INERT.
860 * When the lead surrogate unit's value exceeds the quick check minimum during processing,
861 * the properties for the full supplementary code point need to be looked up.
862 *
863 * uint16_t maybeYesCompositions[MIN_NORMAL_MAYBE_YES-minMaybeYes];
864 * uint16_t extraData[];
865 *
866 * There is only one byte offset for the end of these two arrays.
867 * The split between them is given by the constant and variable mentioned above.
868 * In version 3, the difference must be shifted right by OFFSET_SHIFT.
869 *
870 * The maybeYesCompositions array contains compositions lists for characters that
871 * combine both forward (as starters in composition pairs)
872 * and backward (as trailing characters in composition pairs).
873 * Such characters do not occur in Unicode 5.2 but are allowed by
874 * the Unicode Normalization algorithms.
875 * If there are no such characters, then minMaybeYes==MIN_NORMAL_MAYBE_YES
876 * and the maybeYesCompositions array is empty.
877 * If there are such characters, then minMaybeYes is subtracted from their norm16 values
878 * to get the index into this array.
879 *
880 * The extraData array contains compositions lists for "YesYes" characters,
881 * followed by mappings and optional compositions lists for "YesNo" characters,
882 * followed by only mappings for "NoNo" characters.
883 * (Referring to pairs of NFC/NFD quick check values.)
884 * The norm16 values of those characters are directly indexes into the extraData array.
885 * In version 3, the norm16 values must be shifted right by OFFSET_SHIFT
886 * for accessing extraData.
887 *
888 * The data structures for compositions lists and mappings are described in the design doc.
889 *
890 * uint8_t smallFCD[0x100]; -- new in format version 2
891 *
892 * This is a bit set to help speed up FCD value lookups in the absence of a full
893 * UTrie2 or other large data structure with the full FCD value mapping.
894 *
895 * Each smallFCD bit is set if any of the corresponding 32 BMP code points
896 * has a non-zero FCD value (lccc!=0 or tccc!=0).
897 * Bit 0 of smallFCD[0] is for U+0000..U+001F. Bit 7 of smallFCD[0xff] is for U+FFE0..U+FFFF.
898 * A bit for 32 lead surrogates is set if any of the 32k corresponding
899 * _supplementary_ code points has a non-zero FCD value.
900 *
901 * This bit set is most useful for the large blocks of CJK characters with FCD=0.
902 *
903 * Changes from format version 1 to format version 2 ---------------------------
904 *
905 * - Addition of data for raw (not recursively decomposed) mappings.
906 * + The MAPPING_NO_COMP_BOUNDARY_AFTER bit in the extraData is now also set when
907 * the mapping is to an empty string or when the character combines-forward.
908 * This subsumes the one actual use of the MAPPING_PLUS_COMPOSITION_LIST bit which
909 * is then repurposed for the MAPPING_HAS_RAW_MAPPING bit.
910 * + For details see the design doc.
911 * - Addition of indexes[IX_MIN_YES_NO_MAPPINGS_ONLY] and separation of the yesNo extraData into
912 * distinct ranges (combines-forward vs. not)
913 * so that a range check can be used to find out if there is a compositions list.
914 * This is fully equivalent with formatVersion 1's MAPPING_PLUS_COMPOSITION_LIST flag.
915 * It is needed for the new (in ICU 49) composePair(), not for other normalization.
916 * - Addition of the smallFCD[] bit set.
917 *
918 * Changes from format version 2 to format version 3 (ICU 60) ------------------
919 *
920 * - norm16 bit 0 indicates hasCompBoundaryAfter(),
921 * except that for contiguous composition (FCC) the tccc must be checked as well.
922 * Data indexes and ccc values are shifted left by one (OFFSET_SHIFT).
923 * Thresholds like minNoNo are tested before shifting.
924 *
925 * - Algorithmic mapping deltas are shifted left by two more bits (total DELTA_SHIFT),
926 * to make room for two bits (three values) indicating whether the tccc is 0, 1, or greater.
927 * See DELTA_TCCC_MASK etc.
928 * This helps with fetching tccc/FCD values and FCC hasCompBoundaryAfter().
929 * minMaybeYes is 8-aligned so that the DELTA_TCCC_MASK bits can be tested directly.
930 *
931 * - Algorithmic mappings are only used for mapping to "comp yes and ccc=0" characters,
932 * and ASCII characters are mapped algorithmically only to other ASCII characters.
933 * This helps with hasCompBoundaryBefore() and compose() fast paths.
934 * It is never necessary any more to loop for algorithmic mappings.
935 *
936 * - Addition of indexes[IX_MIN_NO_NO_COMP_BOUNDARY_BEFORE],
937 * indexes[IX_MIN_NO_NO_COMP_NO_MAYBE_CC], and indexes[IX_MIN_NO_NO_EMPTY],
938 * and separation of the noNo extraData into distinct ranges.
939 * With this, the noNo norm16 value indicates whether the mapping is
940 * compose-normalized, not normalized but hasCompBoundaryBefore(),
941 * not even that, or maps to an empty string.
942 * hasCompBoundaryBefore() can be determined solely from the norm16 value.
943 *
944 * - The norm16 value for Hangul LVT is now different from that for Hangul LV,
945 * so that hasCompBoundaryAfter() need not check for the syllable type.
946 * For Hangul LV, minYesNo continues to be used (no comp-boundary-after).
947 * For Hangul LVT, minYesNoMappingsOnly|HAS_COMP_BOUNDARY_AFTER is used.
948 * The extraData units at these indexes are set to firstUnit=2 and firstUnit=3, respectively,
949 * to simplify some code.
950 *
951 * - The extraData firstUnit bit 5 is no longer necessary
952 * (norm16 bit 0 used instead of firstUnit MAPPING_NO_COMP_BOUNDARY_AFTER),
953 * is reserved again, and always set to 0.
954 *
955 * - Addition of indexes[IX_MIN_LCCC_CP], the first code point where lccc!=0.
956 * This used to be hardcoded to U+0300, but in data like NFKC_Casefold it is lower:
957 * U+00AD Soft Hyphen maps to an empty string,
958 * which is artificially assigned "worst case" values lccc=1 and tccc=255.
959 *
960 * - A mapping to an empty string has explicit lccc=1 and tccc=255 values.
961 *
962 * Changes from format version 3 to format version 4 (ICU 63) ------------------
963 *
964 * Switched from UTrie2 to UCPTrie/CodePointTrie.
965 *
966 * The new trie no longer stores different values for surrogate code *units* vs.
967 * surrogate code *points*.
968 * Lead surrogates still have values for optimized UTF-16 string processing.
969 * When looking up code point properties, the code now checks for lead surrogates and
970 * treats them as inert.
971 *
972 * gennorm2 now has to reject mappings for surrogate code points.
973 * UTS #46 maps unpaired surrogates to U+FFFD in code rather than via its
974 * custom normalization data file.
975 */
976
977#endif /* !UCONFIG_NO_NORMALIZATION */
978#endif /* __NORMALIZER2IMPL_H__ */
979