normalizer2impl.cpp 106 KB

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