1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
4 *****************************************************************************
5 * Copyright (C) 1996-2015, International Business Machines Corporation and
6 * others. All Rights Reserved.
7 *****************************************************************************
10 #include "unicode/utypes.h"
12 #if !UCONFIG_NO_NORMALIZATION
14 #include "unicode/caniter.h"
15 #include "unicode/normalizer2.h"
16 #include "unicode/uchar.h"
17 #include "unicode/uniset.h"
18 #include "unicode/usetiter.h"
19 #include "unicode/ustring.h"
20 #include "unicode/utf16.h"
23 #include "normalizer2impl.h"
26 * This class allows one to iterate through all the strings that are canonically equivalent to a given
27 * string. For example, here are some sample results:
28 Results for: {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA}
29 1: \u0041\u030A\u0064\u0307\u0327
30 = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA}
31 2: \u0041\u030A\u0064\u0327\u0307
32 = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D}{COMBINING CEDILLA}{COMBINING DOT ABOVE}
33 3: \u0041\u030A\u1E0B\u0327
34 = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D WITH DOT ABOVE}{COMBINING CEDILLA}
35 4: \u0041\u030A\u1E11\u0307
36 = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D WITH CEDILLA}{COMBINING DOT ABOVE}
37 5: \u00C5\u0064\u0307\u0327
38 = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA}
39 6: \u00C5\u0064\u0327\u0307
40 = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D}{COMBINING CEDILLA}{COMBINING DOT ABOVE}
42 = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D WITH DOT ABOVE}{COMBINING CEDILLA}
44 = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D WITH CEDILLA}{COMBINING DOT ABOVE}
45 9: \u212B\u0064\u0307\u0327
46 = {ANGSTROM SIGN}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA}
47 10: \u212B\u0064\u0327\u0307
48 = {ANGSTROM SIGN}{LATIN SMALL LETTER D}{COMBINING CEDILLA}{COMBINING DOT ABOVE}
49 11: \u212B\u1E0B\u0327
50 = {ANGSTROM SIGN}{LATIN SMALL LETTER D WITH DOT ABOVE}{COMBINING CEDILLA}
51 12: \u212B\u1E11\u0307
52 = {ANGSTROM SIGN}{LATIN SMALL LETTER D WITH CEDILLA}{COMBINING DOT ABOVE}
53 *<br>Note: the code is intended for use with small strings, and is not suitable for larger ones,
54 * since it has not been optimized for that situation.
63 // TODO: add boilerplate methods.
65 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(CanonicalIterator
)
68 *@param source string to get results for
70 CanonicalIterator::CanonicalIterator(const UnicodeString
&sourceStr
, UErrorCode
&status
) :
76 nfd(*Normalizer2::getNFDInstance(status
)),
77 nfcImpl(*Normalizer2Factory::getNFCImpl(status
))
79 if(U_SUCCESS(status
) && nfcImpl
.ensureCanonIterData(status
)) {
80 setSource(sourceStr
, status
);
84 CanonicalIterator::~CanonicalIterator() {
88 void CanonicalIterator::cleanPieces() {
91 for(i
= 0; i
< pieces_length
; i
++) {
92 if(pieces
[i
] != NULL
) {
100 if(pieces_lengths
!= NULL
) {
101 uprv_free(pieces_lengths
);
102 pieces_lengths
= NULL
;
104 if(current
!= NULL
) {
112 *@return gets the source: NOTE: it is the NFD form of source
114 UnicodeString
CanonicalIterator::getSource() {
119 * Resets the iterator so that one can start again from the beginning.
121 void CanonicalIterator::reset() {
123 for (int i
= 0; i
< current_length
; ++i
) {
129 *@return the next string that is canonically equivalent. The value null is returned when
130 * the iteration is done.
132 UnicodeString
CanonicalIterator::next() {
140 // delete old contents
143 // construct return value
145 for (i
= 0; i
< pieces_length
; ++i
) {
146 buffer
.append(pieces
[i
][current
[i
]]);
148 //String result = buffer.toString(); // not needed
150 // find next value for next time
152 for (i
= current_length
- 1; ; --i
) {
158 if (current
[i
] < pieces_lengths
[i
]) break; // got sequence
165 *@param set the source string to iterate against. This allows the same iterator to be used
166 * while changing the source string, saving object creation.
168 void CanonicalIterator::setSource(const UnicodeString
&newSource
, UErrorCode
&status
) {
169 int32_t list_length
= 0;
173 UnicodeString
*list
= NULL
;
175 nfd
.normalize(newSource
, source
, status
);
176 if(U_FAILURE(status
)) {
183 // catch degenerate case
184 if (newSource
.length() == 0) {
185 pieces
= (UnicodeString
**)uprv_malloc(sizeof(UnicodeString
*));
186 pieces_lengths
= (int32_t*)uprv_malloc(1 * sizeof(int32_t));
188 current
= (int32_t*)uprv_malloc(1 * sizeof(int32_t));
190 if (pieces
== NULL
|| pieces_lengths
== NULL
|| current
== NULL
) {
191 status
= U_MEMORY_ALLOCATION_ERROR
;
192 goto CleanPartialInitialization
;
195 pieces
[0] = new UnicodeString
[1];
196 pieces_lengths
[0] = 1;
197 if (pieces
[0] == 0) {
198 status
= U_MEMORY_ALLOCATION_ERROR
;
199 goto CleanPartialInitialization
;
205 list
= new UnicodeString
[source
.length()];
207 status
= U_MEMORY_ALLOCATION_ERROR
;
208 goto CleanPartialInitialization
;
211 // i should initialy be the number of code units at the
212 // start of the string
213 i
= U16_LENGTH(source
.char32At(0));
216 // This code iterates through the source string and
217 // extracts segments that end up on a codepoint that
218 // doesn't start any decompositions. (Analysis is done
219 // on the NFD form - see above).
220 for (; i
< source
.length(); i
+= U16_LENGTH(cp
)) {
221 cp
= source
.char32At(i
);
222 if (nfcImpl
.isCanonSegmentStarter(cp
)) {
223 source
.extract(start
, i
-start
, list
[list_length
++]); // add up to i
227 source
.extract(start
, i
-start
, list
[list_length
++]); // add last one
230 // allocate the arrays, and find the strings that are CE to each segment
231 pieces
= (UnicodeString
**)uprv_malloc(list_length
* sizeof(UnicodeString
*));
232 pieces_length
= list_length
;
233 pieces_lengths
= (int32_t*)uprv_malloc(list_length
* sizeof(int32_t));
234 current
= (int32_t*)uprv_malloc(list_length
* sizeof(int32_t));
235 current_length
= list_length
;
236 if (pieces
== NULL
|| pieces_lengths
== NULL
|| current
== NULL
) {
237 status
= U_MEMORY_ALLOCATION_ERROR
;
238 goto CleanPartialInitialization
;
241 for (i
= 0; i
< current_length
; i
++) {
244 // for each segment, get all the combinations that can produce
245 // it after NFD normalization
246 for (i
= 0; i
< pieces_length
; ++i
) {
247 //if (PROGRESS) printf("SEGMENT\n");
248 pieces
[i
] = getEquivalents(list
[i
], pieces_lengths
[i
], status
);
253 // Common section to cleanup all local variables and reset object variables.
254 CleanPartialInitialization
:
262 * Dumb recursive implementation of permutation.
264 * @param source the string to find permutations for
265 * @return the results in a set.
267 void U_EXPORT2
CanonicalIterator::permute(UnicodeString
&source
, UBool skipZeros
, Hashtable
*result
, UErrorCode
&status
) {
268 if(U_FAILURE(status
)) {
271 //if (PROGRESS) printf("Permute: %s\n", UToS(Tr(source)));
275 // if zero or one character, just return a set with it
276 // we check for length < 2 to keep from counting code points all the time
277 if (source
.length() <= 2 && source
.countChar32() <= 1) {
278 UnicodeString
*toPut
= new UnicodeString(source
);
281 status
= U_MEMORY_ALLOCATION_ERROR
;
284 result
->put(source
, toPut
, status
);
288 // otherwise iterate through the string, and recursively permute all the other characters
290 Hashtable
subpermute(status
);
291 if(U_FAILURE(status
)) {
294 subpermute
.setValueDeleter(uprv_deleteUObject
);
296 for (i
= 0; i
< source
.length(); i
+= U16_LENGTH(cp
)) {
297 cp
= source
.char32At(i
);
298 const UHashElement
*ne
= NULL
;
299 int32_t el
= UHASH_FIRST
;
300 UnicodeString subPermuteString
= source
;
303 // if the character is canonical combining class zero,
305 if (skipZeros
&& i
!= 0 && u_getCombiningClass(cp
) == 0) {
306 //System.out.println("Skipping " + Utility.hex(UTF16.valueOf(source, i)));
310 subpermute
.removeAll();
312 // see what the permutations of the characters before and after this one are
313 //Hashtable *subpermute = permute(source.substring(0,i) + source.substring(i + UTF16.getCharCount(cp)));
314 permute(subPermuteString
.remove(i
, U16_LENGTH(cp
)), skipZeros
, &subpermute
, status
);
315 /* Test for buffer overflows */
316 if(U_FAILURE(status
)) {
319 // The upper remove is destructive. The question is do we have to make a copy, or we don't care about the contents
320 // of source at this point.
322 // prefix this character to all of them
323 ne
= subpermute
.nextElement(el
);
325 UnicodeString
*permRes
= (UnicodeString
*)(ne
->value
.pointer
);
326 UnicodeString
*chStr
= new UnicodeString(cp
);
329 status
= U_MEMORY_ALLOCATION_ERROR
;
332 chStr
->append(*permRes
); //*((UnicodeString *)(ne->value.pointer));
333 //if (PROGRESS) printf(" Piece: %s\n", UToS(*chStr));
334 result
->put(*chStr
, chStr
, status
);
335 ne
= subpermute
.nextElement(el
);
343 // we have a segment, in NFD. Find all the strings that are canonically equivalent to it.
344 UnicodeString
* CanonicalIterator::getEquivalents(const UnicodeString
&segment
, int32_t &result_len
, UErrorCode
&status
) {
345 Hashtable
result(status
);
346 Hashtable
permutations(status
);
347 Hashtable
basic(status
);
348 if (U_FAILURE(status
)) {
351 result
.setValueDeleter(uprv_deleteUObject
);
352 permutations
.setValueDeleter(uprv_deleteUObject
);
353 basic
.setValueDeleter(uprv_deleteUObject
);
356 int32_t segLen
= segment
.extract(USeg
, 256, status
);
357 getEquivalents2(&basic
, USeg
, segLen
, status
);
359 // now get all the permutations
360 // add only the ones that are canonically equivalent
361 // TODO: optimize by not permuting any class zero.
363 const UHashElement
*ne
= NULL
;
364 int32_t el
= UHASH_FIRST
;
365 //Iterator it = basic.iterator();
366 ne
= basic
.nextElement(el
);
367 //while (it.hasNext())
369 //String item = (String) it.next();
370 UnicodeString item
= *((UnicodeString
*)(ne
->value
.pointer
));
372 permutations
.removeAll();
373 permute(item
, CANITER_SKIP_ZEROES
, &permutations
, status
);
374 const UHashElement
*ne2
= NULL
;
375 int32_t el2
= UHASH_FIRST
;
376 //Iterator it2 = permutations.iterator();
377 ne2
= permutations
.nextElement(el2
);
378 //while (it2.hasNext())
379 while (ne2
!= NULL
) {
380 //String possible = (String) it2.next();
381 //UnicodeString *possible = new UnicodeString(*((UnicodeString *)(ne2->value.pointer)));
382 UnicodeString
possible(*((UnicodeString
*)(ne2
->value
.pointer
)));
383 UnicodeString attempt
;
384 nfd
.normalize(possible
, attempt
, status
);
386 // TODO: check if operator == is semanticaly the same as attempt.equals(segment)
387 if (attempt
==segment
) {
388 //if (PROGRESS) printf("Adding Permutation: %s\n", UToS(Tr(*possible)));
389 // TODO: use the hashtable just to catch duplicates - store strings directly (somehow).
390 result
.put(possible
, new UnicodeString(possible
), status
); //add(possible);
392 //if (PROGRESS) printf("-Skipping Permutation: %s\n", UToS(Tr(*possible)));
395 ne2
= permutations
.nextElement(el2
);
397 ne
= basic
.nextElement(el
);
400 /* Test for buffer overflows */
401 if(U_FAILURE(status
)) {
404 // convert into a String[] to clean up storage
405 //String[] finalResult = new String[result.size()];
406 UnicodeString
*finalResult
= NULL
;
408 if((resultCount
= result
.count()) != 0) {
409 finalResult
= new UnicodeString
[resultCount
];
410 if (finalResult
== 0) {
411 status
= U_MEMORY_ALLOCATION_ERROR
;
416 status
= U_ILLEGAL_ARGUMENT_ERROR
;
419 //result.toArray(finalResult);
422 ne
= result
.nextElement(el
);
424 finalResult
[result_len
++] = *((UnicodeString
*)(ne
->value
.pointer
));
425 ne
= result
.nextElement(el
);
432 Hashtable
*CanonicalIterator::getEquivalents2(Hashtable
*fillinResult
, const UChar
*segment
, int32_t segLen
, UErrorCode
&status
) {
434 if (U_FAILURE(status
)) {
438 //if (PROGRESS) printf("Adding: %s\n", UToS(Tr(segment)));
440 UnicodeString
toPut(segment
, segLen
);
442 fillinResult
->put(toPut
, new UnicodeString(toPut
), status
);
446 // cycle through all the characters
448 for (int32_t i
= 0; i
< segLen
; i
+= U16_LENGTH(cp
)) {
449 // see if any character is at the start of some decomposition
450 U16_GET(segment
, 0, i
, segLen
, cp
);
451 if (!nfcImpl
.getCanonStartSet(cp
, starts
)) {
454 // if so, see which decompositions match
455 UnicodeSetIterator
iter(starts
);
456 while (iter
.next()) {
457 UChar32 cp2
= iter
.getCodepoint();
458 Hashtable
remainder(status
);
459 remainder
.setValueDeleter(uprv_deleteUObject
);
460 if (extract(&remainder
, cp2
, segment
, segLen
, i
, status
) == NULL
) {
464 // there were some matches, so add all the possibilities to the set.
465 UnicodeString
prefix(segment
, i
);
468 int32_t el
= UHASH_FIRST
;
469 const UHashElement
*ne
= remainder
.nextElement(el
);
471 UnicodeString item
= *((UnicodeString
*)(ne
->value
.pointer
));
472 UnicodeString
*toAdd
= new UnicodeString(prefix
);
475 status
= U_MEMORY_ALLOCATION_ERROR
;
479 fillinResult
->put(*toAdd
, toAdd
, status
);
481 //if (PROGRESS) printf("Adding: %s\n", UToS(Tr(*toAdd)));
483 ne
= remainder
.nextElement(el
);
488 /* Test for buffer overflows */
489 if(U_FAILURE(status
)) {
496 * See if the decomposition of cp2 is at segment starting at segmentPos
497 * (with canonical rearrangment!)
498 * If so, take the remainder, and return the equivalents
500 Hashtable
*CanonicalIterator::extract(Hashtable
*fillinResult
, UChar32 comp
, const UChar
*segment
, int32_t segLen
, int32_t segmentPos
, UErrorCode
&status
) {
501 //Hashtable *CanonicalIterator::extract(UChar32 comp, const UnicodeString &segment, int32_t segLen, int32_t segmentPos, UErrorCode &status) {
502 //if (PROGRESS) printf(" extract: %s, ", UToS(Tr(UnicodeString(comp))));
503 //if (PROGRESS) printf("%s, %i\n", UToS(Tr(segment)), segmentPos);
505 if (U_FAILURE(status
)) {
509 UnicodeString
temp(comp
);
510 int32_t inputLen
=temp
.length();
511 UnicodeString decompString
;
512 nfd
.normalize(temp
, decompString
, status
);
513 if (U_FAILURE(status
)) {
516 if (decompString
.isBogus()) {
517 status
= U_MEMORY_ALLOCATION_ERROR
;
520 const UChar
*decomp
=decompString
.getBuffer();
521 int32_t decompLen
=decompString
.length();
523 // See if it matches the start of segment (at segmentPos)
526 int32_t decompPos
= 0;
528 U16_NEXT(decomp
, decompPos
, decompLen
, decompCp
);
530 int32_t i
= segmentPos
;
532 U16_NEXT(segment
, i
, segLen
, cp
);
534 if (cp
== decompCp
) { // if equal, eat another cp from decomp
536 //if (PROGRESS) printf(" matches: %s\n", UToS(Tr(UnicodeString(cp))));
538 if (decompPos
== decompLen
) { // done, have all decomp characters!
539 temp
.append(segment
+i
, segLen
-i
);
543 U16_NEXT(decomp
, decompPos
, decompLen
, decompCp
);
545 //if (PROGRESS) printf(" buffer: %s\n", UToS(Tr(UnicodeString(cp))));
547 // brute force approach
551 // since we know that the classes are monotonically increasing, after zero
553 // we can do an optimization
554 // there are only a few cases that work: zero, less, same, greater
555 // if both classes are the same, we fail
556 // if the decomp class < the segment class, we fail
558 segClass = getClass(cp);
559 if (decompClass <= segClass) return null;
564 return NULL
; // we failed, characters left over
566 //if (PROGRESS) printf("Matches\n");
568 if (inputLen
== temp
.length()) {
569 fillinResult
->put(UnicodeString(), new UnicodeString(), status
);
570 return fillinResult
; // succeed, but no remainder
573 // brute force approach
574 // check to make sure result is canonically equivalent
576 nfd
.normalize(temp
, trial
, status
);
577 if(U_FAILURE(status
) || trial
.compare(segment
+segmentPos
, segLen
- segmentPos
) != 0) {
581 return getEquivalents2(fillinResult
, temp
.getBuffer()+inputLen
, temp
.length()-inputLen
, status
);
586 #endif /* #if !UCONFIG_NO_NORMALIZATION */