Path: blob/master/src/java.base/share/classes/jdk/internal/icu/text/UnicodeSet.java
41161 views
/*1* Copyright (c) 2005, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26*******************************************************************************27* Copyright (C) 1996-2015, International Business Machines Corporation and28* others. All Rights Reserved.29*******************************************************************************30*/31package jdk.internal.icu.text;3233import java.text.ParsePosition;34import java.util.ArrayList;35import java.util.TreeSet;3637import jdk.internal.icu.impl.BMPSet;38import jdk.internal.icu.impl.UCharacterProperty;39import jdk.internal.icu.impl.UnicodeSetStringSpan;40import jdk.internal.icu.impl.Utility;41import jdk.internal.icu.lang.UCharacter;42import jdk.internal.icu.util.OutputInt;43import jdk.internal.icu.util.VersionInfo;4445/**46* A mutable set of Unicode characters and multicharacter strings.47* Objects of this class represent <em>character classes</em> used48* in regular expressions. A character specifies a subset of Unicode49* code points. Legal code points are U+0000 to U+10FFFF, inclusive.50*51* Note: method freeze() will not only make the set immutable, but52* also makes important methods much higher performance:53* contains(c), containsNone(...), span(...), spanBack(...) etc.54* After the object is frozen, any subsequent call that wants to change55* the object will throw UnsupportedOperationException.56*57* <p>The UnicodeSet class is not designed to be subclassed.58*59* <p><code>UnicodeSet</code> supports two APIs. The first is the60* <em>operand</em> API that allows the caller to modify the value of61* a <code>UnicodeSet</code> object. It conforms to Java 2's62* <code>java.util.Set</code> interface, although63* <code>UnicodeSet</code> does not actually implement that64* interface. All methods of <code>Set</code> are supported, with the65* modification that they take a character range or single character66* instead of an <code>Object</code>, and they take a67* <code>UnicodeSet</code> instead of a <code>Collection</code>. The68* operand API may be thought of in terms of boolean logic: a boolean69* OR is implemented by <code>add</code>, a boolean AND is implemented70* by <code>retain</code>, a boolean XOR is implemented by71* <code>complement</code> taking an argument, and a boolean NOT is72* implemented by <code>complement</code> with no argument. In terms73* of traditional set theory function names, <code>add</code> is a74* union, <code>retain</code> is an intersection, <code>remove</code>75* is an asymmetric difference, and <code>complement</code> with no76* argument is a set complement with respect to the superset range77* <code>MIN_VALUE-MAX_VALUE</code>78*79* <p>The second API is the80* <code>applyPattern()</code>/<code>toPattern()</code> API from the81* <code>java.text.Format</code>-derived classes. Unlike the82* methods that add characters, add categories, and control the logic83* of the set, the method <code>applyPattern()</code> sets all84* attributes of a <code>UnicodeSet</code> at once, based on a85* string pattern.86*87* <p><b>Pattern syntax</b></p>88*89* Patterns are accepted by the constructors and the90* <code>applyPattern()</code> methods and returned by the91* <code>toPattern()</code> method. These patterns follow a syntax92* similar to that employed by version 8 regular expression character93* classes. Here are some simple examples:94*95* <blockquote>96* <table>97* <tr align="top">98* <td nowrap valign="top" align="left"><code>[]</code></td>99* <td valign="top">No characters</td>100* </tr><tr align="top">101* <td nowrap valign="top" align="left"><code>[a]</code></td>102* <td valign="top">The character 'a'</td>103* </tr><tr align="top">104* <td nowrap valign="top" align="left"><code>[ae]</code></td>105* <td valign="top">The characters 'a' and 'e'</td>106* </tr>107* <tr>108* <td nowrap valign="top" align="left"><code>[a-e]</code></td>109* <td valign="top">The characters 'a' through 'e' inclusive, in Unicode code110* point order</td>111* </tr>112* <tr>113* <td nowrap valign="top" align="left"><code>[\\u4E01]</code></td>114* <td valign="top">The character U+4E01</td>115* </tr>116* <tr>117* <td nowrap valign="top" align="left"><code>[a{ab}{ac}]</code></td>118* <td valign="top">The character 'a' and the multicharacter strings "ab" and119* "ac"</td>120* </tr>121* <tr>122* <td nowrap valign="top" align="left"><code>[\p{Lu}]</code></td>123* <td valign="top">All characters in the general category Uppercase Letter</td>124* </tr>125* </table>126* </blockquote>127*128* Any character may be preceded by a backslash in order to remove any special129* meaning. White space characters, as defined by the Unicode Pattern_White_Space property, are130* ignored, unless they are escaped.131*132* <p>Property patterns specify a set of characters having a certain133* property as defined by the Unicode standard. Both the POSIX-like134* "[:Lu:]" and the Perl-like syntax "\p{Lu}" are recognized. For a135* complete list of supported property patterns, see the User's Guide136* for UnicodeSet at137* <a href="http://www.icu-project.org/userguide/unicodeSet.html">138* http://www.icu-project.org/userguide/unicodeSet.html</a>.139* Actual determination of property data is defined by the underlying140* Unicode database as implemented by UCharacter.141*142* <p>Patterns specify individual characters, ranges of characters, and143* Unicode property sets. When elements are concatenated, they144* specify their union. To complement a set, place a '^' immediately145* after the opening '['. Property patterns are inverted by modifying146* their delimiters; "[:^foo]" and "\P{foo}". In any other location,147* '^' has no special meaning.148*149* <p>Ranges are indicated by placing two a '-' between two150* characters, as in "a-z". This specifies the range of all151* characters from the left to the right, in Unicode order. If the152* left character is greater than or equal to the153* right character it is a syntax error. If a '-' occurs as the first154* character after the opening '[' or '[^', or if it occurs as the155* last character before the closing ']', then it is taken as a156* literal. Thus "[a\\-b]", "[-ab]", and "[ab-]" all indicate the same157* set of three characters, 'a', 'b', and '-'.158*159* <p>Sets may be intersected using the {@literal '&'} operator or the asymmetric160* set difference may be taken using the '-' operator, for example,161* "{@code [[:L:]&[\\u0000-\\u0FFF]]}" indicates the set of all Unicode letters162* with values less than 4096. Operators ({@literal '&'} and '|') have equal163* precedence and bind left-to-right. Thus164* "[[:L:]-[a-z]-[\\u0100-\\u01FF]]" is equivalent to165* "[[[:L:]-[a-z]]-[\\u0100-\\u01FF]]". This only really matters for166* difference; intersection is commutative.167*168* <table>169* <tr valign=top><td nowrap><code>[a]</code><td>The set containing 'a'170* <tr valign=top><td nowrap><code>[a-z]</code><td>The set containing 'a'171* through 'z' and all letters in between, in Unicode order172* <tr valign=top><td nowrap><code>[^a-z]</code><td>The set containing173* all characters but 'a' through 'z',174* that is, U+0000 through 'a'-1 and 'z'+1 through U+10FFFF175* <tr valign=top><td nowrap><code>[[<em>pat1</em>][<em>pat2</em>]]</code>176* <td>The union of sets specified by <em>pat1</em> and <em>pat2</em>177* <tr valign=top><td nowrap><code>[[<em>pat1</em>]&[<em>pat2</em>]]</code>178* <td>The intersection of sets specified by <em>pat1</em> and <em>pat2</em>179* <tr valign=top><td nowrap><code>[[<em>pat1</em>]-[<em>pat2</em>]]</code>180* <td>The asymmetric difference of sets specified by <em>pat1</em> and181* <em>pat2</em>182* <tr valign=top><td nowrap><code>[:Lu:] or \p{Lu}</code>183* <td>The set of characters having the specified184* Unicode property; in185* this case, Unicode uppercase letters186* <tr valign=top><td nowrap><code>[:^Lu:] or \P{Lu}</code>187* <td>The set of characters <em>not</em> having the given188* Unicode property189* </table>190*191* <p><b>Warning</b>: you cannot add an empty string ("") to a UnicodeSet.</p>192*193* <p><b>Formal syntax</b></p>194*195* <blockquote>196* <table>197* <tr align="top">198* <td nowrap valign="top" align="right"><code>pattern := </code></td>199* <td valign="top"><code>('[' '^'? item* ']') |200* property</code></td>201* </tr>202* <tr align="top">203* <td nowrap valign="top" align="right"><code>item := </code></td>204* <td valign="top"><code>char | (char '-' char) | pattern-expr<br>205* </code></td>206* </tr>207* <tr align="top">208* <td nowrap valign="top" align="right"><code>pattern-expr := </code></td>209* <td valign="top"><code>pattern | pattern-expr pattern |210* pattern-expr op pattern<br>211* </code></td>212* </tr>213* <tr align="top">214* <td nowrap valign="top" align="right"><code>op := </code></td>215* <td valign="top"><code>'&' | '-'<br>216* </code></td>217* </tr>218* <tr align="top">219* <td nowrap valign="top" align="right"><code>special := </code></td>220* <td valign="top"><code>'[' | ']' | '-'<br>221* </code></td>222* </tr>223* <tr align="top">224* <td nowrap valign="top" align="right"><code>char := </code></td>225* <td valign="top"><em>any character that is not</em><code> special<br>226* | ('\\' </code><em>any character</em><code>)<br>227* | ('\u' hex hex hex hex)<br>228* </code></td>229* </tr>230* <tr align="top">231* <td nowrap valign="top" align="right"><code>hex := </code></td>232* <td valign="top"><em>any character for which233* </em><code>Character.digit(c, 16)</code><em>234* returns a non-negative result</em></td>235* </tr>236* <tr>237* <td nowrap valign="top" align="right"><code>property := </code></td>238* <td valign="top"><em>a Unicode property set pattern</em></td>239* </tr>240* </table>241* <br>242* <table border="1">243* <tr>244* <td>Legend: <table>245* <tr>246* <td nowrap valign="top"><code>a := b</code></td>247* <td width="20" valign="top"> </td>248* <td valign="top"><code>a</code> may be replaced by <code>b</code> </td>249* </tr>250* <tr>251* <td nowrap valign="top"><code>a?</code></td>252* <td valign="top"></td>253* <td valign="top">zero or one instance of <code>a</code><br>254* </td>255* </tr>256* <tr>257* <td nowrap valign="top"><code>a*</code></td>258* <td valign="top"></td>259* <td valign="top">one or more instances of <code>a</code><br>260* </td>261* </tr>262* <tr>263* <td nowrap valign="top"><code>a | b</code></td>264* <td valign="top"></td>265* <td valign="top">either <code>a</code> or <code>b</code><br>266* </td>267* </tr>268* <tr>269* <td nowrap valign="top"><code>'a'</code></td>270* <td valign="top"></td>271* <td valign="top">the literal string between the quotes </td>272* </tr>273* </table>274* </td>275* </tr>276* </table>277* </blockquote>278* <p>To iterate over contents of UnicodeSet, the following are available:279* <ul><li>{@link #ranges()} to iterate through the ranges</li>280* <li>{@link #strings()} to iterate through the strings</li>281* <li>{@link #iterator()} to iterate through the entire contents in a single loop.282* That method is, however, not particularly efficient, since it "boxes" each code point into a String.283* </ul>284* All of the above can be used in <b>for</b> loops.285* The {@link com.ibm.icu.text.UnicodeSetIterator UnicodeSetIterator} can also be used, but not in <b>for</b> loops.286* <p>To replace, count elements, or delete spans, see {@link com.ibm.icu.text.UnicodeSetSpanner UnicodeSetSpanner}.287*288* @author Alan Liu289* @stable ICU 2.0290*/291public class UnicodeSet {292293private static final int LOW = 0x000000; // LOW <= all valid values. ZERO for codepoints294private static final int HIGH = 0x110000; // HIGH > all valid values. 10000 for code units.295// 110000 for codepoints296297/**298* Minimum value that can be stored in a UnicodeSet.299* @stable ICU 2.0300*/301public static final int MIN_VALUE = LOW;302303/**304* Maximum value that can be stored in a UnicodeSet.305* @stable ICU 2.0306*/307public static final int MAX_VALUE = HIGH - 1;308309private int len; // length used; list may be longer to minimize reallocs310private int[] list; // MUST be terminated with HIGH311private int[] rangeList; // internal buffer312private int[] buffer; // internal buffer313314// NOTE: normally the field should be of type SortedSet; but that is missing a public clone!!315// is not private so that UnicodeSetIterator can get access316TreeSet<String> strings = new TreeSet<String>();317318/**319* The pattern representation of this set. This may not be the320* most economical pattern. It is the pattern supplied to321* applyPattern(), with variables substituted and whitespace322* removed. For sets constructed without applyPattern(), or323* modified using the non-pattern API, this string will be null,324* indicating that toPattern() must generate a pattern325* representation from the inversion list.326*/327328private static final int START_EXTRA = 16; // initial storage. Must be >= 0329private static final int GROW_EXTRA = START_EXTRA; // extra amount for growth. Must be >= 0330331private static UnicodeSet INCLUSION = null;332333private volatile BMPSet bmpSet; // The set is frozen if bmpSet or stringSpan is not null.334private volatile UnicodeSetStringSpan stringSpan;335336//----------------------------------------------------------------337// Public API338//----------------------------------------------------------------339340/**341* Constructs an empty set.342* @stable ICU 2.0343*/344private UnicodeSet() {345list = new int[1 + START_EXTRA];346list[len++] = HIGH;347}348349/**350* Constructs a copy of an existing set.351* @stable ICU 2.0352*/353private UnicodeSet(UnicodeSet other) {354set(other);355}356357/**358* Constructs a set containing the given range. If <code>end >359* start</code> then an empty set is created.360*361* @param start first character, inclusive, of range362* @param end last character, inclusive, of range363* @stable ICU 2.0364*/365public UnicodeSet(int start, int end) {366this();367complement(start, end);368}369370/**371* Constructs a set from the given pattern. See the class description372* for the syntax of the pattern language. Whitespace is ignored.373* @param pattern a string specifying what characters are in the set374* @exception java.lang.IllegalArgumentException if the pattern contains375* a syntax error.376* @stable ICU 2.0377*/378public UnicodeSet(String pattern) {379this();380applyPattern(pattern, null);381}382383/**384* Make this object represent the same set as <code>other</code>.385* @param other a <code>UnicodeSet</code> whose value will be386* copied to this object387* @stable ICU 2.0388*/389public UnicodeSet set(UnicodeSet other) {390checkFrozen();391list = other.list.clone();392len = other.len;393strings = new TreeSet<String>(other.strings);394return this;395}396397/**398* Returns the number of elements in this set (its cardinality)399* Note than the elements of a set may include both individual400* codepoints and strings.401*402* @return the number of elements in this set (its cardinality).403* @stable ICU 2.0404*/405public int size() {406int n = 0;407int count = getRangeCount();408for (int i = 0; i < count; ++i) {409n += getRangeEnd(i) - getRangeStart(i) + 1;410}411return n + strings.size();412}413414// for internal use, after checkFrozen has been called415private UnicodeSet add_unchecked(int start, int end) {416if (start < MIN_VALUE || start > MAX_VALUE) {417throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(start, 6));418}419if (end < MIN_VALUE || end > MAX_VALUE) {420throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(end, 6));421}422if (start < end) {423add(range(start, end), 2, 0);424} else if (start == end) {425add(start);426}427return this;428}429430/**431* Adds the specified character to this set if it is not already432* present. If this set already contains the specified character,433* the call leaves this set unchanged.434* @stable ICU 2.0435*/436public final UnicodeSet add(int c) {437checkFrozen();438return add_unchecked(c);439}440441// for internal use only, after checkFrozen has been called442private final UnicodeSet add_unchecked(int c) {443if (c < MIN_VALUE || c > MAX_VALUE) {444throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(c, 6));445}446447// find smallest i such that c < list[i]448// if odd, then it is IN the set449// if even, then it is OUT of the set450int i = findCodePoint(c);451452// already in set?453if ((i & 1) != 0) return this;454455// HIGH is 0x110000456// assert(list[len-1] == HIGH);457458// empty = [HIGH]459// [start_0, limit_0, start_1, limit_1, HIGH]460461// [..., start_k-1, limit_k-1, start_k, limit_k, ..., HIGH]462// ^463// list[i]464465// i == 0 means c is before the first range466467if (c == list[i]-1) {468// c is before start of next range469list[i] = c;470// if we touched the HIGH mark, then add a new one471if (c == MAX_VALUE) {472ensureCapacity(len+1);473list[len++] = HIGH;474}475if (i > 0 && c == list[i-1]) {476// collapse adjacent ranges477478// [..., start_k-1, c, c, limit_k, ..., HIGH]479// ^480// list[i]481System.arraycopy(list, i+1, list, i-1, len-i-1);482len -= 2;483}484}485486else if (i > 0 && c == list[i-1]) {487// c is after end of prior range488list[i-1]++;489// no need to chcek for collapse here490}491492else {493// At this point we know the new char is not adjacent to494// any existing ranges, and it is not 10FFFF.495496497// [..., start_k-1, limit_k-1, start_k, limit_k, ..., HIGH]498// ^499// list[i]500501// [..., start_k-1, limit_k-1, c, c+1, start_k, limit_k, ..., HIGH]502// ^503// list[i]504505// Don't use ensureCapacity() to save on copying.506// NOTE: This has no measurable impact on performance,507// but it might help in some usage patterns.508if (len+2 > list.length) {509int[] temp = new int[len + 2 + GROW_EXTRA];510if (i != 0) System.arraycopy(list, 0, temp, 0, i);511System.arraycopy(list, i, temp, i+2, len-i);512list = temp;513} else {514System.arraycopy(list, i, list, i+2, len-i);515}516517list[i] = c;518list[i+1] = c+1;519len += 2;520}521522return this;523}524525/**526* Adds the specified multicharacter to this set if it is not already527* present. If this set already contains the multicharacter,528* the call leaves this set unchanged.529* Thus {@code "ch" => {"ch"}}530* <br><b>Warning: you cannot add an empty string ("") to a UnicodeSet.</b>531* @param s the source string532* @return this object, for chaining533* @stable ICU 2.0534*/535public final UnicodeSet add(CharSequence s) {536checkFrozen();537int cp = getSingleCP(s);538if (cp < 0) {539strings.add(s.toString());540} else {541add_unchecked(cp, cp);542}543return this;544}545546/**547* Utility for getting code point from single code point CharSequence.548* See the public UTF16.getSingleCodePoint()549* @return a code point IF the string consists of a single one.550* otherwise returns -1.551* @param s to test552*/553private static int getSingleCP(CharSequence s) {554if (s.length() < 1) {555throw new IllegalArgumentException("Can't use zero-length strings in UnicodeSet");556}557if (s.length() > 2) return -1;558if (s.length() == 1) return s.charAt(0);559560// at this point, len = 2561int cp = UTF16.charAt(s, 0);562if (cp > 0xFFFF) { // is surrogate pair563return cp;564}565return -1;566}567568/**569* Complements the specified range in this set. Any character in570* the range will be removed if it is in this set, or will be571* added if it is not in this set. If {@code end > start}572* then an empty range is complemented, leaving the set unchanged.573*574* @param start first character, inclusive, of range to be removed575* from this set.576* @param end last character, inclusive, of range to be removed577* from this set.578* @stable ICU 2.0579*/580public UnicodeSet complement(int start, int end) {581checkFrozen();582if (start < MIN_VALUE || start > MAX_VALUE) {583throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(start, 6));584}585if (end < MIN_VALUE || end > MAX_VALUE) {586throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(end, 6));587}588if (start <= end) {589xor(range(start, end), 2, 0);590}591return this;592}593594/**595* Returns true if this set contains the given character.596* @param c character to be checked for containment597* @return true if the test condition is met598* @stable ICU 2.0599*/600public boolean contains(int c) {601if (c < MIN_VALUE || c > MAX_VALUE) {602throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(c, 6));603}604if (bmpSet != null) {605return bmpSet.contains(c);606}607if (stringSpan != null) {608return stringSpan.contains(c);609}610611/*612// Set i to the index of the start item greater than ch613// We know we will terminate without length test!614int i = -1;615while (true) {616if (c < list[++i]) break;617}618*/619620int i = findCodePoint(c);621622return ((i & 1) != 0); // return true if odd623}624625/**626* Returns the smallest value i such that c < list[i]. Caller627* must ensure that c is a legal value or this method will enter628* an infinite loop. This method performs a binary search.629* @param c a character in the range MIN_VALUE..MAX_VALUE630* inclusive631* @return the smallest integer i in the range 0..len-1,632* inclusive, such that c < list[i]633*/634private final int findCodePoint(int c) {635/* Examples:636findCodePoint(c)637set list[] c=0 1 3 4 7 8638=== ============== ===========639[] [110000] 0 0 0 0 0 0640[\u0000-\u0003] [0, 4, 110000] 1 1 1 2 2 2641[\u0004-\u0007] [4, 8, 110000] 0 0 0 1 1 2642[:all:] [0, 110000] 1 1 1 1 1 1643*/644645// Return the smallest i such that c < list[i]. Assume646// list[len - 1] == HIGH and that c is legal (0..HIGH-1).647if (c < list[0]) return 0;648// High runner test. c is often after the last range, so an649// initial check for this condition pays off.650if (len >= 2 && c >= list[len-2]) return len-1;651int lo = 0;652int hi = len - 1;653// invariant: c >= list[lo]654// invariant: c < list[hi]655for (;;) {656int i = (lo + hi) >>> 1;657if (i == lo) return hi;658if (c < list[i]) {659hi = i;660} else {661lo = i;662}663}664}665666/**667* Retains only the elements in this set that are contained in the668* specified set. In other words, removes from this set all of669* its elements that are not contained in the specified set. This670* operation effectively modifies this set so that its value is671* the <i>intersection</i> of the two sets.672*673* @param c set that defines which elements this set will retain.674* @stable ICU 2.0675*/676public UnicodeSet retainAll(UnicodeSet c) {677checkFrozen();678retain(c.list, c.len, 0);679strings.retainAll(c.strings);680return this;681}682683/**684* Removes all of the elements from this set. This set will be685* empty after this call returns.686* @stable ICU 2.0687*/688public UnicodeSet clear() {689checkFrozen();690list[0] = HIGH;691len = 1;692strings.clear();693return this;694}695696/**697* Iteration method that returns the number of ranges contained in698* this set.699* @see #getRangeStart700* @see #getRangeEnd701* @stable ICU 2.0702*/703public int getRangeCount() {704return len/2;705}706707/**708* Iteration method that returns the first character in the709* specified range of this set.710* @exception ArrayIndexOutOfBoundsException if index is outside711* the range <code>0..getRangeCount()-1</code>712* @see #getRangeCount713* @see #getRangeEnd714* @stable ICU 2.0715*/716public int getRangeStart(int index) {717return list[index*2];718}719720/**721* Iteration method that returns the last character in the722* specified range of this set.723* @exception ArrayIndexOutOfBoundsException if index is outside724* the range <code>0..getRangeCount()-1</code>725* @see #getRangeStart726* @see #getRangeEnd727* @stable ICU 2.0728*/729public int getRangeEnd(int index) {730return (list[index*2 + 1] - 1);731}732733//----------------------------------------------------------------734// Implementation: Pattern parsing735//----------------------------------------------------------------736737/**738* Parses the given pattern, starting at the given position. The character739* at pattern.charAt(pos.getIndex()) must be '[', or the parse fails.740* Parsing continues until the corresponding closing ']'. If a syntax error741* is encountered between the opening and closing brace, the parse fails.742* Upon return from a successful parse, the ParsePosition is updated to743* point to the character following the closing ']', and an inversion744* list for the parsed pattern is returned. This method745* calls itself recursively to parse embedded subpatterns.746*747* @param pattern the string containing the pattern to be parsed. The748* portion of the string from pos.getIndex(), which must be a '[', to the749* corresponding closing ']', is parsed.750* @param pos upon entry, the position at which to being parsing. The751* character at pattern.charAt(pos.getIndex()) must be a '['. Upon return752* from a successful parse, pos.getIndex() is either the character after the753* closing ']' of the parsed pattern, or pattern.length() if the closing ']'754* is the last character of the pattern string.755* @return an inversion list for the parsed substring756* of <code>pattern</code>757* @exception java.lang.IllegalArgumentException if the parse fails.758*/759private UnicodeSet applyPattern(String pattern,760ParsePosition pos) {761if ("[:age=3.2:]".equals(pattern)) {762checkFrozen();763VersionInfo version = VersionInfo.getInstance("3.2");764applyFilter(new VersionFilter(version), UCharacterProperty.SRC_PROPSVEC);765} else {766throw new IllegalStateException("UnicodeSet.applyPattern(unexpected pattern "767+ pattern + ")");768}769770return this;771}772773//----------------------------------------------------------------774// Implementation: Utility methods775//----------------------------------------------------------------776777private void ensureCapacity(int newLen) {778if (newLen <= list.length) return;779int[] temp = new int[newLen + GROW_EXTRA];780System.arraycopy(list, 0, temp, 0, len);781list = temp;782}783784private void ensureBufferCapacity(int newLen) {785if (buffer != null && newLen <= buffer.length) return;786buffer = new int[newLen + GROW_EXTRA];787}788789/**790* Assumes start <= end.791*/792private int[] range(int start, int end) {793if (rangeList == null) {794rangeList = new int[] { start, end+1, HIGH };795} else {796rangeList[0] = start;797rangeList[1] = end+1;798}799return rangeList;800}801802//----------------------------------------------------------------803// Implementation: Fundamental operations804//----------------------------------------------------------------805806// polarity = 0, 3 is normal: x xor y807// polarity = 1, 2: x xor ~y == x === y808809private UnicodeSet xor(int[] other, int otherLen, int polarity) {810ensureBufferCapacity(len + otherLen);811int i = 0, j = 0, k = 0;812int a = list[i++];813int b;814if (polarity == 1 || polarity == 2) {815b = LOW;816if (other[j] == LOW) { // skip base if already LOW817++j;818b = other[j];819}820} else {821b = other[j++];822}823// simplest of all the routines824// sort the values, discarding identicals!825while (true) {826if (a < b) {827buffer[k++] = a;828a = list[i++];829} else if (b < a) {830buffer[k++] = b;831b = other[j++];832} else if (a != HIGH) { // at this point, a == b833// discard both values!834a = list[i++];835b = other[j++];836} else { // DONE!837buffer[k++] = HIGH;838len = k;839break;840}841}842// swap list and buffer843int[] temp = list;844list = buffer;845buffer = temp;846return this;847}848849// polarity = 0 is normal: x union y850// polarity = 2: x union ~y851// polarity = 1: ~x union y852// polarity = 3: ~x union ~y853854private UnicodeSet add(int[] other, int otherLen, int polarity) {855ensureBufferCapacity(len + otherLen);856int i = 0, j = 0, k = 0;857int a = list[i++];858int b = other[j++];859// change from xor is that we have to check overlapping pairs860// polarity bit 1 means a is second, bit 2 means b is.861main:862while (true) {863switch (polarity) {864case 0: // both first; take lower if unequal865if (a < b) { // take a866// Back up over overlapping ranges in buffer[]867if (k > 0 && a <= buffer[k-1]) {868// Pick latter end value in buffer[] vs. list[]869a = max(list[i], buffer[--k]);870} else {871// No overlap872buffer[k++] = a;873a = list[i];874}875i++; // Common if/else code factored out876polarity ^= 1;877} else if (b < a) { // take b878if (k > 0 && b <= buffer[k-1]) {879b = max(other[j], buffer[--k]);880} else {881buffer[k++] = b;882b = other[j];883}884j++;885polarity ^= 2;886} else { // a == b, take a, drop b887if (a == HIGH) break main;888// This is symmetrical; it doesn't matter if889// we backtrack with a or b. - liu890if (k > 0 && a <= buffer[k-1]) {891a = max(list[i], buffer[--k]);892} else {893// No overlap894buffer[k++] = a;895a = list[i];896}897i++;898polarity ^= 1;899b = other[j++]; polarity ^= 2;900}901break;902case 3: // both second; take higher if unequal, and drop other903if (b <= a) { // take a904if (a == HIGH) break main;905buffer[k++] = a;906} else { // take b907if (b == HIGH) break main;908buffer[k++] = b;909}910a = list[i++]; polarity ^= 1; // factored common code911b = other[j++]; polarity ^= 2;912break;913case 1: // a second, b first; if b < a, overlap914if (a < b) { // no overlap, take a915buffer[k++] = a; a = list[i++]; polarity ^= 1;916} else if (b < a) { // OVERLAP, drop b917b = other[j++]; polarity ^= 2;918} else { // a == b, drop both!919if (a == HIGH) break main;920a = list[i++]; polarity ^= 1;921b = other[j++]; polarity ^= 2;922}923break;924case 2: // a first, b second; if a < b, overlap925if (b < a) { // no overlap, take b926buffer[k++] = b; b = other[j++]; polarity ^= 2;927} else if (a < b) { // OVERLAP, drop a928a = list[i++]; polarity ^= 1;929} else { // a == b, drop both!930if (a == HIGH) break main;931a = list[i++]; polarity ^= 1;932b = other[j++]; polarity ^= 2;933}934break;935}936}937buffer[k++] = HIGH; // terminate938len = k;939// swap list and buffer940int[] temp = list;941list = buffer;942buffer = temp;943return this;944}945946// polarity = 0 is normal: x intersect y947// polarity = 2: x intersect ~y == set-minus948// polarity = 1: ~x intersect y949// polarity = 3: ~x intersect ~y950951private UnicodeSet retain(int[] other, int otherLen, int polarity) {952ensureBufferCapacity(len + otherLen);953int i = 0, j = 0, k = 0;954int a = list[i++];955int b = other[j++];956// change from xor is that we have to check overlapping pairs957// polarity bit 1 means a is second, bit 2 means b is.958main:959while (true) {960switch (polarity) {961case 0: // both first; drop the smaller962if (a < b) { // drop a963a = list[i++]; polarity ^= 1;964} else if (b < a) { // drop b965b = other[j++]; polarity ^= 2;966} else { // a == b, take one, drop other967if (a == HIGH) break main;968buffer[k++] = a; a = list[i++]; polarity ^= 1;969b = other[j++]; polarity ^= 2;970}971break;972case 3: // both second; take lower if unequal973if (a < b) { // take a974buffer[k++] = a; a = list[i++]; polarity ^= 1;975} else if (b < a) { // take b976buffer[k++] = b; b = other[j++]; polarity ^= 2;977} else { // a == b, take one, drop other978if (a == HIGH) break main;979buffer[k++] = a; a = list[i++]; polarity ^= 1;980b = other[j++]; polarity ^= 2;981}982break;983case 1: // a second, b first;984if (a < b) { // NO OVERLAP, drop a985a = list[i++]; polarity ^= 1;986} else if (b < a) { // OVERLAP, take b987buffer[k++] = b; b = other[j++]; polarity ^= 2;988} else { // a == b, drop both!989if (a == HIGH) break main;990a = list[i++]; polarity ^= 1;991b = other[j++]; polarity ^= 2;992}993break;994case 2: // a first, b second; if a < b, overlap995if (b < a) { // no overlap, drop b996b = other[j++]; polarity ^= 2;997} else if (a < b) { // OVERLAP, take a998buffer[k++] = a; a = list[i++]; polarity ^= 1;999} else { // a == b, drop both!1000if (a == HIGH) break main;1001a = list[i++]; polarity ^= 1;1002b = other[j++]; polarity ^= 2;1003}1004break;1005}1006}1007buffer[k++] = HIGH; // terminate1008len = k;1009// swap list and buffer1010int[] temp = list;1011list = buffer;1012buffer = temp;1013return this;1014}10151016private static final int max(int a, int b) {1017return (a > b) ? a : b;1018}10191020//----------------------------------------------------------------1021// Generic filter-based scanning code1022//----------------------------------------------------------------10231024private static interface Filter {1025boolean contains(int codePoint);1026}10271028private static final VersionInfo NO_VERSION = VersionInfo.getInstance(0, 0, 0, 0);10291030private static class VersionFilter implements Filter {1031VersionInfo version;1032VersionFilter(VersionInfo version) { this.version = version; }1033public boolean contains(int ch) {1034VersionInfo v = UCharacter.getAge(ch);1035// Reference comparison ok; VersionInfo caches and reuses1036// unique objects.1037return v != NO_VERSION &&1038v.compareTo(version) <= 0;1039}1040}10411042private static synchronized UnicodeSet getInclusions(int src) {1043if (src != UCharacterProperty.SRC_PROPSVEC) {1044throw new IllegalStateException("UnicodeSet.getInclusions(unknown src "+src+")");1045}10461047if (INCLUSION == null) {1048UnicodeSet incl = new UnicodeSet();1049UCharacterProperty.INSTANCE.upropsvec_addPropertyStarts(incl);1050INCLUSION = incl;1051}1052return INCLUSION;1053}10541055/**1056* Generic filter-based scanning code for UCD property UnicodeSets.1057*/1058private UnicodeSet applyFilter(Filter filter, int src) {1059// Logically, walk through all Unicode characters, noting the start1060// and end of each range for which filter.contain(c) is1061// true. Add each range to a set.1062//1063// To improve performance, use an inclusions set which1064// encodes information about character ranges that are known1065// to have identical properties.1066// getInclusions(src) contains exactly the first characters of1067// same-value ranges for the given properties "source".10681069clear();10701071int startHasProperty = -1;1072UnicodeSet inclusions = getInclusions(src);1073int limitRange = inclusions.getRangeCount();10741075for (int j=0; j<limitRange; ++j) {1076// get current range1077int start = inclusions.getRangeStart(j);1078int end = inclusions.getRangeEnd(j);10791080// for all the code points in the range, process1081for (int ch = start; ch <= end; ++ch) {1082// only add to the unicodeset on inflection points --1083// where the hasProperty value changes to false1084if (filter.contains(ch)) {1085if (startHasProperty < 0) {1086startHasProperty = ch;1087}1088} else if (startHasProperty >= 0) {1089add_unchecked(startHasProperty, ch-1);1090startHasProperty = -1;1091}1092}1093}1094if (startHasProperty >= 0) {1095add_unchecked(startHasProperty, 0x10FFFF);1096}10971098return this;1099}11001101/**1102* Is this frozen, according to the Freezable interface?1103*1104* @return value1105* @stable ICU 3.81106*/1107public boolean isFrozen() {1108return (bmpSet != null || stringSpan != null);1109}11101111/**1112* Freeze this class, according to the Freezable interface.1113*1114* @return this1115* @stable ICU 4.41116*/1117public UnicodeSet freeze() {1118if (!isFrozen()) {1119// Do most of what compact() does before freezing because1120// compact() will not work when the set is frozen.1121// Small modification: Don't shrink if the savings would be tiny (<=GROW_EXTRA).11221123// Delete buffer first to defragment memory less.1124buffer = null;1125if (list.length > (len + GROW_EXTRA)) {1126// Make the capacity equal to len or 1.1127// We don't want to realloc of 0 size.1128int capacity = (len == 0) ? 1 : len;1129int[] oldList = list;1130list = new int[capacity];1131for (int i = capacity; i-- > 0;) {1132list[i] = oldList[i];1133}1134}11351136// Optimize contains() and span() and similar functions.1137if (!strings.isEmpty()) {1138stringSpan = new UnicodeSetStringSpan(this, new ArrayList<String>(strings), UnicodeSetStringSpan.ALL);1139}1140if (stringSpan == null || !stringSpan.needsStringSpanUTF16()) {1141// Optimize for code point spans.1142// There are no strings, or1143// all strings are irrelevant for span() etc. because1144// all of each string's code points are contained in this set.1145// However, fully contained strings are relevant for spanAndCount(),1146// so we create both objects.1147bmpSet = new BMPSet(list, len);1148}1149}1150return this;1151}11521153/**1154* Span a string using this UnicodeSet.1155* <p>To replace, count elements, or delete spans, see {@link com.ibm.icu.text.UnicodeSetSpanner UnicodeSetSpanner}.1156* @param s The string to be spanned1157* @param spanCondition The span condition1158* @return the length of the span1159* @stable ICU 4.41160*/1161public int span(CharSequence s, SpanCondition spanCondition) {1162return span(s, 0, spanCondition);1163}11641165/**1166* Span a string using this UnicodeSet.1167* If the start index is less than 0, span will start from 0.1168* If the start index is greater than the string length, span returns the string length.1169* <p>To replace, count elements, or delete spans, see {@link com.ibm.icu.text.UnicodeSetSpanner UnicodeSetSpanner}.1170* @param s The string to be spanned1171* @param start The start index that the span begins1172* @param spanCondition The span condition1173* @return the string index which ends the span (i.e. exclusive)1174* @stable ICU 4.41175*/1176public int span(CharSequence s, int start, SpanCondition spanCondition) {1177int end = s.length();1178if (start < 0) {1179start = 0;1180} else if (start >= end) {1181return end;1182}1183if (bmpSet != null) {1184// Frozen set without strings, or no string is relevant for span().1185return bmpSet.span(s, start, spanCondition, null);1186}1187if (stringSpan != null) {1188return stringSpan.span(s, start, spanCondition);1189} else if (!strings.isEmpty()) {1190int which = spanCondition == SpanCondition.NOT_CONTAINED ? UnicodeSetStringSpan.FWD_UTF16_NOT_CONTAINED1191: UnicodeSetStringSpan.FWD_UTF16_CONTAINED;1192UnicodeSetStringSpan strSpan = new UnicodeSetStringSpan(this, new ArrayList<String>(strings), which);1193if (strSpan.needsStringSpanUTF16()) {1194return strSpan.span(s, start, spanCondition);1195}1196}11971198return spanCodePointsAndCount(s, start, spanCondition, null);1199}12001201/**1202* Same as span() but also counts the smallest number of set elements on any path across the span.1203* <p>To replace, count elements, or delete spans, see {@link com.ibm.icu.text.UnicodeSetSpanner UnicodeSetSpanner}.1204* @param outCount An output-only object (must not be null) for returning the count.1205* @return the limit (exclusive end) of the span1206*/1207public int spanAndCount(CharSequence s, int start, SpanCondition spanCondition, OutputInt outCount) {1208if (outCount == null) {1209throw new IllegalArgumentException("outCount must not be null");1210}1211int end = s.length();1212if (start < 0) {1213start = 0;1214} else if (start >= end) {1215return end;1216}1217if (stringSpan != null) {1218// We might also have bmpSet != null,1219// but fully-contained strings are relevant for counting elements.1220return stringSpan.spanAndCount(s, start, spanCondition, outCount);1221} else if (bmpSet != null) {1222return bmpSet.span(s, start, spanCondition, outCount);1223} else if (!strings.isEmpty()) {1224int which = spanCondition == SpanCondition.NOT_CONTAINED ? UnicodeSetStringSpan.FWD_UTF16_NOT_CONTAINED1225: UnicodeSetStringSpan.FWD_UTF16_CONTAINED;1226which |= UnicodeSetStringSpan.WITH_COUNT;1227UnicodeSetStringSpan strSpan = new UnicodeSetStringSpan(this, new ArrayList<String>(strings), which);1228return strSpan.spanAndCount(s, start, spanCondition, outCount);1229}12301231return spanCodePointsAndCount(s, start, spanCondition, outCount);1232}12331234private int spanCodePointsAndCount(CharSequence s, int start,1235SpanCondition spanCondition, OutputInt outCount) {1236// Pin to 0/1 values.1237boolean spanContained = (spanCondition != SpanCondition.NOT_CONTAINED);12381239int c;1240int next = start;1241int length = s.length();1242int count = 0;1243do {1244c = Character.codePointAt(s, next);1245if (spanContained != contains(c)) {1246break;1247}1248++count;1249next += Character.charCount(c);1250} while (next < length);1251if (outCount != null) { outCount.value = count; }1252return next;1253}12541255/**1256* Span a string backwards (from the fromIndex) using this UnicodeSet.1257* If the fromIndex is less than 0, spanBack will return 0.1258* If fromIndex is greater than the string length, spanBack will start from the string length.1259* <p>To replace, count elements, or delete spans, see {@link com.ibm.icu.text.UnicodeSetSpanner UnicodeSetSpanner}.1260* @param s The string to be spanned1261* @param fromIndex The index of the char (exclusive) that the string should be spanned backwards1262* @param spanCondition The span condition1263* @return The string index which starts the span (i.e. inclusive).1264* @stable ICU 4.41265*/1266public int spanBack(CharSequence s, int fromIndex, SpanCondition spanCondition) {1267if (fromIndex <= 0) {1268return 0;1269}1270if (fromIndex > s.length()) {1271fromIndex = s.length();1272}1273if (bmpSet != null) {1274// Frozen set without strings, or no string is relevant for spanBack().1275return bmpSet.spanBack(s, fromIndex, spanCondition);1276}1277if (stringSpan != null) {1278return stringSpan.spanBack(s, fromIndex, spanCondition);1279} else if (!strings.isEmpty()) {1280int which = (spanCondition == SpanCondition.NOT_CONTAINED)1281? UnicodeSetStringSpan.BACK_UTF16_NOT_CONTAINED1282: UnicodeSetStringSpan.BACK_UTF16_CONTAINED;1283UnicodeSetStringSpan strSpan = new UnicodeSetStringSpan(this, new ArrayList<String>(strings), which);1284if (strSpan.needsStringSpanUTF16()) {1285return strSpan.spanBack(s, fromIndex, spanCondition);1286}1287}12881289// Pin to 0/1 values.1290boolean spanContained = (spanCondition != SpanCondition.NOT_CONTAINED);12911292int c;1293int prev = fromIndex;1294do {1295c = Character.codePointBefore(s, prev);1296if (spanContained != contains(c)) {1297break;1298}1299prev -= Character.charCount(c);1300} while (prev > 0);1301return prev;1302}13031304/**1305* Clone a thawed version of this class, according to the Freezable interface.1306* @return the clone, not frozen1307* @stable ICU 4.41308*/1309public UnicodeSet cloneAsThawed() {1310UnicodeSet result = new UnicodeSet(this);1311assert !result.isFrozen();1312return result;1313}13141315// internal function1316private void checkFrozen() {1317if (isFrozen()) {1318throw new UnsupportedOperationException("Attempt to modify frozen object");1319}1320}13211322/**1323* Argument values for whether span() and similar functions continue while the current character is contained vs.1324* not contained in the set.1325* <p>1326* The functionality is straightforward for sets with only single code points, without strings (which is the common1327* case):1328* <ul>1329* <li>CONTAINED and SIMPLE work the same.1330* <li>CONTAINED and SIMPLE are inverses of NOT_CONTAINED.1331* <li>span() and spanBack() partition any string the1332* same way when alternating between span(NOT_CONTAINED) and span(either "contained" condition).1333* <li>Using a1334* complemented (inverted) set and the opposite span conditions yields the same results.1335* </ul>1336* When a set contains multi-code point strings, then these statements may not be true, depending on the strings in1337* the set (for example, whether they overlap with each other) and the string that is processed. For a set with1338* strings:1339* <ul>1340* <li>The complement of the set contains the opposite set of code points, but the same set of strings.1341* Therefore, complementing both the set and the span conditions may yield different results.1342* <li>When starting spans1343* at different positions in a string (span(s, ...) vs. span(s+1, ...)) the ends of the spans may be different1344* because a set string may start before the later position.1345* <li>span(SIMPLE) may be shorter than1346* span(CONTAINED) because it will not recursively try all possible paths. For example, with a set which1347* contains the three strings "xy", "xya" and "ax", span("xyax", CONTAINED) will return 4 but span("xyax",1348* SIMPLE) will return 3. span(SIMPLE) will never be longer than span(CONTAINED).1349* <li>With either "contained" condition, span() and spanBack() may partition a string in different ways. For example,1350* with a set which contains the two strings "ab" and "ba", and when processing the string "aba", span() will yield1351* contained/not-contained boundaries of { 0, 2, 3 } while spanBack() will yield boundaries of { 0, 1, 3 }.1352* </ul>1353* Note: If it is important to get the same boundaries whether iterating forward or backward through a string, then1354* either only span() should be used and the boundaries cached for backward operation, or an ICU BreakIterator could1355* be used.1356* <p>1357* Note: Unpaired surrogates are treated like surrogate code points. Similarly, set strings match only on code point1358* boundaries, never in the middle of a surrogate pair.1359*1360* @stable ICU 4.41361*/1362public enum SpanCondition {1363/**1364* Continues a span() while there is no set element at the current position.1365* Increments by one code point at a time.1366* Stops before the first set element (character or string).1367* (For code points only, this is like while contains(current)==false).1368* <p>1369* When span() returns, the substring between where it started and the position it returned consists only of1370* characters that are not in the set, and none of its strings overlap with the span.1371*1372* @stable ICU 4.41373*/1374NOT_CONTAINED,13751376/**1377* Spans the longest substring that is a concatenation of set elements (characters or strings).1378* (For characters only, this is like while contains(current)==true).1379* <p>1380* When span() returns, the substring between where it started and the position it returned consists only of set1381* elements (characters or strings) that are in the set.1382* <p>1383* If a set contains strings, then the span will be the longest substring for which there1384* exists at least one non-overlapping concatenation of set elements (characters or strings).1385* This is equivalent to a POSIX regular expression for <code>(OR of each set element)*</code>.1386* (Java/ICU/Perl regex stops at the first match of an OR.)1387*1388* @stable ICU 4.41389*/1390CONTAINED,13911392/**1393* Continues a span() while there is a set element at the current position.1394* Increments by the longest matching element at each position.1395* (For characters only, this is like while contains(current)==true).1396* <p>1397* When span() returns, the substring between where it started and the position it returned consists only of set1398* elements (characters or strings) that are in the set.1399* <p>1400* If a set only contains single characters, then this is the same as CONTAINED.1401* <p>1402* If a set contains strings, then the span will be the longest substring with a match at each position with the1403* longest single set element (character or string).1404* <p>1405* Use this span condition together with other longest-match algorithms, such as ICU converters1406* (ucnv_getUnicodeSet()).1407*1408* @stable ICU 4.41409*/1410SIMPLE,1411}14121413}141414151416