uniset.cpp 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356
  1. // © 2016 and later: Unicode, Inc. and others.
  2. // License & terms of use: http://www.unicode.org/copyright.html
  3. /*
  4. **********************************************************************
  5. * Copyright (C) 1999-2015, International Business Machines
  6. * Corporation and others. All Rights Reserved.
  7. **********************************************************************
  8. * Date Name Description
  9. * 10/20/99 alan Creation.
  10. **********************************************************************
  11. */
  12. #include "unicode/utypes.h"
  13. #include "unicode/parsepos.h"
  14. #include "unicode/symtable.h"
  15. #include "unicode/uniset.h"
  16. #include "unicode/ustring.h"
  17. #include "unicode/utf8.h"
  18. #include "unicode/utf16.h"
  19. #include "ruleiter.h"
  20. #include "cmemory.h"
  21. #include "cstring.h"
  22. #include "patternprops.h"
  23. #include "uelement.h"
  24. #include "util.h"
  25. #include "uvector.h"
  26. #include "charstr.h"
  27. #include "ustrfmt.h"
  28. #include "uassert.h"
  29. #include "bmpset.h"
  30. #include "unisetspan.h"
  31. // HIGH_VALUE > all valid values. 110000 for codepoints
  32. #define UNICODESET_HIGH 0x0110000
  33. // LOW <= all valid values. ZERO for codepoints
  34. #define UNICODESET_LOW 0x000000
  35. /** Max list [0, 1, 2, ..., max code point, HIGH] */
  36. constexpr int32_t MAX_LENGTH = UNICODESET_HIGH + 1;
  37. U_NAMESPACE_BEGIN
  38. SymbolTable::~SymbolTable() {}
  39. UOBJECT_DEFINE_RTTI_IMPLEMENTATION(UnicodeSet)
  40. /**
  41. * Modify the given UChar32 variable so that it is in range, by
  42. * pinning values < UNICODESET_LOW to UNICODESET_LOW, and
  43. * pinning values > UNICODESET_HIGH-1 to UNICODESET_HIGH-1.
  44. * It modifies its argument in-place and also returns it.
  45. */
  46. static inline UChar32 pinCodePoint(UChar32& c) {
  47. if (c < UNICODESET_LOW) {
  48. c = UNICODESET_LOW;
  49. } else if (c > (UNICODESET_HIGH-1)) {
  50. c = (UNICODESET_HIGH-1);
  51. }
  52. return c;
  53. }
  54. //----------------------------------------------------------------
  55. // Debugging
  56. //----------------------------------------------------------------
  57. // DO NOT DELETE THIS CODE. This code is used to debug memory leaks.
  58. // To enable the debugging, define the symbol DEBUG_MEM in the line
  59. // below. This will result in text being sent to stdout that looks
  60. // like this:
  61. // DEBUG UnicodeSet: ct 0x00A39B20; 397 [\u0A81-\u0A83\u0A85-
  62. // DEBUG UnicodeSet: dt 0x00A39B20; 396 [\u0A81-\u0A83\u0A85-
  63. // Each line lists a construction (ct) or destruction (dt) event, the
  64. // object address, the number of outstanding objects after the event,
  65. // and the pattern of the object in question.
  66. // #define DEBUG_MEM
  67. #ifdef DEBUG_MEM
  68. #include <stdio.h>
  69. static int32_t _dbgCount = 0;
  70. static inline void _dbgct(UnicodeSet* set) {
  71. UnicodeString str;
  72. set->toPattern(str, true);
  73. char buf[40];
  74. str.extract(0, 39, buf, "");
  75. printf("DEBUG UnicodeSet: ct 0x%08X; %d %s\n", set, ++_dbgCount, buf);
  76. }
  77. static inline void _dbgdt(UnicodeSet* set) {
  78. UnicodeString str;
  79. set->toPattern(str, true);
  80. char buf[40];
  81. str.extract(0, 39, buf, "");
  82. printf("DEBUG UnicodeSet: dt 0x%08X; %d %s\n", set, --_dbgCount, buf);
  83. }
  84. #else
  85. #define _dbgct(set)
  86. #define _dbgdt(set)
  87. #endif
  88. //----------------------------------------------------------------
  89. // UnicodeString in UVector support
  90. //----------------------------------------------------------------
  91. static void U_CALLCONV cloneUnicodeString(UElement *dst, UElement *src) {
  92. dst->pointer = new UnicodeString(*(UnicodeString*)src->pointer);
  93. }
  94. static int32_t U_CALLCONV compareUnicodeString(UElement t1, UElement t2) {
  95. const UnicodeString &a = *(const UnicodeString*)t1.pointer;
  96. const UnicodeString &b = *(const UnicodeString*)t2.pointer;
  97. return a.compare(b);
  98. }
  99. UBool UnicodeSet::hasStrings() const {
  100. return strings != nullptr && !strings->isEmpty();
  101. }
  102. int32_t UnicodeSet::stringsSize() const {
  103. return strings == nullptr ? 0 : strings->size();
  104. }
  105. UBool UnicodeSet::stringsContains(const UnicodeString &s) const {
  106. return strings != nullptr && strings->contains((void*) &s);
  107. }
  108. //----------------------------------------------------------------
  109. // Constructors &c
  110. //----------------------------------------------------------------
  111. /**
  112. * Constructs an empty set.
  113. */
  114. UnicodeSet::UnicodeSet() {
  115. list[0] = UNICODESET_HIGH;
  116. _dbgct(this);
  117. }
  118. /**
  119. * Constructs a set containing the given range. If <code>end >
  120. * start</code> then an empty set is created.
  121. *
  122. * @param start first character, inclusive, of range
  123. * @param end last character, inclusive, of range
  124. */
  125. UnicodeSet::UnicodeSet(UChar32 start, UChar32 end) {
  126. list[0] = UNICODESET_HIGH;
  127. add(start, end);
  128. _dbgct(this);
  129. }
  130. /**
  131. * Constructs a set that is identical to the given UnicodeSet.
  132. */
  133. UnicodeSet::UnicodeSet(const UnicodeSet& o) : UnicodeFilter(o) {
  134. *this = o;
  135. _dbgct(this);
  136. }
  137. // Copy-construct as thawed.
  138. UnicodeSet::UnicodeSet(const UnicodeSet& o, UBool /* asThawed */) : UnicodeFilter(o) {
  139. if (ensureCapacity(o.len)) {
  140. // *this = o except for bmpSet and stringSpan
  141. len = o.len;
  142. uprv_memcpy(list, o.list, (size_t)len*sizeof(UChar32));
  143. if (o.hasStrings()) {
  144. UErrorCode status = U_ZERO_ERROR;
  145. if (!allocateStrings(status) ||
  146. (strings->assign(*o.strings, cloneUnicodeString, status), U_FAILURE(status))) {
  147. setToBogus();
  148. return;
  149. }
  150. }
  151. if (o.pat) {
  152. setPattern(o.pat, o.patLen);
  153. }
  154. _dbgct(this);
  155. }
  156. }
  157. /**
  158. * Destructs the set.
  159. */
  160. UnicodeSet::~UnicodeSet() {
  161. _dbgdt(this); // first!
  162. if (list != stackList) {
  163. uprv_free(list);
  164. }
  165. delete bmpSet;
  166. if (buffer != stackList) {
  167. uprv_free(buffer);
  168. }
  169. delete strings;
  170. delete stringSpan;
  171. releasePattern();
  172. }
  173. /**
  174. * Assigns this object to be a copy of another.
  175. */
  176. UnicodeSet& UnicodeSet::operator=(const UnicodeSet& o) {
  177. return copyFrom(o, false);
  178. }
  179. UnicodeSet& UnicodeSet::copyFrom(const UnicodeSet& o, UBool asThawed) {
  180. if (this == &o) {
  181. return *this;
  182. }
  183. if (isFrozen()) {
  184. return *this;
  185. }
  186. if (o.isBogus()) {
  187. setToBogus();
  188. return *this;
  189. }
  190. if (!ensureCapacity(o.len)) {
  191. // ensureCapacity will mark the UnicodeSet as Bogus if OOM failure happens.
  192. return *this;
  193. }
  194. len = o.len;
  195. uprv_memcpy(list, o.list, (size_t)len*sizeof(UChar32));
  196. if (o.bmpSet != nullptr && !asThawed) {
  197. bmpSet = new BMPSet(*o.bmpSet, list, len);
  198. if (bmpSet == nullptr) { // Check for memory allocation error.
  199. setToBogus();
  200. return *this;
  201. }
  202. }
  203. if (o.hasStrings()) {
  204. UErrorCode status = U_ZERO_ERROR;
  205. if ((strings == nullptr && !allocateStrings(status)) ||
  206. (strings->assign(*o.strings, cloneUnicodeString, status), U_FAILURE(status))) {
  207. setToBogus();
  208. return *this;
  209. }
  210. } else if (hasStrings()) {
  211. strings->removeAllElements();
  212. }
  213. if (o.stringSpan != nullptr && !asThawed) {
  214. stringSpan = new UnicodeSetStringSpan(*o.stringSpan, *strings);
  215. if (stringSpan == nullptr) { // Check for memory allocation error.
  216. setToBogus();
  217. return *this;
  218. }
  219. }
  220. releasePattern();
  221. if (o.pat) {
  222. setPattern(o.pat, o.patLen);
  223. }
  224. return *this;
  225. }
  226. /**
  227. * Returns a copy of this object. All UnicodeMatcher objects have
  228. * to support cloning in order to allow classes using
  229. * UnicodeMatchers, such as Transliterator, to implement cloning.
  230. */
  231. UnicodeSet* UnicodeSet::clone() const {
  232. return new UnicodeSet(*this);
  233. }
  234. UnicodeSet *UnicodeSet::cloneAsThawed() const {
  235. return new UnicodeSet(*this, true);
  236. }
  237. /**
  238. * Compares the specified object with this set for equality. Returns
  239. * <tt>true</tt> if the two sets
  240. * have the same size, and every member of the specified set is
  241. * contained in this set (or equivalently, every member of this set is
  242. * contained in the specified set).
  243. *
  244. * @param o set to be compared for equality with this set.
  245. * @return <tt>true</tt> if the specified set is equal to this set.
  246. */
  247. bool UnicodeSet::operator==(const UnicodeSet& o) const {
  248. if (len != o.len) return false;
  249. for (int32_t i = 0; i < len; ++i) {
  250. if (list[i] != o.list[i]) return false;
  251. }
  252. if (hasStrings() != o.hasStrings()) { return false; }
  253. if (hasStrings() && *strings != *o.strings) return false;
  254. return true;
  255. }
  256. /**
  257. * Returns the hash code value for this set.
  258. *
  259. * @return the hash code value for this set.
  260. * @see Object#hashCode()
  261. */
  262. int32_t UnicodeSet::hashCode() const {
  263. uint32_t result = static_cast<uint32_t>(len);
  264. for (int32_t i = 0; i < len; ++i) {
  265. result *= 1000003u;
  266. result += list[i];
  267. }
  268. return static_cast<int32_t>(result);
  269. }
  270. //----------------------------------------------------------------
  271. // Public API
  272. //----------------------------------------------------------------
  273. /**
  274. * Returns the number of elements in this set (its cardinality),
  275. * Note than the elements of a set may include both individual
  276. * codepoints and strings.
  277. *
  278. * @return the number of elements in this set (its cardinality).
  279. */
  280. int32_t UnicodeSet::size() const {
  281. int32_t n = 0;
  282. int32_t count = getRangeCount();
  283. for (int32_t i = 0; i < count; ++i) {
  284. n += getRangeEnd(i) - getRangeStart(i) + 1;
  285. }
  286. return n + stringsSize();
  287. }
  288. /**
  289. * Returns <tt>true</tt> if this set contains no elements.
  290. *
  291. * @return <tt>true</tt> if this set contains no elements.
  292. */
  293. UBool UnicodeSet::isEmpty() const {
  294. return len == 1 && !hasStrings();
  295. }
  296. /**
  297. * Returns true if this set contains the given character.
  298. * @param c character to be checked for containment
  299. * @return true if the test condition is met
  300. */
  301. UBool UnicodeSet::contains(UChar32 c) const {
  302. // Set i to the index of the start item greater than ch
  303. // We know we will terminate without length test!
  304. // LATER: for large sets, add binary search
  305. //int32_t i = -1;
  306. //for (;;) {
  307. // if (c < list[++i]) break;
  308. //}
  309. if (bmpSet != nullptr) {
  310. return bmpSet->contains(c);
  311. }
  312. if (stringSpan != nullptr) {
  313. return stringSpan->contains(c);
  314. }
  315. if (c >= UNICODESET_HIGH) { // Don't need to check LOW bound
  316. return false;
  317. }
  318. int32_t i = findCodePoint(c);
  319. return (UBool)(i & 1); // return true if odd
  320. }
  321. /**
  322. * Returns the smallest value i such that c < list[i]. Caller
  323. * must ensure that c is a legal value or this method will enter
  324. * an infinite loop. This method performs a binary search.
  325. * @param c a character in the range MIN_VALUE..MAX_VALUE
  326. * inclusive
  327. * @return the smallest integer i in the range 0..len-1,
  328. * inclusive, such that c < list[i]
  329. */
  330. int32_t UnicodeSet::findCodePoint(UChar32 c) const {
  331. /* Examples:
  332. findCodePoint(c)
  333. set list[] c=0 1 3 4 7 8
  334. === ============== ===========
  335. [] [110000] 0 0 0 0 0 0
  336. [\u0000-\u0003] [0, 4, 110000] 1 1 1 2 2 2
  337. [\u0004-\u0007] [4, 8, 110000] 0 0 0 1 1 2
  338. [:Any:] [0, 110000] 1 1 1 1 1 1
  339. */
  340. // Return the smallest i such that c < list[i]. Assume
  341. // list[len - 1] == HIGH and that c is legal (0..HIGH-1).
  342. if (c < list[0])
  343. return 0;
  344. // High runner test. c is often after the last range, so an
  345. // initial check for this condition pays off.
  346. int32_t lo = 0;
  347. int32_t hi = len - 1;
  348. if (lo >= hi || c >= list[hi-1])
  349. return hi;
  350. // invariant: c >= list[lo]
  351. // invariant: c < list[hi]
  352. for (;;) {
  353. int32_t i = (lo + hi) >> 1;
  354. if (i == lo) {
  355. break; // Found!
  356. } else if (c < list[i]) {
  357. hi = i;
  358. } else {
  359. lo = i;
  360. }
  361. }
  362. return hi;
  363. }
  364. /**
  365. * Returns true if this set contains every character
  366. * of the given range.
  367. * @param start first character, inclusive, of the range
  368. * @param end last character, inclusive, of the range
  369. * @return true if the test condition is met
  370. */
  371. UBool UnicodeSet::contains(UChar32 start, UChar32 end) const {
  372. //int32_t i = -1;
  373. //for (;;) {
  374. // if (start < list[++i]) break;
  375. //}
  376. int32_t i = findCodePoint(start);
  377. return ((i & 1) != 0 && end < list[i]);
  378. }
  379. /**
  380. * Returns <tt>true</tt> if this set contains the given
  381. * multicharacter string.
  382. * @param s string to be checked for containment
  383. * @return <tt>true</tt> if this set contains the specified string
  384. */
  385. UBool UnicodeSet::contains(const UnicodeString& s) const {
  386. int32_t cp = getSingleCP(s);
  387. if (cp < 0) {
  388. return stringsContains(s);
  389. } else {
  390. return contains((UChar32) cp);
  391. }
  392. }
  393. /**
  394. * Returns true if this set contains all the characters and strings
  395. * of the given set.
  396. * @param c set to be checked for containment
  397. * @return true if the test condition is met
  398. */
  399. UBool UnicodeSet::containsAll(const UnicodeSet& c) const {
  400. // The specified set is a subset if all of its pairs are contained in
  401. // this set. It's possible to code this more efficiently in terms of
  402. // direct manipulation of the inversion lists if the need arises.
  403. int32_t n = c.getRangeCount();
  404. for (int i=0; i<n; ++i) {
  405. if (!contains(c.getRangeStart(i), c.getRangeEnd(i))) {
  406. return false;
  407. }
  408. }
  409. return !c.hasStrings() || (strings != nullptr && strings->containsAll(*c.strings));
  410. }
  411. /**
  412. * Returns true if this set contains all the characters
  413. * of the given string.
  414. * @param s string containing characters to be checked for containment
  415. * @return true if the test condition is met
  416. */
  417. UBool UnicodeSet::containsAll(const UnicodeString& s) const {
  418. return (UBool)(span(s.getBuffer(), s.length(), USET_SPAN_CONTAINED) ==
  419. s.length());
  420. }
  421. /**
  422. * Returns true if this set contains none of the characters
  423. * of the given range.
  424. * @param start first character, inclusive, of the range
  425. * @param end last character, inclusive, of the range
  426. * @return true if the test condition is met
  427. */
  428. UBool UnicodeSet::containsNone(UChar32 start, UChar32 end) const {
  429. //int32_t i = -1;
  430. //for (;;) {
  431. // if (start < list[++i]) break;
  432. //}
  433. int32_t i = findCodePoint(start);
  434. return ((i & 1) == 0 && end < list[i]);
  435. }
  436. /**
  437. * Returns true if this set contains none of the characters and strings
  438. * of the given set.
  439. * @param c set to be checked for containment
  440. * @return true if the test condition is met
  441. */
  442. UBool UnicodeSet::containsNone(const UnicodeSet& c) const {
  443. // The specified set is a subset if all of its pairs are contained in
  444. // this set. It's possible to code this more efficiently in terms of
  445. // direct manipulation of the inversion lists if the need arises.
  446. int32_t n = c.getRangeCount();
  447. for (int32_t i=0; i<n; ++i) {
  448. if (!containsNone(c.getRangeStart(i), c.getRangeEnd(i))) {
  449. return false;
  450. }
  451. }
  452. return strings == nullptr || !c.hasStrings() || strings->containsNone(*c.strings);
  453. }
  454. /**
  455. * Returns true if this set contains none of the characters
  456. * of the given string.
  457. * @param s string containing characters to be checked for containment
  458. * @return true if the test condition is met
  459. */
  460. UBool UnicodeSet::containsNone(const UnicodeString& s) const {
  461. return (UBool)(span(s.getBuffer(), s.length(), USET_SPAN_NOT_CONTAINED) ==
  462. s.length());
  463. }
  464. /**
  465. * Returns <tt>true</tt> if this set contains any character whose low byte
  466. * is the given value. This is used by <tt>RuleBasedTransliterator</tt> for
  467. * indexing.
  468. */
  469. UBool UnicodeSet::matchesIndexValue(uint8_t v) const {
  470. /* The index value v, in the range [0,255], is contained in this set if
  471. * it is contained in any pair of this set. Pairs either have the high
  472. * bytes equal, or unequal. If the high bytes are equal, then we have
  473. * aaxx..aayy, where aa is the high byte. Then v is contained if xx <=
  474. * v <= yy. If the high bytes are unequal we have aaxx..bbyy, bb>aa.
  475. * Then v is contained if xx <= v || v <= yy. (This is identical to the
  476. * time zone month containment logic.)
  477. */
  478. int32_t i;
  479. int32_t rangeCount=getRangeCount();
  480. for (i=0; i<rangeCount; ++i) {
  481. UChar32 low = getRangeStart(i);
  482. UChar32 high = getRangeEnd(i);
  483. if ((low & ~0xFF) == (high & ~0xFF)) {
  484. if ((low & 0xFF) <= v && v <= (high & 0xFF)) {
  485. return true;
  486. }
  487. } else if ((low & 0xFF) <= v || v <= (high & 0xFF)) {
  488. return true;
  489. }
  490. }
  491. if (hasStrings()) {
  492. for (i=0; i<strings->size(); ++i) {
  493. const UnicodeString& s = *(const UnicodeString*)strings->elementAt(i);
  494. if (s.isEmpty()) {
  495. continue; // skip the empty string
  496. }
  497. UChar32 c = s.char32At(0);
  498. if ((c & 0xFF) == v) {
  499. return true;
  500. }
  501. }
  502. }
  503. return false;
  504. }
  505. /**
  506. * Implementation of UnicodeMatcher::matches(). Always matches the
  507. * longest possible multichar string.
  508. */
  509. UMatchDegree UnicodeSet::matches(const Replaceable& text,
  510. int32_t& offset,
  511. int32_t limit,
  512. UBool incremental) {
  513. if (offset == limit) {
  514. if (contains(U_ETHER)) {
  515. return incremental ? U_PARTIAL_MATCH : U_MATCH;
  516. } else {
  517. return U_MISMATCH;
  518. }
  519. } else {
  520. if (hasStrings()) { // try strings first
  521. // might separate forward and backward loops later
  522. // for now they are combined
  523. // TODO Improve efficiency of this, at least in the forward
  524. // direction, if not in both. In the forward direction we
  525. // can assume the strings are sorted.
  526. int32_t i;
  527. UBool forward = offset < limit;
  528. // firstChar is the leftmost char to match in the
  529. // forward direction or the rightmost char to match in
  530. // the reverse direction.
  531. char16_t firstChar = text.charAt(offset);
  532. // If there are multiple strings that can match we
  533. // return the longest match.
  534. int32_t highWaterLength = 0;
  535. for (i=0; i<strings->size(); ++i) {
  536. const UnicodeString& trial = *(const UnicodeString*)strings->elementAt(i);
  537. if (trial.isEmpty()) {
  538. continue; // skip the empty string
  539. }
  540. char16_t c = trial.charAt(forward ? 0 : trial.length() - 1);
  541. // Strings are sorted, so we can optimize in the
  542. // forward direction.
  543. if (forward && c > firstChar) break;
  544. if (c != firstChar) continue;
  545. int32_t matchLen = matchRest(text, offset, limit, trial);
  546. if (incremental) {
  547. int32_t maxLen = forward ? limit-offset : offset-limit;
  548. if (matchLen == maxLen) {
  549. // We have successfully matched but only up to limit.
  550. return U_PARTIAL_MATCH;
  551. }
  552. }
  553. if (matchLen == trial.length()) {
  554. // We have successfully matched the whole string.
  555. if (matchLen > highWaterLength) {
  556. highWaterLength = matchLen;
  557. }
  558. // In the forward direction we know strings
  559. // are sorted so we can bail early.
  560. if (forward && matchLen < highWaterLength) {
  561. break;
  562. }
  563. continue;
  564. }
  565. }
  566. // We've checked all strings without a partial match.
  567. // If we have full matches, return the longest one.
  568. if (highWaterLength != 0) {
  569. offset += forward ? highWaterLength : -highWaterLength;
  570. return U_MATCH;
  571. }
  572. }
  573. return UnicodeFilter::matches(text, offset, limit, incremental);
  574. }
  575. }
  576. /**
  577. * Returns the longest match for s in text at the given position.
  578. * If limit > start then match forward from start+1 to limit
  579. * matching all characters except s.charAt(0). If limit < start,
  580. * go backward starting from start-1 matching all characters
  581. * except s.charAt(s.length()-1). This method assumes that the
  582. * first character, text.charAt(start), matches s, so it does not
  583. * check it.
  584. * @param text the text to match
  585. * @param start the first character to match. In the forward
  586. * direction, text.charAt(start) is matched against s.charAt(0).
  587. * In the reverse direction, it is matched against
  588. * s.charAt(s.length()-1).
  589. * @param limit the limit offset for matching, either last+1 in
  590. * the forward direction, or last-1 in the reverse direction,
  591. * where last is the index of the last character to match.
  592. * @return If part of s matches up to the limit, return |limit -
  593. * start|. If all of s matches before reaching the limit, return
  594. * s.length(). If there is a mismatch between s and text, return
  595. * 0
  596. */
  597. int32_t UnicodeSet::matchRest(const Replaceable& text,
  598. int32_t start, int32_t limit,
  599. const UnicodeString& s) {
  600. int32_t i;
  601. int32_t maxLen;
  602. int32_t slen = s.length();
  603. if (start < limit) {
  604. maxLen = limit - start;
  605. if (maxLen > slen) maxLen = slen;
  606. for (i = 1; i < maxLen; ++i) {
  607. if (text.charAt(start + i) != s.charAt(i)) return 0;
  608. }
  609. } else {
  610. maxLen = start - limit;
  611. if (maxLen > slen) maxLen = slen;
  612. --slen; // <=> slen = s.length() - 1;
  613. for (i = 1; i < maxLen; ++i) {
  614. if (text.charAt(start - i) != s.charAt(slen - i)) return 0;
  615. }
  616. }
  617. return maxLen;
  618. }
  619. /**
  620. * Implement of UnicodeMatcher
  621. */
  622. void UnicodeSet::addMatchSetTo(UnicodeSet& toUnionTo) const {
  623. toUnionTo.addAll(*this);
  624. }
  625. /**
  626. * Returns the index of the given character within this set, where
  627. * the set is ordered by ascending code point. If the character
  628. * is not in this set, return -1. The inverse of this method is
  629. * <code>charAt()</code>.
  630. * @return an index from 0..size()-1, or -1
  631. */
  632. int32_t UnicodeSet::indexOf(UChar32 c) const {
  633. if (c < MIN_VALUE || c > MAX_VALUE) {
  634. return -1;
  635. }
  636. int32_t i = 0;
  637. int32_t n = 0;
  638. for (;;) {
  639. UChar32 start = list[i++];
  640. if (c < start) {
  641. return -1;
  642. }
  643. UChar32 limit = list[i++];
  644. if (c < limit) {
  645. return n + c - start;
  646. }
  647. n += limit - start;
  648. }
  649. }
  650. /**
  651. * Returns the character at the given index within this set, where
  652. * the set is ordered by ascending code point. If the index is
  653. * out of range, return (UChar32)-1. The inverse of this method is
  654. * <code>indexOf()</code>.
  655. * @param index an index from 0..size()-1
  656. * @return the character at the given index, or (UChar32)-1.
  657. */
  658. UChar32 UnicodeSet::charAt(int32_t index) const {
  659. if (index >= 0) {
  660. // len2 is the largest even integer <= len, that is, it is len
  661. // for even values and len-1 for odd values. With odd values
  662. // the last entry is UNICODESET_HIGH.
  663. int32_t len2 = len & ~1;
  664. for (int32_t i=0; i < len2;) {
  665. UChar32 start = list[i++];
  666. int32_t count = list[i++] - start;
  667. if (index < count) {
  668. return (UChar32)(start + index);
  669. }
  670. index -= count;
  671. }
  672. }
  673. return (UChar32)-1;
  674. }
  675. /**
  676. * Make this object represent the range <code>start - end</code>.
  677. * If <code>end > start</code> then this object is set to an
  678. * an empty range.
  679. *
  680. * @param start first character in the set, inclusive
  681. * @rparam end last character in the set, inclusive
  682. */
  683. UnicodeSet& UnicodeSet::set(UChar32 start, UChar32 end) {
  684. clear();
  685. complement(start, end);
  686. return *this;
  687. }
  688. /**
  689. * Adds the specified range to this set if it is not already
  690. * present. If this set already contains the specified range,
  691. * the call leaves this set unchanged. If <code>end > start</code>
  692. * then an empty range is added, leaving the set unchanged.
  693. *
  694. * @param start first character, inclusive, of range to be added
  695. * to this set.
  696. * @param end last character, inclusive, of range to be added
  697. * to this set.
  698. */
  699. UnicodeSet& UnicodeSet::add(UChar32 start, UChar32 end) {
  700. if (pinCodePoint(start) < pinCodePoint(end)) {
  701. UChar32 limit = end + 1;
  702. // Fast path for adding a new range after the last one.
  703. // Odd list length: [..., lastStart, lastLimit, HIGH]
  704. if ((len & 1) != 0) {
  705. // If the list is empty, set lastLimit low enough to not be adjacent to 0.
  706. UChar32 lastLimit = len == 1 ? -2 : list[len - 2];
  707. if (lastLimit <= start && !isFrozen() && !isBogus()) {
  708. if (lastLimit == start) {
  709. // Extend the last range.
  710. list[len - 2] = limit;
  711. if (limit == UNICODESET_HIGH) {
  712. --len;
  713. }
  714. } else {
  715. list[len - 1] = start;
  716. if (limit < UNICODESET_HIGH) {
  717. if (ensureCapacity(len + 2)) {
  718. list[len++] = limit;
  719. list[len++] = UNICODESET_HIGH;
  720. }
  721. } else { // limit == UNICODESET_HIGH
  722. if (ensureCapacity(len + 1)) {
  723. list[len++] = UNICODESET_HIGH;
  724. }
  725. }
  726. }
  727. releasePattern();
  728. return *this;
  729. }
  730. }
  731. // This is slow. Could be much faster using findCodePoint(start)
  732. // and modifying the list, dealing with adjacent & overlapping ranges.
  733. UChar32 range[3] = { start, limit, UNICODESET_HIGH };
  734. add(range, 2, 0);
  735. } else if (start == end) {
  736. add(start);
  737. }
  738. return *this;
  739. }
  740. // #define DEBUG_US_ADD
  741. #ifdef DEBUG_US_ADD
  742. #include <stdio.h>
  743. void dump(UChar32 c) {
  744. if (c <= 0xFF) {
  745. printf("%c", (char)c);
  746. } else {
  747. printf("U+%04X", c);
  748. }
  749. }
  750. void dump(const UChar32* list, int32_t len) {
  751. printf("[");
  752. for (int32_t i=0; i<len; ++i) {
  753. if (i != 0) printf(", ");
  754. dump(list[i]);
  755. }
  756. printf("]");
  757. }
  758. #endif
  759. /**
  760. * Adds the specified character to this set if it is not already
  761. * present. If this set already contains the specified character,
  762. * the call leaves this set unchanged.
  763. */
  764. UnicodeSet& UnicodeSet::add(UChar32 c) {
  765. // find smallest i such that c < list[i]
  766. // if odd, then it is IN the set
  767. // if even, then it is OUT of the set
  768. int32_t i = findCodePoint(pinCodePoint(c));
  769. // already in set?
  770. if ((i & 1) != 0 || isFrozen() || isBogus()) return *this;
  771. // HIGH is 0x110000
  772. // assert(list[len-1] == HIGH);
  773. // empty = [HIGH]
  774. // [start_0, limit_0, start_1, limit_1, HIGH]
  775. // [..., start_k-1, limit_k-1, start_k, limit_k, ..., HIGH]
  776. // ^
  777. // list[i]
  778. // i == 0 means c is before the first range
  779. #ifdef DEBUG_US_ADD
  780. printf("Add of ");
  781. dump(c);
  782. printf(" found at %d", i);
  783. printf(": ");
  784. dump(list, len);
  785. printf(" => ");
  786. #endif
  787. if (c == list[i]-1) {
  788. // c is before start of next range
  789. list[i] = c;
  790. // if we touched the HIGH mark, then add a new one
  791. if (c == (UNICODESET_HIGH - 1)) {
  792. if (!ensureCapacity(len+1)) {
  793. // ensureCapacity will mark the object as Bogus if OOM failure happens.
  794. return *this;
  795. }
  796. list[len++] = UNICODESET_HIGH;
  797. }
  798. if (i > 0 && c == list[i-1]) {
  799. // collapse adjacent ranges
  800. // [..., start_k-1, c, c, limit_k, ..., HIGH]
  801. // ^
  802. // list[i]
  803. //for (int32_t k=i-1; k<len-2; ++k) {
  804. // list[k] = list[k+2];
  805. //}
  806. UChar32* dst = list + i - 1;
  807. UChar32* src = dst + 2;
  808. UChar32* srclimit = list + len;
  809. while (src < srclimit) *(dst++) = *(src++);
  810. len -= 2;
  811. }
  812. }
  813. else if (i > 0 && c == list[i-1]) {
  814. // c is after end of prior range
  815. list[i-1]++;
  816. // no need to check for collapse here
  817. }
  818. else {
  819. // At this point we know the new char is not adjacent to
  820. // any existing ranges, and it is not 10FFFF.
  821. // [..., start_k-1, limit_k-1, start_k, limit_k, ..., HIGH]
  822. // ^
  823. // list[i]
  824. // [..., start_k-1, limit_k-1, c, c+1, start_k, limit_k, ..., HIGH]
  825. // ^
  826. // list[i]
  827. if (!ensureCapacity(len+2)) {
  828. // ensureCapacity will mark the object as Bogus if OOM failure happens.
  829. return *this;
  830. }
  831. UChar32 *p = list + i;
  832. uprv_memmove(p + 2, p, (len - i) * sizeof(*p));
  833. list[i] = c;
  834. list[i+1] = c+1;
  835. len += 2;
  836. }
  837. #ifdef DEBUG_US_ADD
  838. dump(list, len);
  839. printf("\n");
  840. for (i=1; i<len; ++i) {
  841. if (list[i] <= list[i-1]) {
  842. // Corrupt array!
  843. printf("ERROR: list has been corrupted\n");
  844. exit(1);
  845. }
  846. }
  847. #endif
  848. releasePattern();
  849. return *this;
  850. }
  851. /**
  852. * Adds the specified multicharacter to this set if it is not already
  853. * present. If this set already contains the multicharacter,
  854. * the call leaves this set unchanged.
  855. * Thus "ch" => {"ch"}
  856. *
  857. * @param s the source string
  858. * @return the modified set, for chaining
  859. */
  860. UnicodeSet& UnicodeSet::add(const UnicodeString& s) {
  861. if (isFrozen() || isBogus()) return *this;
  862. int32_t cp = getSingleCP(s);
  863. if (cp < 0) {
  864. if (!stringsContains(s)) {
  865. _add(s);
  866. releasePattern();
  867. }
  868. } else {
  869. add((UChar32)cp);
  870. }
  871. return *this;
  872. }
  873. /**
  874. * Adds the given string, in order, to 'strings'. The given string
  875. * must have been checked by the caller to not already be in 'strings'.
  876. */
  877. void UnicodeSet::_add(const UnicodeString& s) {
  878. if (isFrozen() || isBogus()) {
  879. return;
  880. }
  881. UErrorCode ec = U_ZERO_ERROR;
  882. if (strings == nullptr && !allocateStrings(ec)) {
  883. setToBogus();
  884. return;
  885. }
  886. UnicodeString* t = new UnicodeString(s);
  887. if (t == nullptr) { // Check for memory allocation error.
  888. setToBogus();
  889. return;
  890. }
  891. strings->sortedInsert(t, compareUnicodeString, ec);
  892. if (U_FAILURE(ec)) {
  893. setToBogus();
  894. }
  895. }
  896. /**
  897. * @return a code point IF the string consists of a single one.
  898. * otherwise returns -1.
  899. * @param string to test
  900. */
  901. int32_t UnicodeSet::getSingleCP(const UnicodeString& s) {
  902. int32_t sLength = s.length();
  903. if (sLength == 1) return s.charAt(0);
  904. if (sLength == 2) {
  905. UChar32 cp = s.char32At(0);
  906. if (cp > 0xFFFF) { // is surrogate pair
  907. return cp;
  908. }
  909. }
  910. return -1;
  911. }
  912. /**
  913. * Adds each of the characters in this string to the set. Thus "ch" => {"c", "h"}
  914. * If this set already any particular character, it has no effect on that character.
  915. * @param the source string
  916. * @return the modified set, for chaining
  917. */
  918. UnicodeSet& UnicodeSet::addAll(const UnicodeString& s) {
  919. UChar32 cp;
  920. for (int32_t i = 0; i < s.length(); i += U16_LENGTH(cp)) {
  921. cp = s.char32At(i);
  922. add(cp);
  923. }
  924. return *this;
  925. }
  926. /**
  927. * Retains EACH of the characters in this string. Note: "ch" == {"c", "h"}
  928. * If this set already any particular character, it has no effect on that character.
  929. * @param the source string
  930. * @return the modified set, for chaining
  931. */
  932. UnicodeSet& UnicodeSet::retainAll(const UnicodeString& s) {
  933. UnicodeSet set;
  934. set.addAll(s);
  935. retainAll(set);
  936. return *this;
  937. }
  938. /**
  939. * Complement EACH of the characters in this string. Note: "ch" == {"c", "h"}
  940. * If this set already any particular character, it has no effect on that character.
  941. * @param the source string
  942. * @return the modified set, for chaining
  943. */
  944. UnicodeSet& UnicodeSet::complementAll(const UnicodeString& s) {
  945. UnicodeSet set;
  946. set.addAll(s);
  947. complementAll(set);
  948. return *this;
  949. }
  950. /**
  951. * Remove EACH of the characters in this string. Note: "ch" == {"c", "h"}
  952. * If this set already any particular character, it has no effect on that character.
  953. * @param the source string
  954. * @return the modified set, for chaining
  955. */
  956. UnicodeSet& UnicodeSet::removeAll(const UnicodeString& s) {
  957. UnicodeSet set;
  958. set.addAll(s);
  959. removeAll(set);
  960. return *this;
  961. }
  962. UnicodeSet& UnicodeSet::removeAllStrings() {
  963. if (!isFrozen() && hasStrings()) {
  964. strings->removeAllElements();
  965. releasePattern();
  966. }
  967. return *this;
  968. }
  969. /**
  970. * Makes a set from a multicharacter string. Thus "ch" => {"ch"}
  971. * <br><b>Warning: you cannot add an empty string ("") to a UnicodeSet.</b>
  972. * @param the source string
  973. * @return a newly created set containing the given string
  974. */
  975. UnicodeSet* U_EXPORT2 UnicodeSet::createFrom(const UnicodeString& s) {
  976. UnicodeSet *set = new UnicodeSet();
  977. if (set != nullptr) { // Check for memory allocation error.
  978. set->add(s);
  979. }
  980. return set;
  981. }
  982. /**
  983. * Makes a set from each of the characters in the string. Thus "ch" => {"c", "h"}
  984. * @param the source string
  985. * @return a newly created set containing the given characters
  986. */
  987. UnicodeSet* U_EXPORT2 UnicodeSet::createFromAll(const UnicodeString& s) {
  988. UnicodeSet *set = new UnicodeSet();
  989. if (set != nullptr) { // Check for memory allocation error.
  990. set->addAll(s);
  991. }
  992. return set;
  993. }
  994. /**
  995. * Retain only the elements in this set that are contained in the
  996. * specified range. If <code>end > start</code> then an empty range is
  997. * retained, leaving the set empty.
  998. *
  999. * @param start first character, inclusive, of range to be retained
  1000. * to this set.
  1001. * @param end last character, inclusive, of range to be retained
  1002. * to this set.
  1003. */
  1004. UnicodeSet& UnicodeSet::retain(UChar32 start, UChar32 end) {
  1005. if (pinCodePoint(start) <= pinCodePoint(end)) {
  1006. UChar32 range[3] = { start, end+1, UNICODESET_HIGH };
  1007. retain(range, 2, 0);
  1008. } else {
  1009. clear();
  1010. }
  1011. return *this;
  1012. }
  1013. UnicodeSet& UnicodeSet::retain(UChar32 c) {
  1014. return retain(c, c);
  1015. }
  1016. UnicodeSet& UnicodeSet::retain(const UnicodeString &s) {
  1017. if (isFrozen() || isBogus()) { return *this; }
  1018. UChar32 cp = getSingleCP(s);
  1019. if (cp < 0) {
  1020. bool isIn = stringsContains(s);
  1021. // Check for getRangeCount() first to avoid somewhat-expensive size()
  1022. // when there are single code points.
  1023. if (isIn && getRangeCount() == 0 && size() == 1) {
  1024. return *this;
  1025. }
  1026. clear();
  1027. if (isIn) {
  1028. _add(s);
  1029. }
  1030. } else {
  1031. retain(cp, cp);
  1032. }
  1033. return *this;
  1034. }
  1035. /**
  1036. * Removes the specified range from this set if it is present.
  1037. * The set will not contain the specified range once the call
  1038. * returns. If <code>end > start</code> then an empty range is
  1039. * removed, leaving the set unchanged.
  1040. *
  1041. * @param start first character, inclusive, of range to be removed
  1042. * from this set.
  1043. * @param end last character, inclusive, of range to be removed
  1044. * from this set.
  1045. */
  1046. UnicodeSet& UnicodeSet::remove(UChar32 start, UChar32 end) {
  1047. if (pinCodePoint(start) <= pinCodePoint(end)) {
  1048. UChar32 range[3] = { start, end+1, UNICODESET_HIGH };
  1049. retain(range, 2, 2);
  1050. }
  1051. return *this;
  1052. }
  1053. /**
  1054. * Removes the specified character from this set if it is present.
  1055. * The set will not contain the specified range once the call
  1056. * returns.
  1057. */
  1058. UnicodeSet& UnicodeSet::remove(UChar32 c) {
  1059. return remove(c, c);
  1060. }
  1061. /**
  1062. * Removes the specified string from this set if it is present.
  1063. * The set will not contain the specified character once the call
  1064. * returns.
  1065. * @param the source string
  1066. * @return the modified set, for chaining
  1067. */
  1068. UnicodeSet& UnicodeSet::remove(const UnicodeString& s) {
  1069. if (isFrozen() || isBogus()) return *this;
  1070. int32_t cp = getSingleCP(s);
  1071. if (cp < 0) {
  1072. if (strings != nullptr && strings->removeElement((void*) &s)) {
  1073. releasePattern();
  1074. }
  1075. } else {
  1076. remove((UChar32)cp, (UChar32)cp);
  1077. }
  1078. return *this;
  1079. }
  1080. /**
  1081. * Complements the specified range in this set. Any character in
  1082. * the range will be removed if it is in this set, or will be
  1083. * added if it is not in this set. If <code>end > start</code>
  1084. * then an empty range is xor'ed, leaving the set unchanged.
  1085. *
  1086. * @param start first character, inclusive, of range to be removed
  1087. * from this set.
  1088. * @param end last character, inclusive, of range to be removed
  1089. * from this set.
  1090. */
  1091. UnicodeSet& UnicodeSet::complement(UChar32 start, UChar32 end) {
  1092. if (isFrozen() || isBogus()) {
  1093. return *this;
  1094. }
  1095. if (pinCodePoint(start) <= pinCodePoint(end)) {
  1096. UChar32 range[3] = { start, end+1, UNICODESET_HIGH };
  1097. exclusiveOr(range, 2, 0);
  1098. }
  1099. releasePattern();
  1100. return *this;
  1101. }
  1102. UnicodeSet& UnicodeSet::complement(UChar32 c) {
  1103. return complement(c, c);
  1104. }
  1105. /**
  1106. * This is equivalent to
  1107. * <code>complement(MIN_VALUE, MAX_VALUE)</code>.
  1108. */
  1109. UnicodeSet& UnicodeSet::complement() {
  1110. if (isFrozen() || isBogus()) {
  1111. return *this;
  1112. }
  1113. if (list[0] == UNICODESET_LOW) {
  1114. uprv_memmove(list, list + 1, (size_t)(len-1)*sizeof(UChar32));
  1115. --len;
  1116. } else {
  1117. if (!ensureCapacity(len+1)) {
  1118. return *this;
  1119. }
  1120. uprv_memmove(list + 1, list, (size_t)len*sizeof(UChar32));
  1121. list[0] = UNICODESET_LOW;
  1122. ++len;
  1123. }
  1124. releasePattern();
  1125. return *this;
  1126. }
  1127. /**
  1128. * Complement the specified string in this set.
  1129. * The set will not contain the specified string once the call
  1130. * returns.
  1131. *
  1132. * @param s the string to complement
  1133. * @return this object, for chaining
  1134. */
  1135. UnicodeSet& UnicodeSet::complement(const UnicodeString& s) {
  1136. if (isFrozen() || isBogus()) return *this;
  1137. int32_t cp = getSingleCP(s);
  1138. if (cp < 0) {
  1139. if (stringsContains(s)) {
  1140. strings->removeElement((void*) &s);
  1141. } else {
  1142. _add(s);
  1143. }
  1144. releasePattern();
  1145. } else {
  1146. complement((UChar32)cp, (UChar32)cp);
  1147. }
  1148. return *this;
  1149. }
  1150. /**
  1151. * Adds all of the elements in the specified set to this set if
  1152. * they're not already present. This operation effectively
  1153. * modifies this set so that its value is the <i>union</i> of the two
  1154. * sets. The behavior of this operation is unspecified if the specified
  1155. * collection is modified while the operation is in progress.
  1156. *
  1157. * @param c set whose elements are to be added to this set.
  1158. * @see #add(char, char)
  1159. */
  1160. UnicodeSet& UnicodeSet::addAll(const UnicodeSet& c) {
  1161. if ( c.len>0 && c.list!=nullptr ) {
  1162. add(c.list, c.len, 0);
  1163. }
  1164. // Add strings in order
  1165. if ( c.strings!=nullptr ) {
  1166. for (int32_t i=0; i<c.strings->size(); ++i) {
  1167. const UnicodeString* s = (const UnicodeString*)c.strings->elementAt(i);
  1168. if (!stringsContains(*s)) {
  1169. _add(*s);
  1170. }
  1171. }
  1172. }
  1173. return *this;
  1174. }
  1175. /**
  1176. * Retains only the elements in this set that are contained in the
  1177. * specified set. In other words, removes from this set all of
  1178. * its elements that are not contained in the specified set. This
  1179. * operation effectively modifies this set so that its value is
  1180. * the <i>intersection</i> of the two sets.
  1181. *
  1182. * @param c set that defines which elements this set will retain.
  1183. */
  1184. UnicodeSet& UnicodeSet::retainAll(const UnicodeSet& c) {
  1185. if (isFrozen() || isBogus()) {
  1186. return *this;
  1187. }
  1188. retain(c.list, c.len, 0);
  1189. if (hasStrings()) {
  1190. if (!c.hasStrings()) {
  1191. strings->removeAllElements();
  1192. } else {
  1193. strings->retainAll(*c.strings);
  1194. }
  1195. }
  1196. return *this;
  1197. }
  1198. /**
  1199. * Removes from this set all of its elements that are contained in the
  1200. * specified set. This operation effectively modifies this
  1201. * set so that its value is the <i>asymmetric set difference</i> of
  1202. * the two sets.
  1203. *
  1204. * @param c set that defines which elements will be removed from
  1205. * this set.
  1206. */
  1207. UnicodeSet& UnicodeSet::removeAll(const UnicodeSet& c) {
  1208. if (isFrozen() || isBogus()) {
  1209. return *this;
  1210. }
  1211. retain(c.list, c.len, 2);
  1212. if (hasStrings() && c.hasStrings()) {
  1213. strings->removeAll(*c.strings);
  1214. }
  1215. return *this;
  1216. }
  1217. /**
  1218. * Complements in this set all elements contained in the specified
  1219. * set. Any character in the other set will be removed if it is
  1220. * in this set, or will be added if it is not in this set.
  1221. *
  1222. * @param c set that defines which elements will be xor'ed from
  1223. * this set.
  1224. */
  1225. UnicodeSet& UnicodeSet::complementAll(const UnicodeSet& c) {
  1226. if (isFrozen() || isBogus()) {
  1227. return *this;
  1228. }
  1229. exclusiveOr(c.list, c.len, 0);
  1230. if (c.strings != nullptr) {
  1231. for (int32_t i=0; i<c.strings->size(); ++i) {
  1232. void* e = c.strings->elementAt(i);
  1233. if (strings == nullptr || !strings->removeElement(e)) {
  1234. _add(*(const UnicodeString*)e);
  1235. }
  1236. }
  1237. }
  1238. return *this;
  1239. }
  1240. /**
  1241. * Removes all of the elements from this set. This set will be
  1242. * empty after this call returns.
  1243. */
  1244. UnicodeSet& UnicodeSet::clear() {
  1245. if (isFrozen()) {
  1246. return *this;
  1247. }
  1248. list[0] = UNICODESET_HIGH;
  1249. len = 1;
  1250. releasePattern();
  1251. if (strings != nullptr) {
  1252. strings->removeAllElements();
  1253. }
  1254. // Remove bogus
  1255. fFlags = 0;
  1256. return *this;
  1257. }
  1258. /**
  1259. * Iteration method that returns the number of ranges contained in
  1260. * this set.
  1261. * @see #getRangeStart
  1262. * @see #getRangeEnd
  1263. */
  1264. int32_t UnicodeSet::getRangeCount() const {
  1265. return len/2;
  1266. }
  1267. /**
  1268. * Iteration method that returns the first character in the
  1269. * specified range of this set.
  1270. * @see #getRangeCount
  1271. * @see #getRangeEnd
  1272. */
  1273. UChar32 UnicodeSet::getRangeStart(int32_t index) const {
  1274. return list[index*2];
  1275. }
  1276. /**
  1277. * Iteration method that returns the last character in the
  1278. * specified range of this set.
  1279. * @see #getRangeStart
  1280. * @see #getRangeEnd
  1281. */
  1282. UChar32 UnicodeSet::getRangeEnd(int32_t index) const {
  1283. return list[index*2 + 1] - 1;
  1284. }
  1285. const UnicodeString* UnicodeSet::getString(int32_t index) const {
  1286. return (const UnicodeString*) strings->elementAt(index);
  1287. }
  1288. /**
  1289. * Reallocate this objects internal structures to take up the least
  1290. * possible space, without changing this object's value.
  1291. */
  1292. UnicodeSet& UnicodeSet::compact() {
  1293. if (isFrozen() || isBogus()) {
  1294. return *this;
  1295. }
  1296. // Delete buffer first to defragment memory less.
  1297. if (buffer != stackList) {
  1298. uprv_free(buffer);
  1299. buffer = nullptr;
  1300. bufferCapacity = 0;
  1301. }
  1302. if (list == stackList) {
  1303. // pass
  1304. } else if (len <= INITIAL_CAPACITY) {
  1305. uprv_memcpy(stackList, list, len * sizeof(UChar32));
  1306. uprv_free(list);
  1307. list = stackList;
  1308. capacity = INITIAL_CAPACITY;
  1309. } else if ((len + 7) < capacity) {
  1310. // If we have more than a little unused capacity, shrink it to len.
  1311. UChar32* temp = (UChar32*) uprv_realloc(list, sizeof(UChar32) * len);
  1312. if (temp) {
  1313. list = temp;
  1314. capacity = len;
  1315. }
  1316. // else what the heck happened?! We allocated less memory!
  1317. // Oh well. We'll keep our original array.
  1318. }
  1319. if (strings != nullptr && strings->isEmpty()) {
  1320. delete strings;
  1321. strings = nullptr;
  1322. }
  1323. return *this;
  1324. }
  1325. #ifdef DEBUG_SERIALIZE
  1326. #include <stdio.h>
  1327. #endif
  1328. /**
  1329. * Deserialize constructor.
  1330. */
  1331. UnicodeSet::UnicodeSet(const uint16_t data[], int32_t dataLen, ESerialization serialization,
  1332. UErrorCode &ec) {
  1333. if(U_FAILURE(ec)) {
  1334. setToBogus();
  1335. return;
  1336. }
  1337. if( (serialization != kSerialized)
  1338. || (data==nullptr)
  1339. || (dataLen < 1)) {
  1340. ec = U_ILLEGAL_ARGUMENT_ERROR;
  1341. setToBogus();
  1342. return;
  1343. }
  1344. // bmp?
  1345. int32_t headerSize = ((data[0]&0x8000)) ?2:1;
  1346. int32_t bmpLength = (headerSize==1)?data[0]:data[1];
  1347. int32_t newLength = (((data[0]&0x7FFF)-bmpLength)/2)+bmpLength;
  1348. #ifdef DEBUG_SERIALIZE
  1349. printf("dataLen %d headerSize %d bmpLen %d len %d. data[0]=%X/%X/%X/%X\n", dataLen,headerSize,bmpLength,newLength, data[0],data[1],data[2],data[3]);
  1350. #endif
  1351. if(!ensureCapacity(newLength + 1)) { // +1 for HIGH
  1352. return;
  1353. }
  1354. // copy bmp
  1355. int32_t i;
  1356. for(i = 0; i< bmpLength;i++) {
  1357. list[i] = data[i+headerSize];
  1358. #ifdef DEBUG_SERIALIZE
  1359. printf("<<16@%d[%d] %X\n", i+headerSize, i, list[i]);
  1360. #endif
  1361. }
  1362. // copy smp
  1363. for(i=bmpLength;i<newLength;i++) {
  1364. list[i] = ((UChar32)data[headerSize+bmpLength+(i-bmpLength)*2+0] << 16) +
  1365. ((UChar32)data[headerSize+bmpLength+(i-bmpLength)*2+1]);
  1366. #ifdef DEBUG_SERIALIZE
  1367. printf("<<32@%d+[%d] %lX\n", headerSize+bmpLength+i, i, list[i]);
  1368. #endif
  1369. }
  1370. U_ASSERT(i == newLength);
  1371. if (i == 0 || list[i - 1] != UNICODESET_HIGH) {
  1372. list[i++] = UNICODESET_HIGH;
  1373. }
  1374. len = i;
  1375. }
  1376. int32_t UnicodeSet::serialize(uint16_t *dest, int32_t destCapacity, UErrorCode& ec) const {
  1377. int32_t bmpLength, length, destLength;
  1378. if (U_FAILURE(ec)) {
  1379. return 0;
  1380. }
  1381. if (destCapacity<0 || (destCapacity>0 && dest==nullptr)) {
  1382. ec=U_ILLEGAL_ARGUMENT_ERROR;
  1383. return 0;
  1384. }
  1385. /* count necessary 16-bit units */
  1386. length=this->len-1; // Subtract 1 to ignore final UNICODESET_HIGH
  1387. // assert(length>=0);
  1388. if (length==0) {
  1389. /* empty set */
  1390. if (destCapacity>0) {
  1391. *dest=0;
  1392. } else {
  1393. ec=U_BUFFER_OVERFLOW_ERROR;
  1394. }
  1395. return 1;
  1396. }
  1397. /* now length>0 */
  1398. if (this->list[length-1]<=0xffff) {
  1399. /* all BMP */
  1400. bmpLength=length;
  1401. } else if (this->list[0]>=0x10000) {
  1402. /* all supplementary */
  1403. bmpLength=0;
  1404. length*=2;
  1405. } else {
  1406. /* some BMP, some supplementary */
  1407. for (bmpLength=0; bmpLength<length && this->list[bmpLength]<=0xffff; ++bmpLength) {}
  1408. length=bmpLength+2*(length-bmpLength);
  1409. }
  1410. #ifdef DEBUG_SERIALIZE
  1411. printf(">> bmpLength%d length%d len%d\n", bmpLength, length, len);
  1412. #endif
  1413. /* length: number of 16-bit array units */
  1414. if (length>0x7fff) {
  1415. /* there are only 15 bits for the length in the first serialized word */
  1416. ec=U_INDEX_OUTOFBOUNDS_ERROR;
  1417. return 0;
  1418. }
  1419. /*
  1420. * total serialized length:
  1421. * number of 16-bit array units (length) +
  1422. * 1 length unit (always) +
  1423. * 1 bmpLength unit (if there are supplementary values)
  1424. */
  1425. destLength=length+((length>bmpLength)?2:1);
  1426. if (destLength<=destCapacity) {
  1427. const UChar32 *p;
  1428. int32_t i;
  1429. #ifdef DEBUG_SERIALIZE
  1430. printf("writeHdr\n");
  1431. #endif
  1432. *dest=(uint16_t)length;
  1433. if (length>bmpLength) {
  1434. *dest|=0x8000;
  1435. *++dest=(uint16_t)bmpLength;
  1436. }
  1437. ++dest;
  1438. /* write the BMP part of the array */
  1439. p=this->list;
  1440. for (i=0; i<bmpLength; ++i) {
  1441. #ifdef DEBUG_SERIALIZE
  1442. printf("writebmp: %x\n", (int)*p);
  1443. #endif
  1444. *dest++=(uint16_t)*p++;
  1445. }
  1446. /* write the supplementary part of the array */
  1447. for (; i<length; i+=2) {
  1448. #ifdef DEBUG_SERIALIZE
  1449. printf("write32: %x\n", (int)*p);
  1450. #endif
  1451. *dest++=(uint16_t)(*p>>16);
  1452. *dest++=(uint16_t)*p++;
  1453. }
  1454. } else {
  1455. ec=U_BUFFER_OVERFLOW_ERROR;
  1456. }
  1457. return destLength;
  1458. }
  1459. //----------------------------------------------------------------
  1460. // Implementation: Utility methods
  1461. //----------------------------------------------------------------
  1462. /**
  1463. * Allocate our strings vector and return true if successful.
  1464. */
  1465. UBool UnicodeSet::allocateStrings(UErrorCode &status) {
  1466. if (U_FAILURE(status)) {
  1467. return false;
  1468. }
  1469. strings = new UVector(uprv_deleteUObject,
  1470. uhash_compareUnicodeString, 1, status);
  1471. if (strings == nullptr) { // Check for memory allocation error.
  1472. status = U_MEMORY_ALLOCATION_ERROR;
  1473. return false;
  1474. }
  1475. if (U_FAILURE(status)) {
  1476. delete strings;
  1477. strings = nullptr;
  1478. return false;
  1479. }
  1480. return true;
  1481. }
  1482. int32_t UnicodeSet::nextCapacity(int32_t minCapacity) {
  1483. // Grow exponentially to reduce the frequency of allocations.
  1484. if (minCapacity < INITIAL_CAPACITY) {
  1485. return minCapacity + INITIAL_CAPACITY;
  1486. } else if (minCapacity <= 2500) {
  1487. return 5 * minCapacity;
  1488. } else {
  1489. int32_t newCapacity = 2 * minCapacity;
  1490. if (newCapacity > MAX_LENGTH) {
  1491. newCapacity = MAX_LENGTH;
  1492. }
  1493. return newCapacity;
  1494. }
  1495. }
  1496. bool UnicodeSet::ensureCapacity(int32_t newLen) {
  1497. if (newLen > MAX_LENGTH) {
  1498. newLen = MAX_LENGTH;
  1499. }
  1500. if (newLen <= capacity) {
  1501. return true;
  1502. }
  1503. int32_t newCapacity = nextCapacity(newLen);
  1504. UChar32* temp = (UChar32*) uprv_malloc(newCapacity * sizeof(UChar32));
  1505. if (temp == nullptr) {
  1506. setToBogus(); // set the object to bogus state if an OOM failure occurred.
  1507. return false;
  1508. }
  1509. // Copy only the actual contents.
  1510. uprv_memcpy(temp, list, len * sizeof(UChar32));
  1511. if (list != stackList) {
  1512. uprv_free(list);
  1513. }
  1514. list = temp;
  1515. capacity = newCapacity;
  1516. return true;
  1517. }
  1518. bool UnicodeSet::ensureBufferCapacity(int32_t newLen) {
  1519. if (newLen > MAX_LENGTH) {
  1520. newLen = MAX_LENGTH;
  1521. }
  1522. if (newLen <= bufferCapacity) {
  1523. return true;
  1524. }
  1525. int32_t newCapacity = nextCapacity(newLen);
  1526. UChar32* temp = (UChar32*) uprv_malloc(newCapacity * sizeof(UChar32));
  1527. if (temp == nullptr) {
  1528. setToBogus();
  1529. return false;
  1530. }
  1531. // The buffer has no contents to be copied.
  1532. // It is always filled from scratch after this call.
  1533. if (buffer != stackList) {
  1534. uprv_free(buffer);
  1535. }
  1536. buffer = temp;
  1537. bufferCapacity = newCapacity;
  1538. return true;
  1539. }
  1540. /**
  1541. * Swap list and buffer.
  1542. */
  1543. void UnicodeSet::swapBuffers() {
  1544. // swap list and buffer
  1545. UChar32* temp = list;
  1546. list = buffer;
  1547. buffer = temp;
  1548. int32_t c = capacity;
  1549. capacity = bufferCapacity;
  1550. bufferCapacity = c;
  1551. }
  1552. void UnicodeSet::setToBogus() {
  1553. clear(); // Remove everything in the set.
  1554. fFlags = kIsBogus;
  1555. }
  1556. //----------------------------------------------------------------
  1557. // Implementation: Fundamental operators
  1558. //----------------------------------------------------------------
  1559. static inline UChar32 max(UChar32 a, UChar32 b) {
  1560. return (a > b) ? a : b;
  1561. }
  1562. // polarity = 0, 3 is normal: x xor y
  1563. // polarity = 1, 2: x xor ~y == x === y
  1564. void UnicodeSet::exclusiveOr(const UChar32* other, int32_t otherLen, int8_t polarity) {
  1565. if (isFrozen() || isBogus()) {
  1566. return;
  1567. }
  1568. if (!ensureBufferCapacity(len + otherLen)) {
  1569. return;
  1570. }
  1571. int32_t i = 0, j = 0, k = 0;
  1572. UChar32 a = list[i++];
  1573. UChar32 b;
  1574. if (polarity == 1 || polarity == 2) {
  1575. b = UNICODESET_LOW;
  1576. if (other[j] == UNICODESET_LOW) { // skip base if already LOW
  1577. ++j;
  1578. b = other[j];
  1579. }
  1580. } else {
  1581. b = other[j++];
  1582. }
  1583. // simplest of all the routines
  1584. // sort the values, discarding identicals!
  1585. for (;;) {
  1586. if (a < b) {
  1587. buffer[k++] = a;
  1588. a = list[i++];
  1589. } else if (b < a) {
  1590. buffer[k++] = b;
  1591. b = other[j++];
  1592. } else if (a != UNICODESET_HIGH) { // at this point, a == b
  1593. // discard both values!
  1594. a = list[i++];
  1595. b = other[j++];
  1596. } else { // DONE!
  1597. buffer[k++] = UNICODESET_HIGH;
  1598. len = k;
  1599. break;
  1600. }
  1601. }
  1602. swapBuffers();
  1603. releasePattern();
  1604. }
  1605. // polarity = 0 is normal: x union y
  1606. // polarity = 2: x union ~y
  1607. // polarity = 1: ~x union y
  1608. // polarity = 3: ~x union ~y
  1609. void UnicodeSet::add(const UChar32* other, int32_t otherLen, int8_t polarity) {
  1610. if (isFrozen() || isBogus() || other==nullptr) {
  1611. return;
  1612. }
  1613. if (!ensureBufferCapacity(len + otherLen)) {
  1614. return;
  1615. }
  1616. int32_t i = 0, j = 0, k = 0;
  1617. UChar32 a = list[i++];
  1618. UChar32 b = other[j++];
  1619. // change from xor is that we have to check overlapping pairs
  1620. // polarity bit 1 means a is second, bit 2 means b is.
  1621. for (;;) {
  1622. switch (polarity) {
  1623. case 0: // both first; take lower if unequal
  1624. if (a < b) { // take a
  1625. // Back up over overlapping ranges in buffer[]
  1626. if (k > 0 && a <= buffer[k-1]) {
  1627. // Pick latter end value in buffer[] vs. list[]
  1628. a = max(list[i], buffer[--k]);
  1629. } else {
  1630. // No overlap
  1631. buffer[k++] = a;
  1632. a = list[i];
  1633. }
  1634. i++; // Common if/else code factored out
  1635. polarity ^= 1;
  1636. } else if (b < a) { // take b
  1637. if (k > 0 && b <= buffer[k-1]) {
  1638. b = max(other[j], buffer[--k]);
  1639. } else {
  1640. buffer[k++] = b;
  1641. b = other[j];
  1642. }
  1643. j++;
  1644. polarity ^= 2;
  1645. } else { // a == b, take a, drop b
  1646. if (a == UNICODESET_HIGH) goto loop_end;
  1647. // This is symmetrical; it doesn't matter if
  1648. // we backtrack with a or b. - liu
  1649. if (k > 0 && a <= buffer[k-1]) {
  1650. a = max(list[i], buffer[--k]);
  1651. } else {
  1652. // No overlap
  1653. buffer[k++] = a;
  1654. a = list[i];
  1655. }
  1656. i++;
  1657. polarity ^= 1;
  1658. b = other[j++];
  1659. polarity ^= 2;
  1660. }
  1661. break;
  1662. case 3: // both second; take higher if unequal, and drop other
  1663. if (b <= a) { // take a
  1664. if (a == UNICODESET_HIGH) goto loop_end;
  1665. buffer[k++] = a;
  1666. } else { // take b
  1667. if (b == UNICODESET_HIGH) goto loop_end;
  1668. buffer[k++] = b;
  1669. }
  1670. a = list[i++];
  1671. polarity ^= 1; // factored common code
  1672. b = other[j++];
  1673. polarity ^= 2;
  1674. break;
  1675. case 1: // a second, b first; if b < a, overlap
  1676. if (a < b) { // no overlap, take a
  1677. buffer[k++] = a; a = list[i++]; polarity ^= 1;
  1678. } else if (b < a) { // OVERLAP, drop b
  1679. b = other[j++];
  1680. polarity ^= 2;
  1681. } else { // a == b, drop both!
  1682. if (a == UNICODESET_HIGH) goto loop_end;
  1683. a = list[i++];
  1684. polarity ^= 1;
  1685. b = other[j++];
  1686. polarity ^= 2;
  1687. }
  1688. break;
  1689. case 2: // a first, b second; if a < b, overlap
  1690. if (b < a) { // no overlap, take b
  1691. buffer[k++] = b;
  1692. b = other[j++];
  1693. polarity ^= 2;
  1694. } else if (a < b) { // OVERLAP, drop a
  1695. a = list[i++];
  1696. polarity ^= 1;
  1697. } else { // a == b, drop both!
  1698. if (a == UNICODESET_HIGH) goto loop_end;
  1699. a = list[i++];
  1700. polarity ^= 1;
  1701. b = other[j++];
  1702. polarity ^= 2;
  1703. }
  1704. break;
  1705. }
  1706. }
  1707. loop_end:
  1708. buffer[k++] = UNICODESET_HIGH; // terminate
  1709. len = k;
  1710. swapBuffers();
  1711. releasePattern();
  1712. }
  1713. // polarity = 0 is normal: x intersect y
  1714. // polarity = 2: x intersect ~y == set-minus
  1715. // polarity = 1: ~x intersect y
  1716. // polarity = 3: ~x intersect ~y
  1717. void UnicodeSet::retain(const UChar32* other, int32_t otherLen, int8_t polarity) {
  1718. if (isFrozen() || isBogus()) {
  1719. return;
  1720. }
  1721. if (!ensureBufferCapacity(len + otherLen)) {
  1722. return;
  1723. }
  1724. int32_t i = 0, j = 0, k = 0;
  1725. UChar32 a = list[i++];
  1726. UChar32 b = other[j++];
  1727. // change from xor is that we have to check overlapping pairs
  1728. // polarity bit 1 means a is second, bit 2 means b is.
  1729. for (;;) {
  1730. switch (polarity) {
  1731. case 0: // both first; drop the smaller
  1732. if (a < b) { // drop a
  1733. a = list[i++];
  1734. polarity ^= 1;
  1735. } else if (b < a) { // drop b
  1736. b = other[j++];
  1737. polarity ^= 2;
  1738. } else { // a == b, take one, drop other
  1739. if (a == UNICODESET_HIGH) goto loop_end;
  1740. buffer[k++] = a;
  1741. a = list[i++];
  1742. polarity ^= 1;
  1743. b = other[j++];
  1744. polarity ^= 2;
  1745. }
  1746. break;
  1747. case 3: // both second; take lower if unequal
  1748. if (a < b) { // take a
  1749. buffer[k++] = a;
  1750. a = list[i++];
  1751. polarity ^= 1;
  1752. } else if (b < a) { // take b
  1753. buffer[k++] = b;
  1754. b = other[j++];
  1755. polarity ^= 2;
  1756. } else { // a == b, take one, drop other
  1757. if (a == UNICODESET_HIGH) goto loop_end;
  1758. buffer[k++] = a;
  1759. a = list[i++];
  1760. polarity ^= 1;
  1761. b = other[j++];
  1762. polarity ^= 2;
  1763. }
  1764. break;
  1765. case 1: // a second, b first;
  1766. if (a < b) { // NO OVERLAP, drop a
  1767. a = list[i++];
  1768. polarity ^= 1;
  1769. } else if (b < a) { // OVERLAP, take b
  1770. buffer[k++] = b;
  1771. b = other[j++];
  1772. polarity ^= 2;
  1773. } else { // a == b, drop both!
  1774. if (a == UNICODESET_HIGH) goto loop_end;
  1775. a = list[i++];
  1776. polarity ^= 1;
  1777. b = other[j++];
  1778. polarity ^= 2;
  1779. }
  1780. break;
  1781. case 2: // a first, b second; if a < b, overlap
  1782. if (b < a) { // no overlap, drop b
  1783. b = other[j++];
  1784. polarity ^= 2;
  1785. } else if (a < b) { // OVERLAP, take a
  1786. buffer[k++] = a;
  1787. a = list[i++];
  1788. polarity ^= 1;
  1789. } else { // a == b, drop both!
  1790. if (a == UNICODESET_HIGH) goto loop_end;
  1791. a = list[i++];
  1792. polarity ^= 1;
  1793. b = other[j++];
  1794. polarity ^= 2;
  1795. }
  1796. break;
  1797. }
  1798. }
  1799. loop_end:
  1800. buffer[k++] = UNICODESET_HIGH; // terminate
  1801. len = k;
  1802. swapBuffers();
  1803. releasePattern();
  1804. }
  1805. /**
  1806. * Append the <code>toPattern()</code> representation of a
  1807. * string to the given <code>StringBuffer</code>.
  1808. */
  1809. void UnicodeSet::_appendToPat(UnicodeString& buf, const UnicodeString& s, UBool escapeUnprintable) {
  1810. UChar32 cp;
  1811. for (int32_t i = 0; i < s.length(); i += U16_LENGTH(cp)) {
  1812. _appendToPat(buf, cp = s.char32At(i), escapeUnprintable);
  1813. }
  1814. }
  1815. /**
  1816. * Append the <code>toPattern()</code> representation of a
  1817. * character to the given <code>StringBuffer</code>.
  1818. */
  1819. void UnicodeSet::_appendToPat(UnicodeString& buf, UChar32 c, UBool escapeUnprintable) {
  1820. if (escapeUnprintable ? ICU_Utility::isUnprintable(c) : ICU_Utility::shouldAlwaysBeEscaped(c)) {
  1821. // Use hex escape notation (\uxxxx or \Uxxxxxxxx) for anything
  1822. // unprintable
  1823. ICU_Utility::escape(buf, c);
  1824. return;
  1825. }
  1826. // Okay to let ':' pass through
  1827. switch (c) {
  1828. case u'[':
  1829. case u']':
  1830. case u'-':
  1831. case u'^':
  1832. case u'&':
  1833. case u'\\':
  1834. case u'{':
  1835. case u'}':
  1836. case u':':
  1837. case SymbolTable::SYMBOL_REF:
  1838. buf.append(u'\\');
  1839. break;
  1840. default:
  1841. // Escape whitespace
  1842. if (PatternProps::isWhiteSpace(c)) {
  1843. buf.append(u'\\');
  1844. }
  1845. break;
  1846. }
  1847. buf.append(c);
  1848. }
  1849. void UnicodeSet::_appendToPat(UnicodeString &result, UChar32 start, UChar32 end,
  1850. UBool escapeUnprintable) {
  1851. _appendToPat(result, start, escapeUnprintable);
  1852. if (start != end) {
  1853. if ((start+1) != end ||
  1854. // Avoid writing what looks like a lead+trail surrogate pair.
  1855. start == 0xdbff) {
  1856. result.append(u'-');
  1857. }
  1858. _appendToPat(result, end, escapeUnprintable);
  1859. }
  1860. }
  1861. /**
  1862. * Append a string representation of this set to result. This will be
  1863. * a cleaned version of the string passed to applyPattern(), if there
  1864. * is one. Otherwise it will be generated.
  1865. */
  1866. UnicodeString& UnicodeSet::_toPattern(UnicodeString& result,
  1867. UBool escapeUnprintable) const
  1868. {
  1869. if (pat != nullptr) {
  1870. int32_t i;
  1871. int32_t backslashCount = 0;
  1872. for (i=0; i<patLen; ) {
  1873. UChar32 c;
  1874. U16_NEXT(pat, i, patLen, c);
  1875. if (escapeUnprintable ?
  1876. ICU_Utility::isUnprintable(c) : ICU_Utility::shouldAlwaysBeEscaped(c)) {
  1877. // If the unprintable character is preceded by an odd
  1878. // number of backslashes, then it has been escaped.
  1879. // Before unescaping it, we delete the final
  1880. // backslash.
  1881. if ((backslashCount % 2) == 1) {
  1882. result.truncate(result.length() - 1);
  1883. }
  1884. ICU_Utility::escape(result, c);
  1885. backslashCount = 0;
  1886. } else {
  1887. result.append(c);
  1888. if (c == u'\\') {
  1889. ++backslashCount;
  1890. } else {
  1891. backslashCount = 0;
  1892. }
  1893. }
  1894. }
  1895. return result;
  1896. }
  1897. return _generatePattern(result, escapeUnprintable);
  1898. }
  1899. /**
  1900. * Returns a string representation of this set. If the result of
  1901. * calling this function is passed to a UnicodeSet constructor, it
  1902. * will produce another set that is equal to this one.
  1903. */
  1904. UnicodeString& UnicodeSet::toPattern(UnicodeString& result,
  1905. UBool escapeUnprintable) const
  1906. {
  1907. result.truncate(0);
  1908. return _toPattern(result, escapeUnprintable);
  1909. }
  1910. /**
  1911. * Generate and append a string representation of this set to result.
  1912. * This does not use this.pat, the cleaned up copy of the string
  1913. * passed to applyPattern().
  1914. */
  1915. UnicodeString& UnicodeSet::_generatePattern(UnicodeString& result,
  1916. UBool escapeUnprintable) const
  1917. {
  1918. result.append(u'[');
  1919. int32_t i = 0;
  1920. int32_t limit = len & ~1; // = 2 * getRangeCount()
  1921. // If the set contains at least 2 intervals and includes both
  1922. // MIN_VALUE and MAX_VALUE, then the inverse representation will
  1923. // be more economical.
  1924. // if (getRangeCount() >= 2 &&
  1925. // getRangeStart(0) == MIN_VALUE &&
  1926. // getRangeEnd(last) == MAX_VALUE)
  1927. // Invariant: list[len-1] == HIGH == MAX_VALUE + 1
  1928. // If limit == len then len is even and the last range ends with MAX_VALUE.
  1929. //
  1930. // *But* do not write the inverse (complement) if there are strings.
  1931. // Since ICU 70, the '^' performs a code point complement which removes all strings.
  1932. if (len >= 4 && list[0] == 0 && limit == len && !hasStrings()) {
  1933. // Emit the inverse
  1934. result.append(u'^');
  1935. // Offsetting the inversion list index by one lets us
  1936. // iterate over the ranges of the set complement.
  1937. i = 1;
  1938. --limit;
  1939. }
  1940. // Emit the ranges as pairs.
  1941. while (i < limit) {
  1942. UChar32 start = list[i]; // getRangeStart()
  1943. UChar32 end = list[i + 1] - 1; // getRangeEnd() = range limit minus one
  1944. if (!(0xd800 <= end && end <= 0xdbff)) {
  1945. _appendToPat(result, start, end, escapeUnprintable);
  1946. i += 2;
  1947. } else {
  1948. // The range ends with a lead surrogate.
  1949. // Avoid writing what looks like a lead+trail surrogate pair.
  1950. // 1. Postpone ranges that start with a lead surrogate code point.
  1951. int32_t firstLead = i;
  1952. while ((i += 2) < limit && list[i] <= 0xdbff) {}
  1953. int32_t firstAfterLead = i;
  1954. // 2. Write following ranges that start with a trail surrogate code point.
  1955. while (i < limit && (start = list[i]) <= 0xdfff) {
  1956. _appendToPat(result, start, list[i + 1] - 1, escapeUnprintable);
  1957. i += 2;
  1958. }
  1959. // 3. Now write the postponed ranges.
  1960. for (int j = firstLead; j < firstAfterLead; j += 2) {
  1961. _appendToPat(result, list[j], list[j + 1] - 1, escapeUnprintable);
  1962. }
  1963. }
  1964. }
  1965. if (strings != nullptr) {
  1966. for (int32_t i = 0; i<strings->size(); ++i) {
  1967. result.append(u'{');
  1968. _appendToPat(result,
  1969. *(const UnicodeString*) strings->elementAt(i),
  1970. escapeUnprintable);
  1971. result.append(u'}');
  1972. }
  1973. }
  1974. return result.append(u']');
  1975. }
  1976. /**
  1977. * Release existing cached pattern
  1978. */
  1979. void UnicodeSet::releasePattern() {
  1980. if (pat) {
  1981. uprv_free(pat);
  1982. pat = nullptr;
  1983. patLen = 0;
  1984. }
  1985. }
  1986. /**
  1987. * Set the new pattern to cache.
  1988. */
  1989. void UnicodeSet::setPattern(const char16_t *newPat, int32_t newPatLen) {
  1990. releasePattern();
  1991. pat = (char16_t *)uprv_malloc((newPatLen + 1) * sizeof(char16_t));
  1992. if (pat) {
  1993. patLen = newPatLen;
  1994. u_memcpy(pat, newPat, patLen);
  1995. pat[patLen] = 0;
  1996. }
  1997. // else we don't care if malloc failed. This was just a nice cache.
  1998. // We can regenerate an equivalent pattern later when requested.
  1999. }
  2000. UnicodeSet *UnicodeSet::freeze() {
  2001. if(!isFrozen() && !isBogus()) {
  2002. compact();
  2003. // Optimize contains() and span() and similar functions.
  2004. if (hasStrings()) {
  2005. stringSpan = new UnicodeSetStringSpan(*this, *strings, UnicodeSetStringSpan::ALL);
  2006. if (stringSpan == nullptr) {
  2007. setToBogus();
  2008. return this;
  2009. } else if (!stringSpan->needsStringSpanUTF16()) {
  2010. // All strings are irrelevant for span() etc. because
  2011. // all of each string's code points are contained in this set.
  2012. // Do not check needsStringSpanUTF8() because UTF-8 has at most as
  2013. // many relevant strings as UTF-16.
  2014. // (Thus needsStringSpanUTF8() implies needsStringSpanUTF16().)
  2015. delete stringSpan;
  2016. stringSpan = nullptr;
  2017. }
  2018. }
  2019. if (stringSpan == nullptr) {
  2020. // No span-relevant strings: Optimize for code point spans.
  2021. bmpSet=new BMPSet(list, len);
  2022. if (bmpSet == nullptr) { // Check for memory allocation error.
  2023. setToBogus();
  2024. }
  2025. }
  2026. }
  2027. return this;
  2028. }
  2029. int32_t UnicodeSet::span(const char16_t *s, int32_t length, USetSpanCondition spanCondition) const {
  2030. if(length>0 && bmpSet!=nullptr) {
  2031. return (int32_t)(bmpSet->span(s, s+length, spanCondition)-s);
  2032. }
  2033. if(length<0) {
  2034. length=u_strlen(s);
  2035. }
  2036. if(length==0) {
  2037. return 0;
  2038. }
  2039. if(stringSpan!=nullptr) {
  2040. return stringSpan->span(s, length, spanCondition);
  2041. } else if(hasStrings()) {
  2042. uint32_t which= spanCondition==USET_SPAN_NOT_CONTAINED ?
  2043. UnicodeSetStringSpan::FWD_UTF16_NOT_CONTAINED :
  2044. UnicodeSetStringSpan::FWD_UTF16_CONTAINED;
  2045. UnicodeSetStringSpan strSpan(*this, *strings, which);
  2046. if(strSpan.needsStringSpanUTF16()) {
  2047. return strSpan.span(s, length, spanCondition);
  2048. }
  2049. }
  2050. if(spanCondition!=USET_SPAN_NOT_CONTAINED) {
  2051. spanCondition=USET_SPAN_CONTAINED; // Pin to 0/1 values.
  2052. }
  2053. UChar32 c;
  2054. int32_t start=0, prev=0;
  2055. do {
  2056. U16_NEXT(s, start, length, c);
  2057. if(spanCondition!=contains(c)) {
  2058. break;
  2059. }
  2060. } while((prev=start)<length);
  2061. return prev;
  2062. }
  2063. int32_t UnicodeSet::spanBack(const char16_t *s, int32_t length, USetSpanCondition spanCondition) const {
  2064. if(length>0 && bmpSet!=nullptr) {
  2065. return (int32_t)(bmpSet->spanBack(s, s+length, spanCondition)-s);
  2066. }
  2067. if(length<0) {
  2068. length=u_strlen(s);
  2069. }
  2070. if(length==0) {
  2071. return 0;
  2072. }
  2073. if(stringSpan!=nullptr) {
  2074. return stringSpan->spanBack(s, length, spanCondition);
  2075. } else if(hasStrings()) {
  2076. uint32_t which= spanCondition==USET_SPAN_NOT_CONTAINED ?
  2077. UnicodeSetStringSpan::BACK_UTF16_NOT_CONTAINED :
  2078. UnicodeSetStringSpan::BACK_UTF16_CONTAINED;
  2079. UnicodeSetStringSpan strSpan(*this, *strings, which);
  2080. if(strSpan.needsStringSpanUTF16()) {
  2081. return strSpan.spanBack(s, length, spanCondition);
  2082. }
  2083. }
  2084. if(spanCondition!=USET_SPAN_NOT_CONTAINED) {
  2085. spanCondition=USET_SPAN_CONTAINED; // Pin to 0/1 values.
  2086. }
  2087. UChar32 c;
  2088. int32_t prev=length;
  2089. do {
  2090. U16_PREV(s, 0, length, c);
  2091. if(spanCondition!=contains(c)) {
  2092. break;
  2093. }
  2094. } while((prev=length)>0);
  2095. return prev;
  2096. }
  2097. int32_t UnicodeSet::spanUTF8(const char *s, int32_t length, USetSpanCondition spanCondition) const {
  2098. if(length>0 && bmpSet!=nullptr) {
  2099. const uint8_t *s0=(const uint8_t *)s;
  2100. return (int32_t)(bmpSet->spanUTF8(s0, length, spanCondition)-s0);
  2101. }
  2102. if(length<0) {
  2103. length=(int32_t)uprv_strlen(s);
  2104. }
  2105. if(length==0) {
  2106. return 0;
  2107. }
  2108. if(stringSpan!=nullptr) {
  2109. return stringSpan->spanUTF8((const uint8_t *)s, length, spanCondition);
  2110. } else if(hasStrings()) {
  2111. uint32_t which= spanCondition==USET_SPAN_NOT_CONTAINED ?
  2112. UnicodeSetStringSpan::FWD_UTF8_NOT_CONTAINED :
  2113. UnicodeSetStringSpan::FWD_UTF8_CONTAINED;
  2114. UnicodeSetStringSpan strSpan(*this, *strings, which);
  2115. if(strSpan.needsStringSpanUTF8()) {
  2116. return strSpan.spanUTF8((const uint8_t *)s, length, spanCondition);
  2117. }
  2118. }
  2119. if(spanCondition!=USET_SPAN_NOT_CONTAINED) {
  2120. spanCondition=USET_SPAN_CONTAINED; // Pin to 0/1 values.
  2121. }
  2122. UChar32 c;
  2123. int32_t start=0, prev=0;
  2124. do {
  2125. U8_NEXT_OR_FFFD(s, start, length, c);
  2126. if(spanCondition!=contains(c)) {
  2127. break;
  2128. }
  2129. } while((prev=start)<length);
  2130. return prev;
  2131. }
  2132. int32_t UnicodeSet::spanBackUTF8(const char *s, int32_t length, USetSpanCondition spanCondition) const {
  2133. if(length>0 && bmpSet!=nullptr) {
  2134. const uint8_t *s0=(const uint8_t *)s;
  2135. return bmpSet->spanBackUTF8(s0, length, spanCondition);
  2136. }
  2137. if(length<0) {
  2138. length=(int32_t)uprv_strlen(s);
  2139. }
  2140. if(length==0) {
  2141. return 0;
  2142. }
  2143. if(stringSpan!=nullptr) {
  2144. return stringSpan->spanBackUTF8((const uint8_t *)s, length, spanCondition);
  2145. } else if(hasStrings()) {
  2146. uint32_t which= spanCondition==USET_SPAN_NOT_CONTAINED ?
  2147. UnicodeSetStringSpan::BACK_UTF8_NOT_CONTAINED :
  2148. UnicodeSetStringSpan::BACK_UTF8_CONTAINED;
  2149. UnicodeSetStringSpan strSpan(*this, *strings, which);
  2150. if(strSpan.needsStringSpanUTF8()) {
  2151. return strSpan.spanBackUTF8((const uint8_t *)s, length, spanCondition);
  2152. }
  2153. }
  2154. if(spanCondition!=USET_SPAN_NOT_CONTAINED) {
  2155. spanCondition=USET_SPAN_CONTAINED; // Pin to 0/1 values.
  2156. }
  2157. UChar32 c;
  2158. int32_t prev=length;
  2159. do {
  2160. U8_PREV_OR_FFFD(s, 0, length, c);
  2161. if(spanCondition!=contains(c)) {
  2162. break;
  2163. }
  2164. } while((prev=length)>0);
  2165. return prev;
  2166. }
  2167. U_NAMESPACE_END