caniter.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. // © 2016 and later: Unicode, Inc. and others.
  2. // License & terms of use: http://www.unicode.org/copyright.html
  3. /*
  4. *****************************************************************************
  5. * Copyright (C) 1996-2015, International Business Machines Corporation and
  6. * others. All Rights Reserved.
  7. *****************************************************************************
  8. */
  9. #include "unicode/utypes.h"
  10. #if !UCONFIG_NO_NORMALIZATION
  11. #include "unicode/caniter.h"
  12. #include "unicode/normalizer2.h"
  13. #include "unicode/uchar.h"
  14. #include "unicode/uniset.h"
  15. #include "unicode/usetiter.h"
  16. #include "unicode/ustring.h"
  17. #include "unicode/utf16.h"
  18. #include "cmemory.h"
  19. #include "hash.h"
  20. #include "normalizer2impl.h"
  21. /**
  22. * This class allows one to iterate through all the strings that are canonically equivalent to a given
  23. * string. For example, here are some sample results:
  24. Results for: {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA}
  25. 1: \u0041\u030A\u0064\u0307\u0327
  26. = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA}
  27. 2: \u0041\u030A\u0064\u0327\u0307
  28. = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D}{COMBINING CEDILLA}{COMBINING DOT ABOVE}
  29. 3: \u0041\u030A\u1E0B\u0327
  30. = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D WITH DOT ABOVE}{COMBINING CEDILLA}
  31. 4: \u0041\u030A\u1E11\u0307
  32. = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D WITH CEDILLA}{COMBINING DOT ABOVE}
  33. 5: \u00C5\u0064\u0307\u0327
  34. = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA}
  35. 6: \u00C5\u0064\u0327\u0307
  36. = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D}{COMBINING CEDILLA}{COMBINING DOT ABOVE}
  37. 7: \u00C5\u1E0B\u0327
  38. = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D WITH DOT ABOVE}{COMBINING CEDILLA}
  39. 8: \u00C5\u1E11\u0307
  40. = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D WITH CEDILLA}{COMBINING DOT ABOVE}
  41. 9: \u212B\u0064\u0307\u0327
  42. = {ANGSTROM SIGN}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA}
  43. 10: \u212B\u0064\u0327\u0307
  44. = {ANGSTROM SIGN}{LATIN SMALL LETTER D}{COMBINING CEDILLA}{COMBINING DOT ABOVE}
  45. 11: \u212B\u1E0B\u0327
  46. = {ANGSTROM SIGN}{LATIN SMALL LETTER D WITH DOT ABOVE}{COMBINING CEDILLA}
  47. 12: \u212B\u1E11\u0307
  48. = {ANGSTROM SIGN}{LATIN SMALL LETTER D WITH CEDILLA}{COMBINING DOT ABOVE}
  49. *<br>Note: the code is intended for use with small strings, and is not suitable for larger ones,
  50. * since it has not been optimized for that situation.
  51. *@author M. Davis
  52. *@draft
  53. */
  54. // public
  55. U_NAMESPACE_BEGIN
  56. // TODO: add boilerplate methods.
  57. UOBJECT_DEFINE_RTTI_IMPLEMENTATION(CanonicalIterator)
  58. /**
  59. *@param source string to get results for
  60. */
  61. CanonicalIterator::CanonicalIterator(const UnicodeString &sourceStr, UErrorCode &status) :
  62. pieces(nullptr),
  63. pieces_length(0),
  64. pieces_lengths(nullptr),
  65. current(nullptr),
  66. current_length(0),
  67. nfd(*Normalizer2::getNFDInstance(status)),
  68. nfcImpl(*Normalizer2Factory::getNFCImpl(status))
  69. {
  70. if(U_SUCCESS(status) && nfcImpl.ensureCanonIterData(status)) {
  71. setSource(sourceStr, status);
  72. }
  73. }
  74. CanonicalIterator::~CanonicalIterator() {
  75. cleanPieces();
  76. }
  77. void CanonicalIterator::cleanPieces() {
  78. int32_t i = 0;
  79. if(pieces != nullptr) {
  80. for(i = 0; i < pieces_length; i++) {
  81. if(pieces[i] != nullptr) {
  82. delete[] pieces[i];
  83. }
  84. }
  85. uprv_free(pieces);
  86. pieces = nullptr;
  87. pieces_length = 0;
  88. }
  89. if(pieces_lengths != nullptr) {
  90. uprv_free(pieces_lengths);
  91. pieces_lengths = nullptr;
  92. }
  93. if(current != nullptr) {
  94. uprv_free(current);
  95. current = nullptr;
  96. current_length = 0;
  97. }
  98. }
  99. /**
  100. *@return gets the source: NOTE: it is the NFD form of source
  101. */
  102. UnicodeString CanonicalIterator::getSource() {
  103. return source;
  104. }
  105. /**
  106. * Resets the iterator so that one can start again from the beginning.
  107. */
  108. void CanonicalIterator::reset() {
  109. done = false;
  110. for (int i = 0; i < current_length; ++i) {
  111. current[i] = 0;
  112. }
  113. }
  114. /**
  115. *@return the next string that is canonically equivalent. The value null is returned when
  116. * the iteration is done.
  117. */
  118. UnicodeString CanonicalIterator::next() {
  119. int32_t i = 0;
  120. if (done) {
  121. buffer.setToBogus();
  122. return buffer;
  123. }
  124. // delete old contents
  125. buffer.remove();
  126. // construct return value
  127. for (i = 0; i < pieces_length; ++i) {
  128. buffer.append(pieces[i][current[i]]);
  129. }
  130. //String result = buffer.toString(); // not needed
  131. // find next value for next time
  132. for (i = current_length - 1; ; --i) {
  133. if (i < 0) {
  134. done = true;
  135. break;
  136. }
  137. current[i]++;
  138. if (current[i] < pieces_lengths[i]) break; // got sequence
  139. current[i] = 0;
  140. }
  141. return buffer;
  142. }
  143. /**
  144. *@param set the source string to iterate against. This allows the same iterator to be used
  145. * while changing the source string, saving object creation.
  146. */
  147. void CanonicalIterator::setSource(const UnicodeString &newSource, UErrorCode &status) {
  148. int32_t list_length = 0;
  149. UChar32 cp = 0;
  150. int32_t start = 0;
  151. int32_t i = 0;
  152. UnicodeString *list = nullptr;
  153. nfd.normalize(newSource, source, status);
  154. if(U_FAILURE(status)) {
  155. return;
  156. }
  157. done = false;
  158. cleanPieces();
  159. // catch degenerate case
  160. if (newSource.length() == 0) {
  161. pieces = (UnicodeString **)uprv_malloc(sizeof(UnicodeString *));
  162. pieces_lengths = (int32_t*)uprv_malloc(1 * sizeof(int32_t));
  163. pieces_length = 1;
  164. current = (int32_t*)uprv_malloc(1 * sizeof(int32_t));
  165. current_length = 1;
  166. if (pieces == nullptr || pieces_lengths == nullptr || current == nullptr) {
  167. status = U_MEMORY_ALLOCATION_ERROR;
  168. goto CleanPartialInitialization;
  169. }
  170. current[0] = 0;
  171. pieces[0] = new UnicodeString[1];
  172. pieces_lengths[0] = 1;
  173. if (pieces[0] == 0) {
  174. status = U_MEMORY_ALLOCATION_ERROR;
  175. goto CleanPartialInitialization;
  176. }
  177. return;
  178. }
  179. list = new UnicodeString[source.length()];
  180. if (list == 0) {
  181. status = U_MEMORY_ALLOCATION_ERROR;
  182. goto CleanPartialInitialization;
  183. }
  184. // i should initially be the number of code units at the
  185. // start of the string
  186. i = U16_LENGTH(source.char32At(0));
  187. // int32_t i = 1;
  188. // find the segments
  189. // This code iterates through the source string and
  190. // extracts segments that end up on a codepoint that
  191. // doesn't start any decompositions. (Analysis is done
  192. // on the NFD form - see above).
  193. for (; i < source.length(); i += U16_LENGTH(cp)) {
  194. cp = source.char32At(i);
  195. if (nfcImpl.isCanonSegmentStarter(cp)) {
  196. source.extract(start, i-start, list[list_length++]); // add up to i
  197. start = i;
  198. }
  199. }
  200. source.extract(start, i-start, list[list_length++]); // add last one
  201. // allocate the arrays, and find the strings that are CE to each segment
  202. pieces = (UnicodeString **)uprv_malloc(list_length * sizeof(UnicodeString *));
  203. pieces_length = list_length;
  204. pieces_lengths = (int32_t*)uprv_malloc(list_length * sizeof(int32_t));
  205. current = (int32_t*)uprv_malloc(list_length * sizeof(int32_t));
  206. current_length = list_length;
  207. if (pieces == nullptr || pieces_lengths == nullptr || current == nullptr) {
  208. status = U_MEMORY_ALLOCATION_ERROR;
  209. goto CleanPartialInitialization;
  210. }
  211. for (i = 0; i < current_length; i++) {
  212. current[i] = 0;
  213. }
  214. // for each segment, get all the combinations that can produce
  215. // it after NFD normalization
  216. for (i = 0; i < pieces_length; ++i) {
  217. //if (PROGRESS) printf("SEGMENT\n");
  218. pieces[i] = getEquivalents(list[i], pieces_lengths[i], status);
  219. }
  220. delete[] list;
  221. return;
  222. // Common section to cleanup all local variables and reset object variables.
  223. CleanPartialInitialization:
  224. if (list != nullptr) {
  225. delete[] list;
  226. }
  227. cleanPieces();
  228. }
  229. /**
  230. * Dumb recursive implementation of permutation.
  231. * TODO: optimize
  232. * @param source the string to find permutations for
  233. * @return the results in a set.
  234. */
  235. void U_EXPORT2 CanonicalIterator::permute(UnicodeString &source, UBool skipZeros, Hashtable *result, UErrorCode &status) {
  236. if(U_FAILURE(status)) {
  237. return;
  238. }
  239. //if (PROGRESS) printf("Permute: %s\n", UToS(Tr(source)));
  240. int32_t i = 0;
  241. // optimization:
  242. // if zero or one character, just return a set with it
  243. // we check for length < 2 to keep from counting code points all the time
  244. if (source.length() <= 2 && source.countChar32() <= 1) {
  245. UnicodeString *toPut = new UnicodeString(source);
  246. /* test for nullptr */
  247. if (toPut == 0) {
  248. status = U_MEMORY_ALLOCATION_ERROR;
  249. return;
  250. }
  251. result->put(source, toPut, status);
  252. return;
  253. }
  254. // otherwise iterate through the string, and recursively permute all the other characters
  255. UChar32 cp;
  256. Hashtable subpermute(status);
  257. if(U_FAILURE(status)) {
  258. return;
  259. }
  260. subpermute.setValueDeleter(uprv_deleteUObject);
  261. for (i = 0; i < source.length(); i += U16_LENGTH(cp)) {
  262. cp = source.char32At(i);
  263. const UHashElement *ne = nullptr;
  264. int32_t el = UHASH_FIRST;
  265. UnicodeString subPermuteString = source;
  266. // optimization:
  267. // if the character is canonical combining class zero,
  268. // don't permute it
  269. if (skipZeros && i != 0 && u_getCombiningClass(cp) == 0) {
  270. //System.out.println("Skipping " + Utility.hex(UTF16.valueOf(source, i)));
  271. continue;
  272. }
  273. subpermute.removeAll();
  274. // see what the permutations of the characters before and after this one are
  275. //Hashtable *subpermute = permute(source.substring(0,i) + source.substring(i + UTF16.getCharCount(cp)));
  276. permute(subPermuteString.remove(i, U16_LENGTH(cp)), skipZeros, &subpermute, status);
  277. /* Test for buffer overflows */
  278. if(U_FAILURE(status)) {
  279. return;
  280. }
  281. // The upper remove is destructive. The question is do we have to make a copy, or we don't care about the contents
  282. // of source at this point.
  283. // prefix this character to all of them
  284. ne = subpermute.nextElement(el);
  285. while (ne != nullptr) {
  286. UnicodeString *permRes = (UnicodeString *)(ne->value.pointer);
  287. UnicodeString *chStr = new UnicodeString(cp);
  288. //test for nullptr
  289. if (chStr == nullptr) {
  290. status = U_MEMORY_ALLOCATION_ERROR;
  291. return;
  292. }
  293. chStr->append(*permRes); //*((UnicodeString *)(ne->value.pointer));
  294. //if (PROGRESS) printf(" Piece: %s\n", UToS(*chStr));
  295. result->put(*chStr, chStr, status);
  296. ne = subpermute.nextElement(el);
  297. }
  298. }
  299. //return result;
  300. }
  301. // privates
  302. // we have a segment, in NFD. Find all the strings that are canonically equivalent to it.
  303. UnicodeString* CanonicalIterator::getEquivalents(const UnicodeString &segment, int32_t &result_len, UErrorCode &status) {
  304. Hashtable result(status);
  305. Hashtable permutations(status);
  306. Hashtable basic(status);
  307. if (U_FAILURE(status)) {
  308. return 0;
  309. }
  310. result.setValueDeleter(uprv_deleteUObject);
  311. permutations.setValueDeleter(uprv_deleteUObject);
  312. basic.setValueDeleter(uprv_deleteUObject);
  313. char16_t USeg[256];
  314. int32_t segLen = segment.extract(USeg, 256, status);
  315. getEquivalents2(&basic, USeg, segLen, status);
  316. // now get all the permutations
  317. // add only the ones that are canonically equivalent
  318. // TODO: optimize by not permuting any class zero.
  319. const UHashElement *ne = nullptr;
  320. int32_t el = UHASH_FIRST;
  321. //Iterator it = basic.iterator();
  322. ne = basic.nextElement(el);
  323. //while (it.hasNext())
  324. while (ne != nullptr) {
  325. //String item = (String) it.next();
  326. UnicodeString item = *((UnicodeString *)(ne->value.pointer));
  327. permutations.removeAll();
  328. permute(item, CANITER_SKIP_ZEROES, &permutations, status);
  329. const UHashElement *ne2 = nullptr;
  330. int32_t el2 = UHASH_FIRST;
  331. //Iterator it2 = permutations.iterator();
  332. ne2 = permutations.nextElement(el2);
  333. //while (it2.hasNext())
  334. while (ne2 != nullptr) {
  335. //String possible = (String) it2.next();
  336. //UnicodeString *possible = new UnicodeString(*((UnicodeString *)(ne2->value.pointer)));
  337. UnicodeString possible(*((UnicodeString *)(ne2->value.pointer)));
  338. UnicodeString attempt;
  339. nfd.normalize(possible, attempt, status);
  340. // TODO: check if operator == is semanticaly the same as attempt.equals(segment)
  341. if (attempt==segment) {
  342. //if (PROGRESS) printf("Adding Permutation: %s\n", UToS(Tr(*possible)));
  343. // TODO: use the hashtable just to catch duplicates - store strings directly (somehow).
  344. result.put(possible, new UnicodeString(possible), status); //add(possible);
  345. } else {
  346. //if (PROGRESS) printf("-Skipping Permutation: %s\n", UToS(Tr(*possible)));
  347. }
  348. ne2 = permutations.nextElement(el2);
  349. }
  350. ne = basic.nextElement(el);
  351. }
  352. /* Test for buffer overflows */
  353. if(U_FAILURE(status)) {
  354. return 0;
  355. }
  356. // convert into a String[] to clean up storage
  357. //String[] finalResult = new String[result.size()];
  358. UnicodeString *finalResult = nullptr;
  359. int32_t resultCount;
  360. if((resultCount = result.count()) != 0) {
  361. finalResult = new UnicodeString[resultCount];
  362. if (finalResult == 0) {
  363. status = U_MEMORY_ALLOCATION_ERROR;
  364. return nullptr;
  365. }
  366. }
  367. else {
  368. status = U_ILLEGAL_ARGUMENT_ERROR;
  369. return nullptr;
  370. }
  371. //result.toArray(finalResult);
  372. result_len = 0;
  373. el = UHASH_FIRST;
  374. ne = result.nextElement(el);
  375. while(ne != nullptr) {
  376. finalResult[result_len++] = *((UnicodeString *)(ne->value.pointer));
  377. ne = result.nextElement(el);
  378. }
  379. return finalResult;
  380. }
  381. Hashtable *CanonicalIterator::getEquivalents2(Hashtable *fillinResult, const char16_t *segment, int32_t segLen, UErrorCode &status) {
  382. if (U_FAILURE(status)) {
  383. return nullptr;
  384. }
  385. //if (PROGRESS) printf("Adding: %s\n", UToS(Tr(segment)));
  386. UnicodeString toPut(segment, segLen);
  387. fillinResult->put(toPut, new UnicodeString(toPut), status);
  388. UnicodeSet starts;
  389. // cycle through all the characters
  390. UChar32 cp;
  391. for (int32_t i = 0; i < segLen; i += U16_LENGTH(cp)) {
  392. // see if any character is at the start of some decomposition
  393. U16_GET(segment, 0, i, segLen, cp);
  394. if (!nfcImpl.getCanonStartSet(cp, starts)) {
  395. continue;
  396. }
  397. // if so, see which decompositions match
  398. UnicodeSetIterator iter(starts);
  399. while (iter.next()) {
  400. UChar32 cp2 = iter.getCodepoint();
  401. Hashtable remainder(status);
  402. remainder.setValueDeleter(uprv_deleteUObject);
  403. if (extract(&remainder, cp2, segment, segLen, i, status) == nullptr) {
  404. continue;
  405. }
  406. // there were some matches, so add all the possibilities to the set.
  407. UnicodeString prefix(segment, i);
  408. prefix += cp2;
  409. int32_t el = UHASH_FIRST;
  410. const UHashElement *ne = remainder.nextElement(el);
  411. while (ne != nullptr) {
  412. UnicodeString item = *((UnicodeString *)(ne->value.pointer));
  413. UnicodeString *toAdd = new UnicodeString(prefix);
  414. /* test for nullptr */
  415. if (toAdd == 0) {
  416. status = U_MEMORY_ALLOCATION_ERROR;
  417. return nullptr;
  418. }
  419. *toAdd += item;
  420. fillinResult->put(*toAdd, toAdd, status);
  421. //if (PROGRESS) printf("Adding: %s\n", UToS(Tr(*toAdd)));
  422. ne = remainder.nextElement(el);
  423. }
  424. }
  425. }
  426. /* Test for buffer overflows */
  427. if(U_FAILURE(status)) {
  428. return nullptr;
  429. }
  430. return fillinResult;
  431. }
  432. /**
  433. * See if the decomposition of cp2 is at segment starting at segmentPos
  434. * (with canonical rearrangement!)
  435. * If so, take the remainder, and return the equivalents
  436. */
  437. Hashtable *CanonicalIterator::extract(Hashtable *fillinResult, UChar32 comp, const char16_t *segment, int32_t segLen, int32_t segmentPos, UErrorCode &status) {
  438. //Hashtable *CanonicalIterator::extract(UChar32 comp, const UnicodeString &segment, int32_t segLen, int32_t segmentPos, UErrorCode &status) {
  439. //if (PROGRESS) printf(" extract: %s, ", UToS(Tr(UnicodeString(comp))));
  440. //if (PROGRESS) printf("%s, %i\n", UToS(Tr(segment)), segmentPos);
  441. if (U_FAILURE(status)) {
  442. return nullptr;
  443. }
  444. UnicodeString temp(comp);
  445. int32_t inputLen=temp.length();
  446. UnicodeString decompString;
  447. nfd.normalize(temp, decompString, status);
  448. if (U_FAILURE(status)) {
  449. return nullptr;
  450. }
  451. if (decompString.isBogus()) {
  452. status = U_MEMORY_ALLOCATION_ERROR;
  453. return nullptr;
  454. }
  455. const char16_t *decomp=decompString.getBuffer();
  456. int32_t decompLen=decompString.length();
  457. // See if it matches the start of segment (at segmentPos)
  458. UBool ok = false;
  459. UChar32 cp;
  460. int32_t decompPos = 0;
  461. UChar32 decompCp;
  462. U16_NEXT(decomp, decompPos, decompLen, decompCp);
  463. int32_t i = segmentPos;
  464. while(i < segLen) {
  465. U16_NEXT(segment, i, segLen, cp);
  466. if (cp == decompCp) { // if equal, eat another cp from decomp
  467. //if (PROGRESS) printf(" matches: %s\n", UToS(Tr(UnicodeString(cp))));
  468. if (decompPos == decompLen) { // done, have all decomp characters!
  469. temp.append(segment+i, segLen-i);
  470. ok = true;
  471. break;
  472. }
  473. U16_NEXT(decomp, decompPos, decompLen, decompCp);
  474. } else {
  475. //if (PROGRESS) printf(" buffer: %s\n", UToS(Tr(UnicodeString(cp))));
  476. // brute force approach
  477. temp.append(cp);
  478. /* TODO: optimize
  479. // since we know that the classes are monotonically increasing, after zero
  480. // e.g. 0 5 7 9 0 3
  481. // we can do an optimization
  482. // there are only a few cases that work: zero, less, same, greater
  483. // if both classes are the same, we fail
  484. // if the decomp class < the segment class, we fail
  485. segClass = getClass(cp);
  486. if (decompClass <= segClass) return null;
  487. */
  488. }
  489. }
  490. if (!ok)
  491. return nullptr; // we failed, characters left over
  492. //if (PROGRESS) printf("Matches\n");
  493. if (inputLen == temp.length()) {
  494. fillinResult->put(UnicodeString(), new UnicodeString(), status);
  495. return fillinResult; // succeed, but no remainder
  496. }
  497. // brute force approach
  498. // check to make sure result is canonically equivalent
  499. UnicodeString trial;
  500. nfd.normalize(temp, trial, status);
  501. if(U_FAILURE(status) || trial.compare(segment+segmentPos, segLen - segmentPos) != 0) {
  502. return nullptr;
  503. }
  504. return getEquivalents2(fillinResult, temp.getBuffer()+inputLen, temp.length()-inputLen, status);
  505. }
  506. U_NAMESPACE_END
  507. #endif /* #if !UCONFIG_NO_NORMALIZATION */