uniset.cpp 71 KB

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