normalizer2impl.cpp 108 KB

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