3 *******************************************************************************
\r
4 * Copyright (C) 1996-2009, International Business Machines Corporation and *
\r
5 * others. All Rights Reserved. *
\r
6 *******************************************************************************
\r
8 package com.ibm.icu.text;
\r
11 import com.ibm.icu.lang.*;
\r
13 import java.io.IOException;
\r
15 import com.ibm.icu.impl.NormalizerImpl;
\r
16 import com.ibm.icu.impl.Utility;
\r
17 import com.ibm.icu.impl.UCharacterProperty;
\r
18 import com.ibm.icu.impl.UBiDiProps;
\r
19 import com.ibm.icu.impl.UCaseProps;
\r
20 import com.ibm.icu.impl.UPropertyAliases;
\r
21 import com.ibm.icu.impl.SortedSetRelation;
\r
22 import com.ibm.icu.impl.RuleCharacterIterator;
\r
24 import com.ibm.icu.util.Freezable;
\r
25 import com.ibm.icu.util.ULocale;
\r
26 import com.ibm.icu.util.VersionInfo;
\r
28 import com.ibm.icu.text.BreakIterator;
\r
30 import java.util.MissingResourceException;
\r
31 import java.util.TreeSet;
\r
32 import java.util.Iterator;
\r
33 import java.util.Collection;
\r
36 * A mutable set of Unicode characters and multicharacter strings. Objects of this class
\r
37 * represent <em>character classes</em> used in regular expressions.
\r
38 * A character specifies a subset of Unicode code points. Legal
\r
39 * code points are U+0000 to U+10FFFF, inclusive.
\r
41 * <p>The UnicodeSet class is not designed to be subclassed.
\r
43 * <p><code>UnicodeSet</code> supports two APIs. The first is the
\r
44 * <em>operand</em> API that allows the caller to modify the value of
\r
45 * a <code>UnicodeSet</code> object. It conforms to Java 2's
\r
46 * <code>java.util.Set</code> interface, although
\r
47 * <code>UnicodeSet</code> does not actually implement that
\r
48 * interface. All methods of <code>Set</code> are supported, with the
\r
49 * modification that they take a character range or single character
\r
50 * instead of an <code>Object</code>, and they take a
\r
51 * <code>UnicodeSet</code> instead of a <code>Collection</code>. The
\r
52 * operand API may be thought of in terms of boolean logic: a boolean
\r
53 * OR is implemented by <code>add</code>, a boolean AND is implemented
\r
54 * by <code>retain</code>, a boolean XOR is implemented by
\r
55 * <code>complement</code> taking an argument, and a boolean NOT is
\r
56 * implemented by <code>complement</code> with no argument. In terms
\r
57 * of traditional set theory function names, <code>add</code> is a
\r
58 * union, <code>retain</code> is an intersection, <code>remove</code>
\r
59 * is an asymmetric difference, and <code>complement</code> with no
\r
60 * argument is a set complement with respect to the superset range
\r
61 * <code>MIN_VALUE-MAX_VALUE</code>
\r
63 * <p>The second API is the
\r
64 * <code>applyPattern()</code>/<code>toPattern()</code> API from the
\r
65 * <code>java.text.Format</code>-derived classes. Unlike the
\r
66 * methods that add characters, add categories, and control the logic
\r
67 * of the set, the method <code>applyPattern()</code> sets all
\r
68 * attributes of a <code>UnicodeSet</code> at once, based on a
\r
71 * <p><b>Pattern syntax</b></p>
\r
73 * Patterns are accepted by the constructors and the
\r
74 * <code>applyPattern()</code> methods and returned by the
\r
75 * <code>toPattern()</code> method. These patterns follow a syntax
\r
76 * similar to that employed by version 8 regular expression character
\r
77 * classes. Here are some simple examples:
\r
82 * <td nowrap valign="top" align="left"><code>[]</code></td>
\r
83 * <td valign="top">No characters</td>
\r
84 * </tr><tr align="top">
\r
85 * <td nowrap valign="top" align="left"><code>[a]</code></td>
\r
86 * <td valign="top">The character 'a'</td>
\r
87 * </tr><tr align="top">
\r
88 * <td nowrap valign="top" align="left"><code>[ae]</code></td>
\r
89 * <td valign="top">The characters 'a' and 'e'</td>
\r
92 * <td nowrap valign="top" align="left"><code>[a-e]</code></td>
\r
93 * <td valign="top">The characters 'a' through 'e' inclusive, in Unicode code
\r
97 * <td nowrap valign="top" align="left"><code>[\\u4E01]</code></td>
\r
98 * <td valign="top">The character U+4E01</td>
\r
101 * <td nowrap valign="top" align="left"><code>[a{ab}{ac}]</code></td>
\r
102 * <td valign="top">The character 'a' and the multicharacter strings "ab" and
\r
103 * "ac"</td>
\r
106 * <td nowrap valign="top" align="left"><code>[\p{Lu}]</code></td>
\r
107 * <td valign="top">All characters in the general category Uppercase Letter</td>
\r
112 * Any character may be preceded by a backslash in order to remove any special
\r
113 * meaning. White space characters, as defined by UCharacterProperty.isRuleWhiteSpace(), are
\r
114 * ignored, unless they are escaped.
\r
116 * <p>Property patterns specify a set of characters having a certain
\r
117 * property as defined by the Unicode standard. Both the POSIX-like
\r
118 * "[:Lu:]" and the Perl-like syntax "\p{Lu}" are recognized. For a
\r
119 * complete list of supported property patterns, see the User's Guide
\r
120 * for UnicodeSet at
\r
121 * <a href="http://www.icu-project.org/userguide/unicodeSet.html">
\r
122 * http://www.icu-project.org/userguide/unicodeSet.html</a>.
\r
123 * Actual determination of property data is defined by the underlying
\r
124 * Unicode database as implemented by UCharacter.
\r
126 * <p>Patterns specify individual characters, ranges of characters, and
\r
127 * Unicode property sets. When elements are concatenated, they
\r
128 * specify their union. To complement a set, place a '^' immediately
\r
129 * after the opening '['. Property patterns are inverted by modifying
\r
130 * their delimiters; "[:^foo]" and "\P{foo}". In any other location,
\r
131 * '^' has no special meaning.
\r
133 * <p>Ranges are indicated by placing two a '-' between two
\r
134 * characters, as in "a-z". This specifies the range of all
\r
135 * characters from the left to the right, in Unicode order. If the
\r
136 * left character is greater than or equal to the
\r
137 * right character it is a syntax error. If a '-' occurs as the first
\r
138 * character after the opening '[' or '[^', or if it occurs as the
\r
139 * last character before the closing ']', then it is taken as a
\r
140 * literal. Thus "[a\\-b]", "[-ab]", and "[ab-]" all indicate the same
\r
141 * set of three characters, 'a', 'b', and '-'.
\r
143 * <p>Sets may be intersected using the '&' operator or the asymmetric
\r
144 * set difference may be taken using the '-' operator, for example,
\r
145 * "[[:L:]&[\\u0000-\\u0FFF]]" indicates the set of all Unicode letters
\r
146 * with values less than 4096. Operators ('&' and '|') have equal
\r
147 * precedence and bind left-to-right. Thus
\r
148 * "[[:L:]-[a-z]-[\\u0100-\\u01FF]]" is equivalent to
\r
149 * "[[[:L:]-[a-z]]-[\\u0100-\\u01FF]]". This only really matters for
\r
150 * difference; intersection is commutative.
\r
153 * <tr valign=top><td nowrap><code>[a]</code><td>The set containing 'a'
\r
154 * <tr valign=top><td nowrap><code>[a-z]</code><td>The set containing 'a'
\r
155 * through 'z' and all letters in between, in Unicode order
\r
156 * <tr valign=top><td nowrap><code>[^a-z]</code><td>The set containing
\r
157 * all characters but 'a' through 'z',
\r
158 * that is, U+0000 through 'a'-1 and 'z'+1 through U+10FFFF
\r
159 * <tr valign=top><td nowrap><code>[[<em>pat1</em>][<em>pat2</em>]]</code>
\r
160 * <td>The union of sets specified by <em>pat1</em> and <em>pat2</em>
\r
161 * <tr valign=top><td nowrap><code>[[<em>pat1</em>]&[<em>pat2</em>]]</code>
\r
162 * <td>The intersection of sets specified by <em>pat1</em> and <em>pat2</em>
\r
163 * <tr valign=top><td nowrap><code>[[<em>pat1</em>]-[<em>pat2</em>]]</code>
\r
164 * <td>The asymmetric difference of sets specified by <em>pat1</em> and
\r
166 * <tr valign=top><td nowrap><code>[:Lu:] or \p{Lu}</code>
\r
167 * <td>The set of characters having the specified
\r
168 * Unicode property; in
\r
169 * this case, Unicode uppercase letters
\r
170 * <tr valign=top><td nowrap><code>[:^Lu:] or \P{Lu}</code>
\r
171 * <td>The set of characters <em>not</em> having the given
\r
175 * <p><b>Warning</b>: you cannot add an empty string ("") to a UnicodeSet.</p>
\r
177 * <p><b>Formal syntax</b></p>
\r
182 * <td nowrap valign="top" align="right"><code>pattern := </code></td>
\r
183 * <td valign="top"><code>('[' '^'? item* ']') |
\r
184 * property</code></td>
\r
187 * <td nowrap valign="top" align="right"><code>item := </code></td>
\r
188 * <td valign="top"><code>char | (char '-' char) | pattern-expr<br>
\r
192 * <td nowrap valign="top" align="right"><code>pattern-expr := </code></td>
\r
193 * <td valign="top"><code>pattern | pattern-expr pattern |
\r
194 * pattern-expr op pattern<br>
\r
198 * <td nowrap valign="top" align="right"><code>op := </code></td>
\r
199 * <td valign="top"><code>'&' | '-'<br>
\r
203 * <td nowrap valign="top" align="right"><code>special := </code></td>
\r
204 * <td valign="top"><code>'[' | ']' | '-'<br>
\r
208 * <td nowrap valign="top" align="right"><code>char := </code></td>
\r
209 * <td valign="top"><em>any character that is not</em><code> special<br>
\r
210 * | ('\\' </code><em>any character</em><code>)<br>
\r
211 * | ('\u' hex hex hex hex)<br>
\r
215 * <td nowrap valign="top" align="right"><code>hex := </code></td>
\r
216 * <td valign="top"><em>any character for which
\r
217 * </em><code>Character.digit(c, 16)</code><em>
\r
218 * returns a non-negative result</em></td>
\r
221 * <td nowrap valign="top" align="right"><code>property := </code></td>
\r
222 * <td valign="top"><em>a Unicode property set pattern</td>
\r
226 * <table border="1">
\r
228 * <td>Legend: <table>
\r
230 * <td nowrap valign="top"><code>a := b</code></td>
\r
231 * <td width="20" valign="top"> </td>
\r
232 * <td valign="top"><code>a</code> may be replaced by <code>b</code> </td>
\r
235 * <td nowrap valign="top"><code>a?</code></td>
\r
236 * <td valign="top"></td>
\r
237 * <td valign="top">zero or one instance of <code>a</code><br>
\r
241 * <td nowrap valign="top"><code>a*</code></td>
\r
242 * <td valign="top"></td>
\r
243 * <td valign="top">one or more instances of <code>a</code><br>
\r
247 * <td nowrap valign="top"><code>a | b</code></td>
\r
248 * <td valign="top"></td>
\r
249 * <td valign="top">either <code>a</code> or <code>b</code><br>
\r
253 * <td nowrap valign="top"><code>'a'</code></td>
\r
254 * <td valign="top"></td>
\r
255 * <td valign="top">the literal string between the quotes </td>
\r
262 * <p>To iterate over contents of UnicodeSet, use UnicodeSetIterator class.
\r
266 * @see UnicodeSetIterator
\r
268 public class UnicodeSet extends UnicodeFilter implements Freezable {
\r
270 private static final int LOW = 0x000000; // LOW <= all valid values. ZERO for codepoints
\r
271 private static final int HIGH = 0x110000; // HIGH > all valid values. 10000 for code units.
\r
272 // 110000 for codepoints
\r
275 * Minimum value that can be stored in a UnicodeSet.
\r
278 public static final int MIN_VALUE = LOW;
\r
281 * Maximum value that can be stored in a UnicodeSet.
\r
284 public static final int MAX_VALUE = HIGH - 1;
\r
286 private int len; // length used; list may be longer to minimize reallocs
\r
287 private int[] list; // MUST be terminated with HIGH
\r
288 private int[] rangeList; // internal buffer
\r
289 private int[] buffer; // internal buffer
\r
291 // NOTE: normally the field should be of type SortedSet; but that is missing a public clone!!
\r
292 // is not private so that UnicodeSetIterator can get access
\r
293 TreeSet strings = new TreeSet();
\r
296 * The pattern representation of this set. This may not be the
\r
297 * most economical pattern. It is the pattern supplied to
\r
298 * applyPattern(), with variables substituted and whitespace
\r
299 * removed. For sets constructed without applyPattern(), or
\r
300 * modified using the non-pattern API, this string will be null,
\r
301 * indicating that toPattern() must generate a pattern
\r
302 * representation from the inversion list.
\r
304 private String pat = null;
\r
306 private static final int START_EXTRA = 16; // initial storage. Must be >= 0
\r
307 private static final int GROW_EXTRA = START_EXTRA; // extra amount for growth. Must be >= 0
\r
309 // Special property set IDs
\r
310 private static final String ANY_ID = "ANY"; // [\u0000-\U0010FFFF]
\r
311 private static final String ASCII_ID = "ASCII"; // [\u0000-\u007F]
\r
312 private static final String ASSIGNED = "Assigned"; // [:^Cn:]
\r
315 * A set of all characters _except_ the second through last characters of
\r
316 * certain ranges. These ranges are ranges of characters whose
\r
317 * properties are all exactly alike, e.g. CJK Ideographs from
\r
318 * U+4E00 to U+9FA5.
\r
320 private static UnicodeSet INCLUSIONS[] = null;
\r
322 //----------------------------------------------------------------
\r
324 //----------------------------------------------------------------
\r
327 * Constructs an empty set.
\r
330 public UnicodeSet() {
\r
331 list = new int[1 + START_EXTRA];
\r
332 list[len++] = HIGH;
\r
336 * Constructs a copy of an existing set.
\r
339 public UnicodeSet(UnicodeSet other) {
\r
344 * Constructs a set containing the given range. If <code>end >
\r
345 * start</code> then an empty set is created.
\r
347 * @param start first character, inclusive, of range
\r
348 * @param end last character, inclusive, of range
\r
351 public UnicodeSet(int start, int end) {
\r
353 complement(start, end);
\r
357 * Constructs a set from the given pattern. See the class description
\r
358 * for the syntax of the pattern language. Whitespace is ignored.
\r
359 * @param pattern a string specifying what characters are in the set
\r
360 * @exception java.lang.IllegalArgumentException if the pattern contains
\r
364 public UnicodeSet(String pattern) {
\r
366 applyPattern(pattern, null, null, IGNORE_SPACE);
\r
370 * Constructs a set from the given pattern. See the class description
\r
371 * for the syntax of the pattern language.
\r
372 * @param pattern a string specifying what characters are in the set
\r
373 * @param ignoreWhitespace if true, ignore characters for which
\r
374 * UCharacterProperty.isRuleWhiteSpace() returns true
\r
375 * @exception java.lang.IllegalArgumentException if the pattern contains
\r
379 public UnicodeSet(String pattern, boolean ignoreWhitespace) {
\r
381 applyPattern(pattern, null, null, ignoreWhitespace ? IGNORE_SPACE : 0);
\r
385 * Constructs a set from the given pattern. See the class description
\r
386 * for the syntax of the pattern language.
\r
387 * @param pattern a string specifying what characters are in the set
\r
388 * @param options a bitmask indicating which options to apply.
\r
389 * Valid options are IGNORE_SPACE and CASE.
\r
390 * @exception java.lang.IllegalArgumentException if the pattern contains
\r
394 public UnicodeSet(String pattern, int options) {
\r
396 applyPattern(pattern, null, null, options);
\r
400 * Constructs a set from the given pattern. See the class description
\r
401 * for the syntax of the pattern language.
\r
402 * @param pattern a string specifying what characters are in the set
\r
403 * @param pos on input, the position in pattern at which to start parsing.
\r
404 * On output, the position after the last character parsed.
\r
405 * @param symbols a symbol table mapping variables to char[] arrays
\r
406 * and chars to UnicodeSets
\r
407 * @exception java.lang.IllegalArgumentException if the pattern
\r
408 * contains a syntax error.
\r
411 public UnicodeSet(String pattern, ParsePosition pos, SymbolTable symbols) {
\r
413 applyPattern(pattern, pos, symbols, IGNORE_SPACE);
\r
417 * Constructs a set from the given pattern. See the class description
\r
418 * for the syntax of the pattern language.
\r
419 * @param pattern a string specifying what characters are in the set
\r
420 * @param pos on input, the position in pattern at which to start parsing.
\r
421 * On output, the position after the last character parsed.
\r
422 * @param symbols a symbol table mapping variables to char[] arrays
\r
423 * and chars to UnicodeSets
\r
424 * @param options a bitmask indicating which options to apply.
\r
425 * Valid options are IGNORE_SPACE and CASE.
\r
426 * @exception java.lang.IllegalArgumentException if the pattern
\r
427 * contains a syntax error.
\r
430 public UnicodeSet(String pattern, ParsePosition pos, SymbolTable symbols, int options) {
\r
432 applyPattern(pattern, pos, symbols, options);
\r
437 * Return a new set that is equivalent to this one.
\r
440 public Object clone() {
\r
441 UnicodeSet result = new UnicodeSet(this);
\r
442 result.frozen = this.frozen;
\r
447 * Make this object represent the range <code>start - end</code>.
\r
448 * If <code>end > start</code> then this object is set to an
\r
451 * @param start first character in the set, inclusive
\r
452 * @param end last character in the set, inclusive
\r
455 public UnicodeSet set(int start, int end) {
\r
458 complement(start, end);
\r
463 * Make this object represent the same set as <code>other</code>.
\r
464 * @param other a <code>UnicodeSet</code> whose value will be
\r
465 * copied to this object
\r
468 public UnicodeSet set(UnicodeSet other) {
\r
470 list = (int[]) other.list.clone();
\r
473 strings = (TreeSet)other.strings.clone();
\r
478 * Modifies this set to represent the set specified by the given pattern.
\r
479 * See the class description for the syntax of the pattern language.
\r
480 * Whitespace is ignored.
\r
481 * @param pattern a string specifying what characters are in the set
\r
482 * @exception java.lang.IllegalArgumentException if the pattern
\r
483 * contains a syntax error.
\r
486 public final UnicodeSet applyPattern(String pattern) {
\r
488 return applyPattern(pattern, null, null, IGNORE_SPACE);
\r
492 * Modifies this set to represent the set specified by the given pattern,
\r
493 * optionally ignoring whitespace.
\r
494 * See the class description for the syntax of the pattern language.
\r
495 * @param pattern a string specifying what characters are in the set
\r
496 * @param ignoreWhitespace if true then characters for which
\r
497 * UCharacterProperty.isRuleWhiteSpace() returns true are ignored
\r
498 * @exception java.lang.IllegalArgumentException if the pattern
\r
499 * contains a syntax error.
\r
502 public UnicodeSet applyPattern(String pattern, boolean ignoreWhitespace) {
\r
504 return applyPattern(pattern, null, null, ignoreWhitespace ? IGNORE_SPACE : 0);
\r
508 * Modifies this set to represent the set specified by the given pattern,
\r
509 * optionally ignoring whitespace.
\r
510 * See the class description for the syntax of the pattern language.
\r
511 * @param pattern a string specifying what characters are in the set
\r
512 * @param options a bitmask indicating which options to apply.
\r
513 * Valid options are IGNORE_SPACE and CASE.
\r
514 * @exception java.lang.IllegalArgumentException if the pattern
\r
515 * contains a syntax error.
\r
518 public UnicodeSet applyPattern(String pattern, int options) {
\r
520 return applyPattern(pattern, null, null, options);
\r
524 * Return true if the given position, in the given pattern, appears
\r
525 * to be the start of a UnicodeSet pattern.
\r
528 public static boolean resemblesPattern(String pattern, int pos) {
\r
529 return ((pos+1) < pattern.length() &&
\r
530 pattern.charAt(pos) == '[') ||
\r
531 resemblesPropertyPattern(pattern, pos);
\r
535 * Append the <code>toPattern()</code> representation of a
\r
536 * string to the given <code>StringBuffer</code>.
\r
538 private static void _appendToPat(StringBuffer buf, String s, boolean escapeUnprintable) {
\r
539 for (int i = 0; i < s.length(); i += UTF16.getCharCount(i)) {
\r
540 _appendToPat(buf, UTF16.charAt(s, i), escapeUnprintable);
\r
545 * Append the <code>toPattern()</code> representation of a
\r
546 * character to the given <code>StringBuffer</code>.
\r
548 private static void _appendToPat(StringBuffer buf, int c, boolean escapeUnprintable) {
\r
549 if (escapeUnprintable && Utility.isUnprintable(c)) {
\r
550 // Use hex escape notation (<backslash>uxxxx or <backslash>Uxxxxxxxx) for anything
\r
552 if (Utility.escapeUnprintable(buf, c)) {
\r
556 // Okay to let ':' pass through
\r
558 case '[': // SET_OPEN:
\r
559 case ']': // SET_CLOSE:
\r
560 case '-': // HYPHEN:
\r
561 case '^': // COMPLEMENT:
\r
562 case '&': // INTERSECTION:
\r
563 case '\\': //BACKSLASH:
\r
571 // Escape whitespace
\r
572 if (UCharacterProperty.isRuleWhiteSpace(c)) {
\r
577 UTF16.append(buf, c);
\r
581 * Returns a string representation of this set. If the result of
\r
582 * calling this function is passed to a UnicodeSet constructor, it
\r
583 * will produce another set that is equal to this one.
\r
586 public String toPattern(boolean escapeUnprintable) {
\r
587 StringBuffer result = new StringBuffer();
\r
588 return _toPattern(result, escapeUnprintable).toString();
\r
592 * Append a string representation of this set to result. This will be
\r
593 * a cleaned version of the string passed to applyPattern(), if there
\r
594 * is one. Otherwise it will be generated.
\r
596 private StringBuffer _toPattern(StringBuffer result,
\r
597 boolean escapeUnprintable) {
\r
600 int backslashCount = 0;
\r
601 for (i=0; i<pat.length(); ) {
\r
602 int c = UTF16.charAt(pat, i);
\r
603 i += UTF16.getCharCount(c);
\r
604 if (escapeUnprintable && Utility.isUnprintable(c)) {
\r
605 // If the unprintable character is preceded by an odd
\r
606 // number of backslashes, then it has been escaped.
\r
607 // Before unescaping it, we delete the final
\r
609 if ((backslashCount % 2) == 1) {
\r
610 result.setLength(result.length() - 1);
\r
612 Utility.escapeUnprintable(result, c);
\r
613 backslashCount = 0;
\r
615 UTF16.append(result, c);
\r
619 backslashCount = 0;
\r
626 return _generatePattern(result, escapeUnprintable, true);
\r
630 * Generate and append a string representation of this set to result.
\r
631 * This does not use this.pat, the cleaned up copy of the string
\r
632 * passed to applyPattern().
\r
633 * @param result the buffer into which to generate the pattern
\r
634 * @param escapeUnprintable escape unprintable characters if true
\r
637 public StringBuffer _generatePattern(StringBuffer result, boolean escapeUnprintable) {
\r
638 return _generatePattern(result, escapeUnprintable, true);
\r
642 * Generate and append a string representation of this set to result.
\r
643 * This does not use this.pat, the cleaned up copy of the string
\r
644 * passed to applyPattern().
\r
645 * @param includeStrings if false, doesn't include the strings.
\r
648 public StringBuffer _generatePattern(StringBuffer result,
\r
649 boolean escapeUnprintable, boolean includeStrings) {
\r
650 result.append('[');
\r
652 // // Check against the predefined categories. We implicitly build
\r
653 // // up ALL category sets the first time toPattern() is called.
\r
654 // for (int cat=0; cat<CATEGORY_COUNT; ++cat) {
\r
655 // if (this.equals(getCategorySet(cat))) {
\r
656 // result.append(':');
\r
657 // result.append(CATEGORY_NAMES.substring(cat*2, cat*2+2));
\r
658 // return result.append(":]");
\r
662 int count = getRangeCount();
\r
664 // If the set contains at least 2 intervals and includes both
\r
665 // MIN_VALUE and MAX_VALUE, then the inverse representation will
\r
666 // be more economical.
\r
668 getRangeStart(0) == MIN_VALUE &&
\r
669 getRangeEnd(count-1) == MAX_VALUE) {
\r
671 // Emit the inverse
\r
672 result.append('^');
\r
674 for (int i = 1; i < count; ++i) {
\r
675 int start = getRangeEnd(i-1)+1;
\r
676 int end = getRangeStart(i)-1;
\r
677 _appendToPat(result, start, escapeUnprintable);
\r
678 if (start != end) {
\r
679 if ((start+1) != end) {
\r
680 result.append('-');
\r
682 _appendToPat(result, end, escapeUnprintable);
\r
687 // Default; emit the ranges as pairs
\r
689 for (int i = 0; i < count; ++i) {
\r
690 int start = getRangeStart(i);
\r
691 int end = getRangeEnd(i);
\r
692 _appendToPat(result, start, escapeUnprintable);
\r
693 if (start != end) {
\r
694 if ((start+1) != end) {
\r
695 result.append('-');
\r
697 _appendToPat(result, end, escapeUnprintable);
\r
702 if (includeStrings && strings.size() > 0) {
\r
703 Iterator it = strings.iterator();
\r
704 while (it.hasNext()) {
\r
705 result.append('{');
\r
706 _appendToPat(result, (String) it.next(), escapeUnprintable);
\r
707 result.append('}');
\r
710 return result.append(']');
\r
714 * Returns the number of elements in this set (its cardinality)
\r
715 * Note than the elements of a set may include both individual
\r
716 * codepoints and strings.
\r
718 * @return the number of elements in this set (its cardinality).
\r
721 public int size() {
\r
723 int count = getRangeCount();
\r
724 for (int i = 0; i < count; ++i) {
\r
725 n += getRangeEnd(i) - getRangeStart(i) + 1;
\r
727 return n + strings.size();
\r
731 * Returns <tt>true</tt> if this set contains no elements.
\r
733 * @return <tt>true</tt> if this set contains no elements.
\r
736 public boolean isEmpty() {
\r
737 return len == 1 && strings.size() == 0;
\r
741 * Implementation of UnicodeMatcher API. Returns <tt>true</tt> if
\r
742 * this set contains any character whose low byte is the given
\r
743 * value. This is used by <tt>RuleBasedTransliterator</tt> for
\r
747 public boolean matchesIndexValue(int v) {
\r
748 /* The index value v, in the range [0,255], is contained in this set if
\r
749 * it is contained in any pair of this set. Pairs either have the high
\r
750 * bytes equal, or unequal. If the high bytes are equal, then we have
\r
751 * aaxx..aayy, where aa is the high byte. Then v is contained if xx <=
\r
752 * v <= yy. If the high bytes are unequal we have aaxx..bbyy, bb>aa.
\r
753 * Then v is contained if xx <= v || v <= yy. (This is identical to the
\r
754 * time zone month containment logic.)
\r
756 for (int i=0; i<getRangeCount(); ++i) {
\r
757 int low = getRangeStart(i);
\r
758 int high = getRangeEnd(i);
\r
759 if ((low & ~0xFF) == (high & ~0xFF)) {
\r
760 if ((low & 0xFF) <= v && v <= (high & 0xFF)) {
\r
763 } else if ((low & 0xFF) <= v || v <= (high & 0xFF)) {
\r
767 if (strings.size() != 0) {
\r
768 Iterator it = strings.iterator();
\r
769 while (it.hasNext()) {
\r
770 String s = (String) it.next();
\r
771 //if (s.length() == 0) {
\r
772 // // Empty strings match everything
\r
775 // assert(s.length() != 0); // We enforce this elsewhere
\r
776 int c = UTF16.charAt(s, 0);
\r
777 if ((c & 0xFF) == v) {
\r
786 * Implementation of UnicodeMatcher.matches(). Always matches the
\r
787 * longest possible multichar string.
\r
790 public int matches(Replaceable text,
\r
793 boolean incremental) {
\r
795 if (offset[0] == limit) {
\r
796 // Strings, if any, have length != 0, so we don't worry
\r
797 // about them here. If we ever allow zero-length strings
\r
798 // we much check for them here.
\r
799 if (contains(UnicodeMatcher.ETHER)) {
\r
800 return incremental ? U_PARTIAL_MATCH : U_MATCH;
\r
805 if (strings.size() != 0) { // try strings first
\r
807 // might separate forward and backward loops later
\r
808 // for now they are combined
\r
810 // TODO Improve efficiency of this, at least in the forward
\r
811 // direction, if not in both. In the forward direction we
\r
812 // can assume the strings are sorted.
\r
814 Iterator it = strings.iterator();
\r
815 boolean forward = offset[0] < limit;
\r
817 // firstChar is the leftmost char to match in the
\r
818 // forward direction or the rightmost char to match in
\r
819 // the reverse direction.
\r
820 char firstChar = text.charAt(offset[0]);
\r
822 // If there are multiple strings that can match we
\r
823 // return the longest match.
\r
824 int highWaterLength = 0;
\r
826 while (it.hasNext()) {
\r
827 String trial = (String) it.next();
\r
829 //if (trial.length() == 0) {
\r
830 // return U_MATCH; // null-string always matches
\r
832 // assert(trial.length() != 0); // We ensure this elsewhere
\r
834 char c = trial.charAt(forward ? 0 : trial.length() - 1);
\r
836 // Strings are sorted, so we can optimize in the
\r
837 // forward direction.
\r
838 if (forward && c > firstChar) break;
\r
839 if (c != firstChar) continue;
\r
841 int length = matchRest(text, offset[0], limit, trial);
\r
844 int maxLen = forward ? limit-offset[0] : offset[0]-limit;
\r
845 if (length == maxLen) {
\r
846 // We have successfully matched but only up to limit.
\r
847 return U_PARTIAL_MATCH;
\r
851 if (length == trial.length()) {
\r
852 // We have successfully matched the whole string.
\r
853 if (length > highWaterLength) {
\r
854 highWaterLength = length;
\r
856 // In the forward direction we know strings
\r
857 // are sorted so we can bail early.
\r
858 if (forward && length < highWaterLength) {
\r
865 // We've checked all strings without a partial match.
\r
866 // If we have full matches, return the longest one.
\r
867 if (highWaterLength != 0) {
\r
868 offset[0] += forward ? highWaterLength : -highWaterLength;
\r
872 return super.matches(text, offset, limit, incremental);
\r
877 * Returns the longest match for s in text at the given position.
\r
878 * If limit > start then match forward from start+1 to limit
\r
879 * matching all characters except s.charAt(0). If limit < start,
\r
880 * go backward starting from start-1 matching all characters
\r
881 * except s.charAt(s.length()-1). This method assumes that the
\r
882 * first character, text.charAt(start), matches s, so it does not
\r
884 * @param text the text to match
\r
885 * @param start the first character to match. In the forward
\r
886 * direction, text.charAt(start) is matched against s.charAt(0).
\r
887 * In the reverse direction, it is matched against
\r
888 * s.charAt(s.length()-1).
\r
889 * @param limit the limit offset for matching, either last+1 in
\r
890 * the forward direction, or last-1 in the reverse direction,
\r
891 * where last is the index of the last character to match.
\r
892 * @return If part of s matches up to the limit, return |limit -
\r
893 * start|. If all of s matches before reaching the limit, return
\r
894 * s.length(). If there is a mismatch between s and text, return
\r
897 private static int matchRest (Replaceable text, int start, int limit, String s) {
\r
899 int slen = s.length();
\r
900 if (start < limit) {
\r
901 maxLen = limit - start;
\r
902 if (maxLen > slen) maxLen = slen;
\r
903 for (int i = 1; i < maxLen; ++i) {
\r
904 if (text.charAt(start + i) != s.charAt(i)) return 0;
\r
907 maxLen = start - limit;
\r
908 if (maxLen > slen) maxLen = slen;
\r
909 --slen; // <=> slen = s.length() - 1;
\r
910 for (int i = 1; i < maxLen; ++i) {
\r
911 if (text.charAt(start - i) != s.charAt(slen - i)) return 0;
\r
917 //#if defined(FOUNDATION10) || defined(J2SE13)
\r
920 * Tests whether the text matches at the offset. If so, returns the end of the longest substring that it matches. If not, returns -1.
\r
922 * @deprecated This API is ICU internal only.
\r
924 public int matchesAt(CharSequence text, int offset) {
\r
927 if (strings.size() != 0) {
\r
928 char firstChar = text.charAt(offset);
\r
929 String trial = null;
\r
930 // find the first string starting with firstChar
\r
931 Iterator it = strings.iterator();
\r
932 while (it.hasNext()) {
\r
933 trial = (String) it.next();
\r
934 char firstStringChar = trial.charAt(0);
\r
935 if (firstStringChar < firstChar) continue;
\r
936 if (firstStringChar > firstChar) break strings;
\r
938 // now keep checking string until we get the longest one
\r
940 int tempLen = matchesAt(text, offset, trial);
\r
941 if (lastLen > tempLen) break strings;
\r
943 if (!it.hasNext()) break;
\r
944 trial = (String) it.next();
\r
948 int cp = UTF16.charAt(text, offset);
\r
949 if (contains(cp)) {
\r
950 lastLen = UTF16.getCharCount(cp);
\r
953 return offset+lastLen;
\r
957 * Does one string contain another, starting at a specific offset?
\r
963 // Note: This method was moved from CollectionUtilities
\r
964 private static int matchesAt(CharSequence text, int offset, CharSequence other) {
\r
965 int len = other.length();
\r
968 for (; i < len; ++i, ++j) {
\r
969 char pc = other.charAt(i);
\r
970 char tc = text.charAt(j);
\r
971 if (pc != tc) return -1;
\r
978 * Implementation of UnicodeMatcher API. Union the set of all
\r
979 * characters that may be matched by this object into the given
\r
981 * @param toUnionTo the set into which to union the source characters
\r
984 public void addMatchSetTo(UnicodeSet toUnionTo) {
\r
985 toUnionTo.addAll(this);
\r
989 * Returns the index of the given character within this set, where
\r
990 * the set is ordered by ascending code point. If the character
\r
991 * is not in this set, return -1. The inverse of this method is
\r
992 * <code>charAt()</code>.
\r
993 * @return an index from 0..size()-1, or -1
\r
996 public int indexOf(int c) {
\r
997 if (c < MIN_VALUE || c > MAX_VALUE) {
\r
998 throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(c, 6));
\r
1003 int start = list[i++];
\r
1007 int limit = list[i++];
\r
1009 return n + c - start;
\r
1011 n += limit - start;
\r
1016 * Returns the character at the given index within this set, where
\r
1017 * the set is ordered by ascending code point. If the index is
\r
1018 * out of range, return -1. The inverse of this method is
\r
1019 * <code>indexOf()</code>.
\r
1020 * @param index an index from 0..size()-1
\r
1021 * @return the character at the given index, or -1.
\r
1024 public int charAt(int index) {
\r
1026 // len2 is the largest even integer <= len, that is, it is len
\r
1027 // for even values and len-1 for odd values. With odd values
\r
1028 // the last entry is UNICODESET_HIGH.
\r
1029 int len2 = len & ~1;
\r
1030 for (int i=0; i < len2;) {
\r
1031 int start = list[i++];
\r
1032 int count = list[i++] - start;
\r
1033 if (index < count) {
\r
1034 return start + index;
\r
1043 * Adds the specified range to this set if it is not already
\r
1044 * present. If this set already contains the specified range,
\r
1045 * the call leaves this set unchanged. If <code>end > start</code>
\r
1046 * then an empty range is added, leaving the set unchanged.
\r
1048 * @param start first character, inclusive, of range to be added
\r
1050 * @param end last character, inclusive, of range to be added
\r
1054 public UnicodeSet add(int start, int end) {
\r
1056 return add_unchecked(start, end);
\r
1059 // for internal use, after checkFrozen has been called
\r
1060 private UnicodeSet add_unchecked(int start, int end) {
\r
1061 if (start < MIN_VALUE || start > MAX_VALUE) {
\r
1062 throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(start, 6));
\r
1064 if (end < MIN_VALUE || end > MAX_VALUE) {
\r
1065 throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(end, 6));
\r
1067 if (start < end) {
\r
1068 add(range(start, end), 2, 0);
\r
1069 } else if (start == end) {
\r
1076 // * Format out the inversion list as a string, for debugging. Uncomment when
\r
1079 // public final String dump() {
\r
1080 // StringBuffer buf = new StringBuffer("[");
\r
1081 // for (int i=0; i<len; ++i) {
\r
1082 // if (i != 0) buf.append(", ");
\r
1083 // int c = list[i];
\r
1084 // //if (c <= 0x7F && c != '\n' && c != '\r' && c != '\t' && c != ' ') {
\r
1085 // // buf.append((char) c);
\r
1087 // buf.append("U+").append(Utility.hex(c, (c<0x10000)?4:6));
\r
1090 // buf.append("]");
\r
1091 // return buf.toString();
\r
1095 * Adds the specified character to this set if it is not already
\r
1096 * present. If this set already contains the specified character,
\r
1097 * the call leaves this set unchanged.
\r
1100 public final UnicodeSet add(int c) {
\r
1102 return add_unchecked(c);
\r
1105 // for internal use only, after checkFrozen has been called
\r
1106 private final UnicodeSet add_unchecked(int c) {
\r
1107 if (c < MIN_VALUE || c > MAX_VALUE) {
\r
1108 throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(c, 6));
\r
1111 // find smallest i such that c < list[i]
\r
1112 // if odd, then it is IN the set
\r
1113 // if even, then it is OUT of the set
\r
1114 int i = findCodePoint(c);
\r
1116 // already in set?
\r
1117 if ((i & 1) != 0) return this;
\r
1119 // HIGH is 0x110000
\r
1120 // assert(list[len-1] == HIGH);
\r
1123 // [start_0, limit_0, start_1, limit_1, HIGH]
\r
1125 // [..., start_k-1, limit_k-1, start_k, limit_k, ..., HIGH]
\r
1129 // i == 0 means c is before the first range
\r
1131 if (c == list[i]-1) {
\r
1132 // c is before start of next range
\r
1134 // if we touched the HIGH mark, then add a new one
\r
1135 if (c == MAX_VALUE) {
\r
1136 ensureCapacity(len+1);
\r
1137 list[len++] = HIGH;
\r
1139 if (i > 0 && c == list[i-1]) {
\r
1140 // collapse adjacent ranges
\r
1142 // [..., start_k-1, c, c, limit_k, ..., HIGH]
\r
1145 System.arraycopy(list, i+1, list, i-1, len-i-1);
\r
1150 else if (i > 0 && c == list[i-1]) {
\r
1151 // c is after end of prior range
\r
1153 // no need to chcek for collapse here
\r
1157 // At this point we know the new char is not adjacent to
\r
1158 // any existing ranges, and it is not 10FFFF.
\r
1161 // [..., start_k-1, limit_k-1, start_k, limit_k, ..., HIGH]
\r
1165 // [..., start_k-1, limit_k-1, c, c+1, start_k, limit_k, ..., HIGH]
\r
1169 // Don't use ensureCapacity() to save on copying.
\r
1170 // NOTE: This has no measurable impact on performance,
\r
1171 // but it might help in some usage patterns.
\r
1172 if (len+2 > list.length) {
\r
1173 int[] temp = new int[len + 2 + GROW_EXTRA];
\r
1174 if (i != 0) System.arraycopy(list, 0, temp, 0, i);
\r
1175 System.arraycopy(list, i, temp, i+2, len-i);
\r
1178 System.arraycopy(list, i, list, i+2, len-i);
\r
1191 * Adds the specified multicharacter to this set if it is not already
\r
1192 * present. If this set already contains the multicharacter,
\r
1193 * the call leaves this set unchanged.
\r
1194 * Thus "ch" => {"ch"}
\r
1195 * <br><b>Warning: you cannot add an empty string ("") to a UnicodeSet.</b>
\r
1196 * @param s the source string
\r
1197 * @return this object, for chaining
\r
1200 public final UnicodeSet add(String s) {
\r
1202 int cp = getSingleCP(s);
\r
1207 add_unchecked(cp, cp);
\r
1213 * @return a code point IF the string consists of a single one.
\r
1214 * otherwise returns -1.
\r
1215 * @param string to test
\r
1217 private static int getSingleCP(String s) {
\r
1218 if (s.length() < 1) {
\r
1219 throw new IllegalArgumentException("Can't use zero-length strings in UnicodeSet");
\r
1221 if (s.length() > 2) return -1;
\r
1222 if (s.length() == 1) return s.charAt(0);
\r
1224 // at this point, len = 2
\r
1225 int cp = UTF16.charAt(s, 0);
\r
1226 if (cp > 0xFFFF) { // is surrogate pair
\r
1233 * Adds each of the characters in this string to the set. Thus "ch" => {"c", "h"}
\r
1234 * If this set already any particular character, it has no effect on that character.
\r
1235 * @param s the source string
\r
1236 * @return this object, for chaining
\r
1239 public final UnicodeSet addAll(String s) {
\r
1242 for (int i = 0; i < s.length(); i += UTF16.getCharCount(cp)) {
\r
1243 cp = UTF16.charAt(s, i);
\r
1244 add_unchecked(cp, cp);
\r
1250 * Retains EACH of the characters in this string. Note: "ch" == {"c", "h"}
\r
1251 * If this set already any particular character, it has no effect on that character.
\r
1252 * @param s the source string
\r
1253 * @return this object, for chaining
\r
1256 public final UnicodeSet retainAll(String s) {
\r
1257 return retainAll(fromAll(s));
\r
1261 * Complement EACH of the characters in this string. Note: "ch" == {"c", "h"}
\r
1262 * If this set already any particular character, it has no effect on that character.
\r
1263 * @param s the source string
\r
1264 * @return this object, for chaining
\r
1267 public final UnicodeSet complementAll(String s) {
\r
1268 return complementAll(fromAll(s));
\r
1272 * Remove EACH of the characters in this string. Note: "ch" == {"c", "h"}
\r
1273 * If this set already any particular character, it has no effect on that character.
\r
1274 * @param s the source string
\r
1275 * @return this object, for chaining
\r
1278 public final UnicodeSet removeAll(String s) {
\r
1279 return removeAll(fromAll(s));
\r
1283 * Remove all strings from this UnicodeSet
\r
1284 * @return this object, for chaining
\r
1286 * @provisional This API might change or be removed in a future release.
\r
1288 public final UnicodeSet removeAllStrings() {
\r
1290 if (strings.size() != 0) {
\r
1298 * Makes a set from a multicharacter string. Thus "ch" => {"ch"}
\r
1299 * <br><b>Warning: you cannot add an empty string ("") to a UnicodeSet.</b>
\r
1300 * @param s the source string
\r
1301 * @return a newly created set containing the given string
\r
1304 public static UnicodeSet from(String s) {
\r
1305 return new UnicodeSet().add(s);
\r
1310 * Makes a set from each of the characters in the string. Thus "ch" => {"c", "h"}
\r
1311 * @param s the source string
\r
1312 * @return a newly created set containing the given characters
\r
1315 public static UnicodeSet fromAll(String s) {
\r
1316 return new UnicodeSet().addAll(s);
\r
1321 * Retain only the elements in this set that are contained in the
\r
1322 * specified range. If <code>end > start</code> then an empty range is
\r
1323 * retained, leaving the set empty.
\r
1325 * @param start first character, inclusive, of range to be retained
\r
1327 * @param end last character, inclusive, of range to be retained
\r
1331 public UnicodeSet retain(int start, int end) {
\r
1333 if (start < MIN_VALUE || start > MAX_VALUE) {
\r
1334 throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(start, 6));
\r
1336 if (end < MIN_VALUE || end > MAX_VALUE) {
\r
1337 throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(end, 6));
\r
1339 if (start <= end) {
\r
1340 retain(range(start, end), 2, 0);
\r
1348 * Retain the specified character from this set if it is present.
\r
1349 * Upon return this set will be empty if it did not contain c, or
\r
1350 * will only contain c if it did contain c.
\r
1351 * @param c the character to be retained
\r
1352 * @return this object, for chaining
\r
1355 public final UnicodeSet retain(int c) {
\r
1356 return retain(c, c);
\r
1360 * Retain the specified string in this set if it is present.
\r
1361 * Upon return this set will be empty if it did not contain s, or
\r
1362 * will only contain s if it did contain s.
\r
1363 * @param s the string to be retained
\r
1364 * @return this object, for chaining
\r
1367 public final UnicodeSet retain(String s) {
\r
1368 int cp = getSingleCP(s);
\r
1370 boolean isIn = strings.contains(s);
\r
1371 if (isIn && size() == 1) {
\r
1384 * Removes the specified range from this set if it is present.
\r
1385 * The set will not contain the specified range once the call
\r
1386 * returns. If <code>end > start</code> then an empty range is
\r
1387 * removed, leaving the set unchanged.
\r
1389 * @param start first character, inclusive, of range to be removed
\r
1391 * @param end last character, inclusive, of range to be removed
\r
1395 public UnicodeSet remove(int start, int end) {
\r
1397 if (start < MIN_VALUE || start > MAX_VALUE) {
\r
1398 throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(start, 6));
\r
1400 if (end < MIN_VALUE || end > MAX_VALUE) {
\r
1401 throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(end, 6));
\r
1403 if (start <= end) {
\r
1404 retain(range(start, end), 2, 2);
\r
1410 * Removes the specified character from this set if it is present.
\r
1411 * The set will not contain the specified character once the call
\r
1413 * @param c the character to be removed
\r
1414 * @return this object, for chaining
\r
1417 public final UnicodeSet remove(int c) {
\r
1418 return remove(c, c);
\r
1422 * Removes the specified string from this set if it is present.
\r
1423 * The set will not contain the specified string once the call
\r
1425 * @param s the string to be removed
\r
1426 * @return this object, for chaining
\r
1429 public final UnicodeSet remove(String s) {
\r
1430 int cp = getSingleCP(s);
\r
1432 strings.remove(s);
\r
1441 * Complements the specified range in this set. Any character in
\r
1442 * the range will be removed if it is in this set, or will be
\r
1443 * added if it is not in this set. If <code>end > start</code>
\r
1444 * then an empty range is complemented, leaving the set unchanged.
\r
1446 * @param start first character, inclusive, of range to be removed
\r
1448 * @param end last character, inclusive, of range to be removed
\r
1452 public UnicodeSet complement(int start, int end) {
\r
1454 if (start < MIN_VALUE || start > MAX_VALUE) {
\r
1455 throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(start, 6));
\r
1457 if (end < MIN_VALUE || end > MAX_VALUE) {
\r
1458 throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(end, 6));
\r
1460 if (start <= end) {
\r
1461 xor(range(start, end), 2, 0);
\r
1468 * Complements the specified character in this set. The character
\r
1469 * will be removed if it is in this set, or will be added if it is
\r
1470 * not in this set.
\r
1473 public final UnicodeSet complement(int c) {
\r
1474 return complement(c, c);
\r
1478 * This is equivalent to
\r
1479 * <code>complement(MIN_VALUE, MAX_VALUE)</code>.
\r
1482 public UnicodeSet complement() {
\r
1484 if (list[0] == LOW) {
\r
1485 System.arraycopy(list, 1, list, 0, len-1);
\r
1488 ensureCapacity(len+1);
\r
1489 System.arraycopy(list, 0, list, 1, len);
\r
1498 * Complement the specified string in this set.
\r
1499 * The set will not contain the specified string once the call
\r
1501 * <br><b>Warning: you cannot add an empty string ("") to a UnicodeSet.</b>
\r
1502 * @param s the string to complement
\r
1503 * @return this object, for chaining
\r
1506 public final UnicodeSet complement(String s) {
\r
1508 int cp = getSingleCP(s);
\r
1510 if (strings.contains(s)) strings.remove(s);
\r
1511 else strings.add(s);
\r
1514 complement(cp, cp);
\r
1520 * Returns true if this set contains the given character.
\r
1521 * @param c character to be checked for containment
\r
1522 * @return true if the test condition is met
\r
1525 public boolean contains(int c) {
\r
1526 if (c < MIN_VALUE || c > MAX_VALUE) {
\r
1527 throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(c, 6));
\r
1531 // Set i to the index of the start item greater than ch
\r
1532 // We know we will terminate without length test!
\r
1535 if (c < list[++i]) break;
\r
1539 int i = findCodePoint(c);
\r
1541 return ((i & 1) != 0); // return true if odd
\r
1545 * Returns the smallest value i such that c < list[i]. Caller
\r
1546 * must ensure that c is a legal value or this method will enter
\r
1547 * an infinite loop. This method performs a binary search.
\r
1548 * @param c a character in the range MIN_VALUE..MAX_VALUE
\r
1550 * @return the smallest integer i in the range 0..len-1,
\r
1551 * inclusive, such that c < list[i]
\r
1553 private final int findCodePoint(int c) {
\r
1556 set list[] c=0 1 3 4 7 8
\r
1557 === ============== ===========
\r
1558 [] [110000] 0 0 0 0 0 0
\r
1559 [\u0000-\u0003] [0, 4, 110000] 1 1 1 2 2 2
\r
1560 [\u0004-\u0007] [4, 8, 110000] 0 0 0 1 1 2
\r
1561 [:all:] [0, 110000] 1 1 1 1 1 1
\r
1564 // Return the smallest i such that c < list[i]. Assume
\r
1565 // list[len - 1] == HIGH and that c is legal (0..HIGH-1).
\r
1566 if (c < list[0]) return 0;
\r
1567 // High runner test. c is often after the last range, so an
\r
1568 // initial check for this condition pays off.
\r
1569 if (len >= 2 && c >= list[len-2]) return len-1;
\r
1572 // invariant: c >= list[lo]
\r
1573 // invariant: c < list[hi]
\r
1575 int i = (lo + hi) >>> 1;
\r
1576 if (i == lo) return hi;
\r
1577 if (c < list[i]) {
\r
1585 // //----------------------------------------------------------------
\r
1586 // // Unrolled binary search
\r
1587 // //----------------------------------------------------------------
\r
1589 // private int validLen = -1; // validated value of len
\r
1590 // private int topOfLow;
\r
1591 // private int topOfHigh;
\r
1592 // private int power;
\r
1593 // private int deltaStart;
\r
1595 // private void validate() {
\r
1596 // if (len <= 1) {
\r
1597 // throw new IllegalArgumentException("list.len==" + len + "; must be >1");
\r
1600 // // find greatest power of 2 less than or equal to len
\r
1601 // for (power = exp2.length-1; power > 0 && exp2[power] > len; power--) {}
\r
1603 // // assert(exp2[power] <= len);
\r
1605 // // determine the starting points
\r
1606 // topOfLow = exp2[power] - 1;
\r
1607 // topOfHigh = len - 1;
\r
1608 // deltaStart = exp2[power-1];
\r
1609 // validLen = len;
\r
1612 // private static final int exp2[] = {
\r
1613 // 0x1, 0x2, 0x4, 0x8,
\r
1614 // 0x10, 0x20, 0x40, 0x80,
\r
1615 // 0x100, 0x200, 0x400, 0x800,
\r
1616 // 0x1000, 0x2000, 0x4000, 0x8000,
\r
1617 // 0x10000, 0x20000, 0x40000, 0x80000,
\r
1618 // 0x100000, 0x200000, 0x400000, 0x800000,
\r
1619 // 0x1000000, 0x2000000, 0x4000000, 0x8000000,
\r
1620 // 0x10000000, 0x20000000 // , 0x40000000 // no unsigned int in Java
\r
1624 // * Unrolled lowest index GT.
\r
1626 // private final int leastIndexGT(int searchValue) {
\r
1628 // if (len != validLen) {
\r
1629 // if (len == 1) return 0;
\r
1634 // // set up initial range to search. Each subrange is a power of two in length
\r
1635 // int high = searchValue < list[topOfLow] ? topOfLow : topOfHigh;
\r
1637 // // Completely unrolled binary search, folhighing "Programming Pearls"
\r
1638 // // Each case deliberately falls through to the next
\r
1639 // // Logically, list[-1] < all_search_values && list[count] > all_search_values
\r
1640 // // although the values -1 and count are never actually touched.
\r
1642 // // The bounds at each point are low & high,
\r
1643 // // where low == high - delta*2
\r
1644 // // so high - delta is the midpoint
\r
1646 // // The invariant AFTER each line is that list[low] < searchValue <= list[high]
\r
1648 // switch (power) {
\r
1649 // //case 31: if (searchValue < list[temp = high-0x40000000]) high = temp; // no unsigned int in Java
\r
1650 // case 30: if (searchValue < list[temp = high-0x20000000]) high = temp;
\r
1651 // case 29: if (searchValue < list[temp = high-0x10000000]) high = temp;
\r
1653 // case 28: if (searchValue < list[temp = high- 0x8000000]) high = temp;
\r
1654 // case 27: if (searchValue < list[temp = high- 0x4000000]) high = temp;
\r
1655 // case 26: if (searchValue < list[temp = high- 0x2000000]) high = temp;
\r
1656 // case 25: if (searchValue < list[temp = high- 0x1000000]) high = temp;
\r
1658 // case 24: if (searchValue < list[temp = high- 0x800000]) high = temp;
\r
1659 // case 23: if (searchValue < list[temp = high- 0x400000]) high = temp;
\r
1660 // case 22: if (searchValue < list[temp = high- 0x200000]) high = temp;
\r
1661 // case 21: if (searchValue < list[temp = high- 0x100000]) high = temp;
\r
1663 // case 20: if (searchValue < list[temp = high- 0x80000]) high = temp;
\r
1664 // case 19: if (searchValue < list[temp = high- 0x40000]) high = temp;
\r
1665 // case 18: if (searchValue < list[temp = high- 0x20000]) high = temp;
\r
1666 // case 17: if (searchValue < list[temp = high- 0x10000]) high = temp;
\r
1668 // case 16: if (searchValue < list[temp = high- 0x8000]) high = temp;
\r
1669 // case 15: if (searchValue < list[temp = high- 0x4000]) high = temp;
\r
1670 // case 14: if (searchValue < list[temp = high- 0x2000]) high = temp;
\r
1671 // case 13: if (searchValue < list[temp = high- 0x1000]) high = temp;
\r
1673 // case 12: if (searchValue < list[temp = high- 0x800]) high = temp;
\r
1674 // case 11: if (searchValue < list[temp = high- 0x400]) high = temp;
\r
1675 // case 10: if (searchValue < list[temp = high- 0x200]) high = temp;
\r
1676 // case 9: if (searchValue < list[temp = high- 0x100]) high = temp;
\r
1678 // case 8: if (searchValue < list[temp = high- 0x80]) high = temp;
\r
1679 // case 7: if (searchValue < list[temp = high- 0x40]) high = temp;
\r
1680 // case 6: if (searchValue < list[temp = high- 0x20]) high = temp;
\r
1681 // case 5: if (searchValue < list[temp = high- 0x10]) high = temp;
\r
1683 // case 4: if (searchValue < list[temp = high- 0x8]) high = temp;
\r
1684 // case 3: if (searchValue < list[temp = high- 0x4]) high = temp;
\r
1685 // case 2: if (searchValue < list[temp = high- 0x2]) high = temp;
\r
1686 // case 1: if (searchValue < list[temp = high- 0x1]) high = temp;
\r
1692 // // For debugging only
\r
1693 // public int len() {
\r
1697 // //----------------------------------------------------------------
\r
1698 // //----------------------------------------------------------------
\r
1701 * Returns true if this set contains every character
\r
1702 * of the given range.
\r
1703 * @param start first character, inclusive, of the range
\r
1704 * @param end last character, inclusive, of the range
\r
1705 * @return true if the test condition is met
\r
1708 public boolean contains(int start, int end) {
\r
1709 if (start < MIN_VALUE || start > MAX_VALUE) {
\r
1710 throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(start, 6));
\r
1712 if (end < MIN_VALUE || end > MAX_VALUE) {
\r
1713 throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(end, 6));
\r
1717 // if (start < list[++i]) break;
\r
1719 int i = findCodePoint(start);
\r
1720 return ((i & 1) != 0 && end < list[i]);
\r
1724 * Returns <tt>true</tt> if this set contains the given
\r
1725 * multicharacter string.
\r
1726 * @param s string to be checked for containment
\r
1727 * @return <tt>true</tt> if this set contains the specified string
\r
1730 public final boolean contains(String s) {
\r
1732 int cp = getSingleCP(s);
\r
1734 return strings.contains(s);
\r
1736 return contains(cp);
\r
1741 * Returns true if this set contains all the characters and strings
\r
1742 * of the given set.
\r
1743 * @param b set to be checked for containment
\r
1744 * @return true if the test condition is met
\r
1747 public boolean containsAll(UnicodeSet b) {
\r
1748 // The specified set is a subset if all of its pairs are contained in
\r
1749 // this set. This implementation accesses the lists directly for speed.
\r
1750 // TODO: this could be faster if size() were cached. But that would affect building speed
\r
1751 // so it needs investigation.
\r
1752 int[] listB = b.list;
\r
1753 boolean needA = true;
\r
1754 boolean needB = true;
\r
1757 int aLen = len - 1;
\r
1758 int bLen = b.len - 1;
\r
1759 int startA = 0, startB = 0, limitA = 0, limitB = 0;
\r
1761 // double iterations are such a pain...
\r
1763 if (aPtr >= aLen) {
\r
1764 // ran out of A. If B is also exhausted, then break;
\r
1765 if (needB && bPtr >= bLen) {
\r
1770 startA = list[aPtr++];
\r
1771 limitA = list[aPtr++];
\r
1774 if (bPtr >= bLen) {
\r
1775 // ran out of B. Since we got this far, we have an A and we are ok so far
\r
1778 startB = listB[bPtr++];
\r
1779 limitB = listB[bPtr++];
\r
1781 // if B doesn't overlap and is greater than A, get new A
\r
1782 if (startB >= limitA) {
\r
1787 // if B is wholy contained in A, then get a new B
\r
1788 if (startB >= startA && limitB <= limitA) {
\r
1793 // all other combinations mean we fail
\r
1797 if (!strings.containsAll(b.strings)) return false;
\r
1802 // * Returns true if this set contains all the characters and strings
\r
1803 // * of the given set.
\r
1804 // * @param c set to be checked for containment
\r
1805 // * @return true if the test condition is met
\r
1806 // * @stable ICU 2.0
\r
1808 // public boolean containsAllOld(UnicodeSet c) {
\r
1809 // // The specified set is a subset if all of its pairs are contained in
\r
1810 // // this set. It's possible to code this more efficiently in terms of
\r
1811 // // direct manipulation of the inversion lists if the need arises.
\r
1812 // int n = c.getRangeCount();
\r
1813 // for (int i=0; i<n; ++i) {
\r
1814 // if (!contains(c.getRangeStart(i), c.getRangeEnd(i))) {
\r
1818 // if (!strings.containsAll(c.strings)) return false;
\r
1823 * Returns true if there is a partition of the string such that this set contains each of the partitioned strings.
\r
1824 * For example, for the Unicode set [a{bc}{cd}]<br>
\r
1825 * containsAll is true for each of: "a", "bc", ""cdbca"<br>
\r
1826 * containsAll is false for each of: "acb", "bcda", "bcx"<br>
\r
1827 * @param s string containing characters to be checked for containment
\r
1828 * @return true if the test condition is met
\r
1831 public boolean containsAll(String s) {
\r
1833 for (int i = 0; i < s.length(); i += UTF16.getCharCount(cp)) {
\r
1834 cp = UTF16.charAt(s, i);
\r
1835 if (!contains(cp)) {
\r
1836 if (strings.size() == 0) {
\r
1839 return containsAll(s, 0);
\r
1846 * Recursive routine called if we fail to find a match in containsAll, and there are strings
\r
1847 * @param s source string
\r
1848 * @param i point to match to the end on
\r
1849 * @return true if ok
\r
1851 private boolean containsAll(String s, int i) {
\r
1852 if (i >= s.length()) {
\r
1855 int cp= UTF16.charAt(s, i);
\r
1856 if (contains(cp) && containsAll(s, i+UTF16.getCharCount(cp))) {
\r
1860 Iterator it = strings.iterator();
\r
1861 while (it.hasNext()) {
\r
1862 String setStr = (String)it.next();
\r
1863 if (s.startsWith(setStr, i) && containsAll(s, i+setStr.length())) {
\r
1872 * Get the Regex equivalent for this UnicodeSet
\r
1873 * @return regex pattern equivalent to this UnicodeSet
\r
1875 * @deprecated This API is ICU internal only.
\r
1877 public String getRegexEquivalent() {
\r
1878 if (strings.size() == 0) return toString();
\r
1879 StringBuffer result = new StringBuffer("(?:");
\r
1880 _generatePattern(result, true, false);
\r
1881 Iterator it = strings.iterator();
\r
1882 while (it.hasNext()) {
\r
1883 result.append('|');
\r
1884 _appendToPat(result, (String) it.next(), true);
\r
1886 return result.append(")").toString();
\r
1890 * Returns true if this set contains none of the characters
\r
1891 * of the given range.
\r
1892 * @param start first character, inclusive, of the range
\r
1893 * @param end last character, inclusive, of the range
\r
1894 * @return true if the test condition is met
\r
1897 public boolean containsNone(int start, int end) {
\r
1898 if (start < MIN_VALUE || start > MAX_VALUE) {
\r
1899 throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(start, 6));
\r
1901 if (end < MIN_VALUE || end > MAX_VALUE) {
\r
1902 throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(end, 6));
\r
1906 if (start < list[++i]) break;
\r
1908 return ((i & 1) == 0 && end < list[i]);
\r
1912 * Returns true if none of the characters or strings in this UnicodeSet appears in the string.
\r
1913 * For example, for the Unicode set [a{bc}{cd}]<br>
\r
1914 * containsNone is true for: "xy", "cb"<br>
\r
1915 * containsNone is false for: "a", "bc", "bcd"<br>
\r
1916 * @param b set to be checked for containment
\r
1917 * @return true if the test condition is met
\r
1920 public boolean containsNone(UnicodeSet b) {
\r
1921 // The specified set is a subset if some of its pairs overlap with some of this set's pairs.
\r
1922 // This implementation accesses the lists directly for speed.
\r
1923 int[] listB = b.list;
\r
1924 boolean needA = true;
\r
1925 boolean needB = true;
\r
1928 int aLen = len - 1;
\r
1929 int bLen = b.len - 1;
\r
1930 int startA = 0, startB = 0, limitA = 0, limitB = 0;
\r
1932 // double iterations are such a pain...
\r
1934 if (aPtr >= aLen) {
\r
1935 // ran out of A: break so we test strings
\r
1938 startA = list[aPtr++];
\r
1939 limitA = list[aPtr++];
\r
1942 if (bPtr >= bLen) {
\r
1943 // ran out of B: break so we test strings
\r
1946 startB = listB[bPtr++];
\r
1947 limitB = listB[bPtr++];
\r
1949 // if B is higher than any part of A, get new A
\r
1950 if (startB >= limitA) {
\r
1955 // if A is higher than any part of B, get new B
\r
1956 if (startA >= limitB) {
\r
1961 // all other combinations mean we fail
\r
1965 if (!SortedSetRelation.hasRelation(strings, SortedSetRelation.DISJOINT, b.strings)) return false;
\r
1970 // * Returns true if none of the characters or strings in this UnicodeSet appears in the string.
\r
1971 // * For example, for the Unicode set [a{bc}{cd}]<br>
\r
1972 // * containsNone is true for: "xy", "cb"<br>
\r
1973 // * containsNone is false for: "a", "bc", "bcd"<br>
\r
1974 // * @param c set to be checked for containment
\r
1975 // * @return true if the test condition is met
\r
1976 // * @stable ICU 2.0
\r
1978 // public boolean containsNoneOld(UnicodeSet c) {
\r
1979 // // The specified set is a subset if all of its pairs are contained in
\r
1980 // // this set. It's possible to code this more efficiently in terms of
\r
1981 // // direct manipulation of the inversion lists if the need arises.
\r
1982 // int n = c.getRangeCount();
\r
1983 // for (int i=0; i<n; ++i) {
\r
1984 // if (!containsNone(c.getRangeStart(i), c.getRangeEnd(i))) {
\r
1988 // if (!SortedSetRelation.hasRelation(strings, SortedSetRelation.DISJOINT, c.strings)) return false;
\r
1993 * Returns true if this set contains none of the characters
\r
1994 * of the given string.
\r
1995 * @param s string containing characters to be checked for containment
\r
1996 * @return true if the test condition is met
\r
1999 public boolean containsNone(String s) {
\r
2001 for (int i = 0; i < s.length(); i += UTF16.getCharCount(cp)) {
\r
2002 cp = UTF16.charAt(s, i);
\r
2003 if (contains(cp)) return false;
\r
2005 if (strings.size() == 0) return true;
\r
2006 // do a last check to make sure no strings are in.
\r
2007 for (Iterator it = strings.iterator(); it.hasNext();) {
\r
2008 String item = (String)it.next();
\r
2009 if (s.indexOf(item) >= 0) return false;
\r
2015 * Returns true if this set contains one or more of the characters
\r
2016 * in the given range.
\r
2017 * @param start first character, inclusive, of the range
\r
2018 * @param end last character, inclusive, of the range
\r
2019 * @return true if the condition is met
\r
2022 public final boolean containsSome(int start, int end) {
\r
2023 return !containsNone(start, end);
\r
2027 * Returns true if this set contains one or more of the characters
\r
2028 * and strings of the given set.
\r
2029 * @param s set to be checked for containment
\r
2030 * @return true if the condition is met
\r
2033 public final boolean containsSome(UnicodeSet s) {
\r
2034 return !containsNone(s);
\r
2038 * Returns true if this set contains one or more of the characters
\r
2039 * of the given string.
\r
2040 * @param s string containing characters to be checked for containment
\r
2041 * @return true if the condition is met
\r
2044 public final boolean containsSome(String s) {
\r
2045 return !containsNone(s);
\r
2050 * Adds all of the elements in the specified set to this set if
\r
2051 * they're not already present. This operation effectively
\r
2052 * modifies this set so that its value is the <i>union</i> of the two
\r
2053 * sets. The behavior of this operation is unspecified if the specified
\r
2054 * collection is modified while the operation is in progress.
\r
2056 * @param c set whose elements are to be added to this set.
\r
2059 public UnicodeSet addAll(UnicodeSet c) {
\r
2061 add(c.list, c.len, 0);
\r
2062 strings.addAll(c.strings);
\r
2067 * Retains only the elements in this set that are contained in the
\r
2068 * specified set. In other words, removes from this set all of
\r
2069 * its elements that are not contained in the specified set. This
\r
2070 * operation effectively modifies this set so that its value is
\r
2071 * the <i>intersection</i> of the two sets.
\r
2073 * @param c set that defines which elements this set will retain.
\r
2076 public UnicodeSet retainAll(UnicodeSet c) {
\r
2078 retain(c.list, c.len, 0);
\r
2079 strings.retainAll(c.strings);
\r
2084 * Removes from this set all of its elements that are contained in the
\r
2085 * specified set. This operation effectively modifies this
\r
2086 * set so that its value is the <i>asymmetric set difference</i> of
\r
2089 * @param c set that defines which elements will be removed from
\r
2093 public UnicodeSet removeAll(UnicodeSet c) {
\r
2095 retain(c.list, c.len, 2);
\r
2096 strings.removeAll(c.strings);
\r
2101 * Complements in this set all elements contained in the specified
\r
2102 * set. Any character in the other set will be removed if it is
\r
2103 * in this set, or will be added if it is not in this set.
\r
2105 * @param c set that defines which elements will be complemented from
\r
2109 public UnicodeSet complementAll(UnicodeSet c) {
\r
2111 xor(c.list, c.len, 0);
\r
2112 SortedSetRelation.doOperation(strings, SortedSetRelation.COMPLEMENTALL, c.strings);
\r
2117 * Removes all of the elements from this set. This set will be
\r
2118 * empty after this call returns.
\r
2121 public UnicodeSet clear() {
\r
2131 * Iteration method that returns the number of ranges contained in
\r
2133 * @see #getRangeStart
\r
2134 * @see #getRangeEnd
\r
2137 public int getRangeCount() {
\r
2142 * Iteration method that returns the first character in the
\r
2143 * specified range of this set.
\r
2144 * @exception ArrayIndexOutOfBoundsException if index is outside
\r
2145 * the range <code>0..getRangeCount()-1</code>
\r
2146 * @see #getRangeCount
\r
2147 * @see #getRangeEnd
\r
2150 public int getRangeStart(int index) {
\r
2151 return list[index*2];
\r
2155 * Iteration method that returns the last character in the
\r
2156 * specified range of this set.
\r
2157 * @exception ArrayIndexOutOfBoundsException if index is outside
\r
2158 * the range <code>0..getRangeCount()-1</code>
\r
2159 * @see #getRangeStart
\r
2160 * @see #getRangeEnd
\r
2163 public int getRangeEnd(int index) {
\r
2164 return (list[index*2 + 1] - 1);
\r
2168 * Reallocate this objects internal structures to take up the least
\r
2169 * possible space, without changing this object's value.
\r
2172 public UnicodeSet compact() {
\r
2174 if (len != list.length) {
\r
2175 int[] temp = new int[len];
\r
2176 System.arraycopy(list, 0, temp, 0, len);
\r
2185 * Compares the specified object with this set for equality. Returns
\r
2186 * <tt>true</tt> if the specified object is also a set, the two sets
\r
2187 * have the same size, and every member of the specified set is
\r
2188 * contained in this set (or equivalently, every member of this set is
\r
2189 * contained in the specified set).
\r
2191 * @param o Object to be compared for equality with this set.
\r
2192 * @return <tt>true</tt> if the specified Object is equal to this set.
\r
2195 public boolean equals(Object o) {
\r
2197 UnicodeSet that = (UnicodeSet) o;
\r
2198 if (len != that.len) return false;
\r
2199 for (int i = 0; i < len; ++i) {
\r
2200 if (list[i] != that.list[i]) return false;
\r
2202 if (!strings.equals(that.strings)) return false;
\r
2203 } catch (Exception e) {
\r
2210 * Returns the hash code value for this set.
\r
2212 * @return the hash code value for this set.
\r
2213 * @see java.lang.Object#hashCode()
\r
2216 public int hashCode() {
\r
2218 for (int i = 0; i < len; ++i) {
\r
2219 result *= 1000003;
\r
2220 result += list[i];
\r
2226 * Return a programmer-readable string representation of this object.
\r
2229 public String toString() {
\r
2230 return toPattern(true);
\r
2233 //----------------------------------------------------------------
\r
2234 // Implementation: Pattern parsing
\r
2235 //----------------------------------------------------------------
\r
2238 * Parses the given pattern, starting at the given position. The character
\r
2239 * at pattern.charAt(pos.getIndex()) must be '[', or the parse fails.
\r
2240 * Parsing continues until the corresponding closing ']'. If a syntax error
\r
2241 * is encountered between the opening and closing brace, the parse fails.
\r
2242 * Upon return from a successful parse, the ParsePosition is updated to
\r
2243 * point to the character following the closing ']', and an inversion
\r
2244 * list for the parsed pattern is returned. This method
\r
2245 * calls itself recursively to parse embedded subpatterns.
\r
2247 * @param pattern the string containing the pattern to be parsed. The
\r
2248 * portion of the string from pos.getIndex(), which must be a '[', to the
\r
2249 * corresponding closing ']', is parsed.
\r
2250 * @param pos upon entry, the position at which to being parsing. The
\r
2251 * character at pattern.charAt(pos.getIndex()) must be a '['. Upon return
\r
2252 * from a successful parse, pos.getIndex() is either the character after the
\r
2253 * closing ']' of the parsed pattern, or pattern.length() if the closing ']'
\r
2254 * is the last character of the pattern string.
\r
2255 * @return an inversion list for the parsed substring
\r
2256 * of <code>pattern</code>
\r
2257 * @exception java.lang.IllegalArgumentException if the parse fails.
\r
2259 * @deprecated - for internal use only
\r
2261 public UnicodeSet applyPattern(String pattern,
\r
2262 ParsePosition pos,
\r
2263 SymbolTable symbols,
\r
2266 // Need to build the pattern in a temporary string because
\r
2267 // _applyPattern calls add() etc., which set pat to empty.
\r
2268 boolean parsePositionWasNull = pos == null;
\r
2269 if (parsePositionWasNull) {
\r
2270 pos = new ParsePosition(0);
\r
2273 StringBuffer rebuiltPat = new StringBuffer();
\r
2274 RuleCharacterIterator chars =
\r
2275 new RuleCharacterIterator(pattern, symbols, pos);
\r
2276 applyPattern(chars, symbols, rebuiltPat, options);
\r
2277 if (chars.inVariable()) {
\r
2278 syntaxError(chars, "Extra chars in variable value");
\r
2280 pat = rebuiltPat.toString();
\r
2281 if (parsePositionWasNull) {
\r
2282 int i = pos.getIndex();
\r
2284 // Skip over trailing whitespace
\r
2285 if ((options & IGNORE_SPACE) != 0) {
\r
2286 i = Utility.skipWhitespace(pattern, i);
\r
2289 if (i != pattern.length()) {
\r
2290 throw new IllegalArgumentException("Parse of \"" + pattern +
\r
2291 "\" failed at " + i);
\r
2298 * Parse the pattern from the given RuleCharacterIterator. The
\r
2299 * iterator is advanced over the parsed pattern.
\r
2300 * @param chars iterator over the pattern characters. Upon return
\r
2301 * it will be advanced to the first character after the parsed
\r
2302 * pattern, or the end of the iteration if all characters are
\r
2304 * @param symbols symbol table to use to parse and dereference
\r
2305 * variables, or null if none.
\r
2306 * @param rebuiltPat the pattern that was parsed, rebuilt or
\r
2307 * copied from the input pattern, as appropriate.
\r
2308 * @param options a bit mask of zero or more of the following:
\r
2309 * IGNORE_SPACE, CASE.
\r
2311 void applyPattern(RuleCharacterIterator chars, SymbolTable symbols,
\r
2312 StringBuffer rebuiltPat, int options) {
\r
2314 // Syntax characters: [ ] ^ - & { }
\r
2316 // Recognized special forms for chars, sets: c-c s-s s&s
\r
2318 int opts = RuleCharacterIterator.PARSE_VARIABLES |
\r
2319 RuleCharacterIterator.PARSE_ESCAPES;
\r
2320 if ((options & IGNORE_SPACE) != 0) {
\r
2321 opts |= RuleCharacterIterator.SKIP_WHITESPACE;
\r
2324 StringBuffer patBuf = new StringBuffer(), buf = null;
\r
2325 boolean usePat = false;
\r
2326 UnicodeSet scratch = null;
\r
2327 Object backup = null;
\r
2329 // mode: 0=before [, 1=between [...], 2=after ]
\r
2330 // lastItem: 0=none, 1=char, 2=set
\r
2331 int lastItem = 0, lastChar = 0, mode = 0;
\r
2334 boolean invert = false;
\r
2338 while (mode != 2 && !chars.atEnd()) {
\r
2340 // Debugging assertion
\r
2341 if (!((lastItem == 0 && op == 0) ||
\r
2342 (lastItem == 1 && (op == 0 || op == '-')) ||
\r
2343 (lastItem == 2 && (op == 0 || op == '-' || op == '&')))) {
\r
2344 throw new IllegalArgumentException();
\r
2349 boolean literal = false;
\r
2350 UnicodeSet nested = null;
\r
2352 // -------- Check for property pattern
\r
2354 // setMode: 0=none, 1=unicodeset, 2=propertypat, 3=preparsed
\r
2356 if (resemblesPropertyPattern(chars, opts)) {
\r
2360 // -------- Parse '[' of opening delimiter OR nested set.
\r
2361 // If there is a nested set, use `setMode' to define how
\r
2362 // the set should be parsed. If the '[' is part of the
\r
2363 // opening delimiter for this pattern, parse special
\r
2364 // strings "[", "[^", "[-", and "[^-". Check for stand-in
\r
2365 // characters representing a nested set in the symbol
\r
2369 // Prepare to backup if necessary
\r
2370 backup = chars.getPos(backup);
\r
2371 c = chars.next(opts);
\r
2372 literal = chars.isEscaped();
\r
2374 if (c == '[' && !literal) {
\r
2376 chars.setPos(backup); // backup
\r
2379 // Handle opening '[' delimiter
\r
2381 patBuf.append('[');
\r
2382 backup = chars.getPos(backup); // prepare to backup
\r
2383 c = chars.next(opts);
\r
2384 literal = chars.isEscaped();
\r
2385 if (c == '^' && !literal) {
\r
2387 patBuf.append('^');
\r
2388 backup = chars.getPos(backup); // prepare to backup
\r
2389 c = chars.next(opts);
\r
2390 literal = chars.isEscaped();
\r
2392 // Fall through to handle special leading '-';
\r
2393 // otherwise restart loop for nested [], \p{}, etc.
\r
2396 // Fall through to handle literal '-' below
\r
2398 chars.setPos(backup); // backup
\r
2402 } else if (symbols != null) {
\r
2403 UnicodeMatcher m = symbols.lookupMatcher(c); // may be null
\r
2406 nested = (UnicodeSet) m;
\r
2408 } catch (ClassCastException e) {
\r
2409 syntaxError(chars, "Syntax error");
\r
2415 // -------- Handle a nested set. This either is inline in
\r
2416 // the pattern or represented by a stand-in that has
\r
2417 // previously been parsed and was looked up in the symbol
\r
2420 if (setMode != 0) {
\r
2421 if (lastItem == 1) {
\r
2423 syntaxError(chars, "Char expected after operator");
\r
2425 add_unchecked(lastChar, lastChar);
\r
2426 _appendToPat(patBuf, lastChar, false);
\r
2427 lastItem = op = 0;
\r
2430 if (op == '-' || op == '&') {
\r
2431 patBuf.append(op);
\r
2434 if (nested == null) {
\r
2435 if (scratch == null) scratch = new UnicodeSet();
\r
2438 switch (setMode) {
\r
2440 nested.applyPattern(chars, symbols, patBuf, options);
\r
2443 chars.skipIgnored(opts);
\r
2444 nested.applyPropertyPattern(chars, patBuf, symbols);
\r
2446 case 3: // `nested' already parsed
\r
2447 nested._toPattern(patBuf, false);
\r
2454 // Entire pattern is a category; leave parse loop
\r
2462 removeAll(nested);
\r
2465 retainAll(nested);
\r
2479 syntaxError(chars, "Missing '['");
\r
2482 // -------- Parse special (syntax) characters. If the
\r
2483 // current character is not special, or if it is escaped,
\r
2484 // then fall through and handle it below.
\r
2489 if (lastItem == 1) {
\r
2490 add_unchecked(lastChar, lastChar);
\r
2491 _appendToPat(patBuf, lastChar, false);
\r
2493 // Treat final trailing '-' as a literal
\r
2495 add_unchecked(op, op);
\r
2496 patBuf.append(op);
\r
2497 } else if (op == '&') {
\r
2498 syntaxError(chars, "Trailing '&'");
\r
2500 patBuf.append(']');
\r
2505 if (lastItem != 0) {
\r
2509 // Treat final trailing '-' as a literal
\r
2510 add_unchecked(c, c);
\r
2511 c = chars.next(opts);
\r
2512 literal = chars.isEscaped();
\r
2513 if (c == ']' && !literal) {
\r
2514 patBuf.append("-]");
\r
2520 syntaxError(chars, "'-' not after char or set");
\r
2522 if (lastItem == 2 && op == 0) {
\r
2526 syntaxError(chars, "'&' not after set");
\r
2528 syntaxError(chars, "'^' not after '['");
\r
2531 syntaxError(chars, "Missing operand after operator");
\r
2533 if (lastItem == 1) {
\r
2534 add_unchecked(lastChar, lastChar);
\r
2535 _appendToPat(patBuf, lastChar, false);
\r
2538 if (buf == null) {
\r
2539 buf = new StringBuffer();
\r
2543 boolean ok = false;
\r
2544 while (!chars.atEnd()) {
\r
2545 c = chars.next(opts);
\r
2546 literal = chars.isEscaped();
\r
2547 if (c == '}' && !literal) {
\r
2551 UTF16.append(buf, c);
\r
2553 if (buf.length() < 1 || !ok) {
\r
2554 syntaxError(chars, "Invalid multicharacter string");
\r
2556 // We have new string. Add it to set and continue;
\r
2557 // we don't need to drop through to the further
\r
2559 add(buf.toString());
\r
2560 patBuf.append('{');
\r
2561 _appendToPat(patBuf, buf.toString(), false);
\r
2562 patBuf.append('}');
\r
2564 case SymbolTable.SYMBOL_REF:
\r
2565 // symbols nosymbols
\r
2566 // [a-$] error error (ambiguous)
\r
2567 // [a$] anchor anchor
\r
2568 // [a-$x] var "x"* literal '$'
\r
2569 // [a-$.] error literal '$'
\r
2570 // *We won't get here in the case of var "x"
\r
2571 backup = chars.getPos(backup);
\r
2572 c = chars.next(opts);
\r
2573 literal = chars.isEscaped();
\r
2574 boolean anchor = (c == ']' && !literal);
\r
2575 if (symbols == null && !anchor) {
\r
2576 c = SymbolTable.SYMBOL_REF;
\r
2577 chars.setPos(backup);
\r
2578 break; // literal '$'
\r
2580 if (anchor && op == 0) {
\r
2581 if (lastItem == 1) {
\r
2582 add_unchecked(lastChar, lastChar);
\r
2583 _appendToPat(patBuf, lastChar, false);
\r
2585 add_unchecked(UnicodeMatcher.ETHER);
\r
2587 patBuf.append(SymbolTable.SYMBOL_REF).append(']');
\r
2591 syntaxError(chars, "Unquoted '$'");
\r
2597 // -------- Parse literal characters. This includes both
\r
2598 // escaped chars ("\u4E01") and non-syntax characters
\r
2601 switch (lastItem) {
\r
2608 if (lastChar >= c) {
\r
2609 // Don't allow redundant (a-a) or empty (b-a) ranges;
\r
2610 // these are most likely typos.
\r
2611 syntaxError(chars, "Invalid range");
\r
2613 add_unchecked(lastChar, c);
\r
2614 _appendToPat(patBuf, lastChar, false);
\r
2615 patBuf.append(op);
\r
2616 _appendToPat(patBuf, c, false);
\r
2617 lastItem = op = 0;
\r
2619 add_unchecked(lastChar, lastChar);
\r
2620 _appendToPat(patBuf, lastChar, false);
\r
2626 syntaxError(chars, "Set expected after operator");
\r
2635 syntaxError(chars, "Missing ']'");
\r
2638 chars.skipIgnored(opts);
\r
2641 * Handle global flags (invert, case insensitivity). If this
\r
2642 * pattern should be compiled case-insensitive, then we need
\r
2643 * to close over case BEFORE COMPLEMENTING. This makes
\r
2644 * patterns like /[^abc]/i work.
\r
2646 if ((options & CASE) != 0) {
\r
2653 // Use the rebuilt pattern (pat) only if necessary. Prefer the
\r
2654 // generated pattern.
\r
2656 rebuiltPat.append(patBuf.toString());
\r
2658 _generatePattern(rebuiltPat, false, true);
\r
2662 private static void syntaxError(RuleCharacterIterator chars, String msg) {
\r
2663 throw new IllegalArgumentException("Error: " + msg + " at \"" +
\r
2664 Utility.escape(chars.toString()) +
\r
2669 * Add the contents of the UnicodeSet (as strings) into a collection.
\r
2670 * @param target collection to add into
\r
2673 public void addAllTo(Collection target) {
\r
2674 UnicodeSetIterator it = new UnicodeSetIterator(this);
\r
2675 while (it.next()) {
\r
2676 target.add(it.getString());
\r
2681 * Add the contents of the collection (as strings) into this UnicodeSet.
\r
2682 * @param source the collection to add
\r
2685 public void addAll(Collection source) {
\r
2687 Iterator it = source.iterator();
\r
2688 while (it.hasNext()) {
\r
2689 add(it.next().toString());
\r
2693 //----------------------------------------------------------------
\r
2694 // Implementation: Utility methods
\r
2695 //----------------------------------------------------------------
\r
2697 private void ensureCapacity(int newLen) {
\r
2698 if (newLen <= list.length) return;
\r
2699 int[] temp = new int[newLen + GROW_EXTRA];
\r
2700 System.arraycopy(list, 0, temp, 0, len);
\r
2704 private void ensureBufferCapacity(int newLen) {
\r
2705 if (buffer != null && newLen <= buffer.length) return;
\r
2706 buffer = new int[newLen + GROW_EXTRA];
\r
2710 * Assumes start <= end.
\r
2712 private int[] range(int start, int end) {
\r
2713 if (rangeList == null) {
\r
2714 rangeList = new int[] { start, end+1, HIGH };
\r
2716 rangeList[0] = start;
\r
2717 rangeList[1] = end+1;
\r
2722 //----------------------------------------------------------------
\r
2723 // Implementation: Fundamental operations
\r
2724 //----------------------------------------------------------------
\r
2726 // polarity = 0, 3 is normal: x xor y
\r
2727 // polarity = 1, 2: x xor ~y == x === y
\r
2729 private UnicodeSet xor(int[] other, int otherLen, int polarity) {
\r
2730 ensureBufferCapacity(len + otherLen);
\r
2731 int i = 0, j = 0, k = 0;
\r
2732 int a = list[i++];
\r
2734 if (polarity == 1 || polarity == 2) {
\r
2736 if (other[j] == LOW) { // skip base if already LOW
\r
2743 // simplest of all the routines
\r
2744 // sort the values, discarding identicals!
\r
2749 } else if (b < a) {
\r
2752 } else if (a != HIGH) { // at this point, a == b
\r
2753 // discard both values!
\r
2757 buffer[k++] = HIGH;
\r
2762 // swap list and buffer
\r
2763 int[] temp = list;
\r
2770 // polarity = 0 is normal: x union y
\r
2771 // polarity = 2: x union ~y
\r
2772 // polarity = 1: ~x union y
\r
2773 // polarity = 3: ~x union ~y
\r
2775 private UnicodeSet add(int[] other, int otherLen, int polarity) {
\r
2776 ensureBufferCapacity(len + otherLen);
\r
2777 int i = 0, j = 0, k = 0;
\r
2778 int a = list[i++];
\r
2779 int b = other[j++];
\r
2780 // change from xor is that we have to check overlapping pairs
\r
2781 // polarity bit 1 means a is second, bit 2 means b is.
\r
2784 switch (polarity) {
\r
2785 case 0: // both first; take lower if unequal
\r
2786 if (a < b) { // take a
\r
2787 // Back up over overlapping ranges in buffer[]
\r
2788 if (k > 0 && a <= buffer[k-1]) {
\r
2789 // Pick latter end value in buffer[] vs. list[]
\r
2790 a = max(list[i], buffer[--k]);
\r
2796 i++; // Common if/else code factored out
\r
2798 } else if (b < a) { // take b
\r
2799 if (k > 0 && b <= buffer[k-1]) {
\r
2800 b = max(other[j], buffer[--k]);
\r
2807 } else { // a == b, take a, drop b
\r
2808 if (a == HIGH) break main;
\r
2809 // This is symmetrical; it doesn't matter if
\r
2810 // we backtrack with a or b. - liu
\r
2811 if (k > 0 && a <= buffer[k-1]) {
\r
2812 a = max(list[i], buffer[--k]);
\r
2820 b = other[j++]; polarity ^= 2;
\r
2823 case 3: // both second; take higher if unequal, and drop other
\r
2824 if (b <= a) { // take a
\r
2825 if (a == HIGH) break main;
\r
2827 } else { // take b
\r
2828 if (b == HIGH) break main;
\r
2831 a = list[i++]; polarity ^= 1; // factored common code
\r
2832 b = other[j++]; polarity ^= 2;
\r
2834 case 1: // a second, b first; if b < a, overlap
\r
2835 if (a < b) { // no overlap, take a
\r
2836 buffer[k++] = a; a = list[i++]; polarity ^= 1;
\r
2837 } else if (b < a) { // OVERLAP, drop b
\r
2838 b = other[j++]; polarity ^= 2;
\r
2839 } else { // a == b, drop both!
\r
2840 if (a == HIGH) break main;
\r
2841 a = list[i++]; polarity ^= 1;
\r
2842 b = other[j++]; polarity ^= 2;
\r
2845 case 2: // a first, b second; if a < b, overlap
\r
2846 if (b < a) { // no overlap, take b
\r
2847 buffer[k++] = b; b = other[j++]; polarity ^= 2;
\r
2848 } else if (a < b) { // OVERLAP, drop a
\r
2849 a = list[i++]; polarity ^= 1;
\r
2850 } else { // a == b, drop both!
\r
2851 if (a == HIGH) break main;
\r
2852 a = list[i++]; polarity ^= 1;
\r
2853 b = other[j++]; polarity ^= 2;
\r
2858 buffer[k++] = HIGH; // terminate
\r
2860 // swap list and buffer
\r
2861 int[] temp = list;
\r
2868 // polarity = 0 is normal: x intersect y
\r
2869 // polarity = 2: x intersect ~y == set-minus
\r
2870 // polarity = 1: ~x intersect y
\r
2871 // polarity = 3: ~x intersect ~y
\r
2873 private UnicodeSet retain(int[] other, int otherLen, int polarity) {
\r
2874 ensureBufferCapacity(len + otherLen);
\r
2875 int i = 0, j = 0, k = 0;
\r
2876 int a = list[i++];
\r
2877 int b = other[j++];
\r
2878 // change from xor is that we have to check overlapping pairs
\r
2879 // polarity bit 1 means a is second, bit 2 means b is.
\r
2882 switch (polarity) {
\r
2883 case 0: // both first; drop the smaller
\r
2884 if (a < b) { // drop a
\r
2885 a = list[i++]; polarity ^= 1;
\r
2886 } else if (b < a) { // drop b
\r
2887 b = other[j++]; polarity ^= 2;
\r
2888 } else { // a == b, take one, drop other
\r
2889 if (a == HIGH) break main;
\r
2890 buffer[k++] = a; a = list[i++]; polarity ^= 1;
\r
2891 b = other[j++]; polarity ^= 2;
\r
2894 case 3: // both second; take lower if unequal
\r
2895 if (a < b) { // take a
\r
2896 buffer[k++] = a; a = list[i++]; polarity ^= 1;
\r
2897 } else if (b < a) { // take b
\r
2898 buffer[k++] = b; b = other[j++]; polarity ^= 2;
\r
2899 } else { // a == b, take one, drop other
\r
2900 if (a == HIGH) break main;
\r
2901 buffer[k++] = a; a = list[i++]; polarity ^= 1;
\r
2902 b = other[j++]; polarity ^= 2;
\r
2905 case 1: // a second, b first;
\r
2906 if (a < b) { // NO OVERLAP, drop a
\r
2907 a = list[i++]; polarity ^= 1;
\r
2908 } else if (b < a) { // OVERLAP, take b
\r
2909 buffer[k++] = b; b = other[j++]; polarity ^= 2;
\r
2910 } else { // a == b, drop both!
\r
2911 if (a == HIGH) break main;
\r
2912 a = list[i++]; polarity ^= 1;
\r
2913 b = other[j++]; polarity ^= 2;
\r
2916 case 2: // a first, b second; if a < b, overlap
\r
2917 if (b < a) { // no overlap, drop b
\r
2918 b = other[j++]; polarity ^= 2;
\r
2919 } else if (a < b) { // OVERLAP, take a
\r
2920 buffer[k++] = a; a = list[i++]; polarity ^= 1;
\r
2921 } else { // a == b, drop both!
\r
2922 if (a == HIGH) break main;
\r
2923 a = list[i++]; polarity ^= 1;
\r
2924 b = other[j++]; polarity ^= 2;
\r
2929 buffer[k++] = HIGH; // terminate
\r
2931 // swap list and buffer
\r
2932 int[] temp = list;
\r
2939 private static final int max(int a, int b) {
\r
2940 return (a > b) ? a : b;
\r
2943 //----------------------------------------------------------------
\r
2944 // Generic filter-based scanning code
\r
2945 //----------------------------------------------------------------
\r
2947 private static interface Filter {
\r
2948 boolean contains(int codePoint);
\r
2951 private static class NumericValueFilter implements Filter {
\r
2953 NumericValueFilter(double value) { this.value = value; }
\r
2954 public boolean contains(int ch) {
\r
2955 return UCharacter.getUnicodeNumericValue(ch) == value;
\r
2959 private static class GeneralCategoryMaskFilter implements Filter {
\r
2961 GeneralCategoryMaskFilter(int mask) { this.mask = mask; }
\r
2962 public boolean contains(int ch) {
\r
2963 return ((1 << UCharacter.getType(ch)) & mask) != 0;
\r
2967 private static class IntPropertyFilter implements Filter {
\r
2970 IntPropertyFilter(int prop, int value) {
\r
2972 this.value = value;
\r
2974 public boolean contains(int ch) {
\r
2975 return UCharacter.getIntPropertyValue(ch, prop) == value;
\r
2979 // VersionInfo for unassigned characters
\r
2980 static final VersionInfo NO_VERSION = VersionInfo.getInstance(0, 0, 0, 0);
\r
2982 private static class VersionFilter implements Filter {
\r
2983 VersionInfo version;
\r
2984 VersionFilter(VersionInfo version) { this.version = version; }
\r
2985 public boolean contains(int ch) {
\r
2986 VersionInfo v = UCharacter.getAge(ch);
\r
2987 // Reference comparison ok; VersionInfo caches and reuses
\r
2988 // unique objects.
\r
2989 return v != NO_VERSION &&
\r
2990 v.compareTo(version) <= 0;
\r
2994 private static synchronized UnicodeSet getInclusions(int src) {
\r
2995 if (INCLUSIONS == null) {
\r
2996 INCLUSIONS = new UnicodeSet[UCharacterProperty.SRC_COUNT];
\r
2998 if(INCLUSIONS[src] == null) {
\r
2999 UnicodeSet incl = new UnicodeSet();
\r
3001 case UCharacterProperty.SRC_CHAR:
\r
3002 UCharacterProperty.getInstance().addPropertyStarts(incl);
\r
3004 case UCharacterProperty.SRC_PROPSVEC:
\r
3005 UCharacterProperty.getInstance().upropsvec_addPropertyStarts(incl);
\r
3007 case UCharacterProperty.SRC_CHAR_AND_PROPSVEC:
\r
3008 UCharacterProperty.getInstance().addPropertyStarts(incl);
\r
3009 UCharacterProperty.getInstance().upropsvec_addPropertyStarts(incl);
\r
3011 case UCharacterProperty.SRC_HST:
\r
3012 UCharacterProperty.getInstance().uhst_addPropertyStarts(incl);
\r
3014 case UCharacterProperty.SRC_NORM:
\r
3015 NormalizerImpl.addPropertyStarts(incl);
\r
3017 case UCharacterProperty.SRC_CASE:
\r
3019 UCaseProps.getSingleton().addPropertyStarts(incl);
\r
3020 } catch(IOException e) {
\r
3021 throw new MissingResourceException(e.getMessage(),"","");
\r
3024 case UCharacterProperty.SRC_BIDI:
\r
3026 UBiDiProps.getSingleton().addPropertyStarts(incl);
\r
3027 } catch(IOException e) {
\r
3028 throw new MissingResourceException(e.getMessage(),"","");
\r
3032 throw new IllegalStateException("UnicodeSet.getInclusions(unknown src "+src+")");
\r
3034 INCLUSIONS[src] = incl;
\r
3036 return INCLUSIONS[src];
\r
3040 * Generic filter-based scanning code for UCD property UnicodeSets.
\r
3042 private UnicodeSet applyFilter(Filter filter, int src) {
\r
3043 // Walk through all Unicode characters, noting the start
\r
3044 // and end of each range for which filter.contain(c) is
\r
3045 // true. Add each range to a set.
\r
3047 // To improve performance, use the INCLUSIONS set, which
\r
3048 // encodes information about character ranges that are known
\r
3049 // to have identical properties, such as the CJK Ideographs
\r
3050 // from U+4E00 to U+9FA5. INCLUSIONS contains all characters
\r
3051 // except the first characters of such ranges.
\r
3053 // TODO Where possible, instead of scanning over code points,
\r
3054 // use internal property data to initialize UnicodeSets for
\r
3055 // those properties. Scanning code points is slow.
\r
3059 int startHasProperty = -1;
\r
3060 UnicodeSet inclusions = getInclusions(src);
\r
3061 int limitRange = inclusions.getRangeCount();
\r
3063 for (int j=0; j<limitRange; ++j) {
\r
3064 // get current range
\r
3065 int start = inclusions.getRangeStart(j);
\r
3066 int end = inclusions.getRangeEnd(j);
\r
3068 // for all the code points in the range, process
\r
3069 for (int ch = start; ch <= end; ++ch) {
\r
3070 // only add to the unicodeset on inflection points --
\r
3071 // where the hasProperty value changes to false
\r
3072 if (filter.contains(ch)) {
\r
3073 if (startHasProperty < 0) {
\r
3074 startHasProperty = ch;
\r
3076 } else if (startHasProperty >= 0) {
\r
3077 add_unchecked(startHasProperty, ch-1);
\r
3078 startHasProperty = -1;
\r
3082 if (startHasProperty >= 0) {
\r
3083 add_unchecked(startHasProperty, 0x10FFFF);
\r
3091 * Remove leading and trailing rule white space and compress
\r
3092 * internal rule white space to a single space character.
\r
3094 * @see UCharacterProperty#isRuleWhiteSpace
\r
3096 private static String mungeCharName(String source) {
\r
3097 StringBuffer buf = new StringBuffer();
\r
3098 for (int i=0; i<source.length(); ) {
\r
3099 int ch = UTF16.charAt(source, i);
\r
3100 i += UTF16.getCharCount(ch);
\r
3101 if (UCharacterProperty.isRuleWhiteSpace(ch)) {
\r
3102 if (buf.length() == 0 ||
\r
3103 buf.charAt(buf.length() - 1) == ' ') {
\r
3106 ch = ' '; // convert to ' '
\r
3108 UTF16.append(buf, ch);
\r
3110 if (buf.length() != 0 &&
\r
3111 buf.charAt(buf.length() - 1) == ' ') {
\r
3112 buf.setLength(buf.length() - 1);
\r
3114 return buf.toString();
\r
3117 //----------------------------------------------------------------
\r
3118 // Property set API
\r
3119 //----------------------------------------------------------------
\r
3122 * Modifies this set to contain those code points which have the
\r
3123 * given value for the given binary or enumerated property, as
\r
3124 * returned by UCharacter.getIntPropertyValue. Prior contents of
\r
3125 * this set are lost.
\r
3127 * @param prop a property in the range
\r
3128 * UProperty.BIN_START..UProperty.BIN_LIMIT-1 or
\r
3129 * UProperty.INT_START..UProperty.INT_LIMIT-1 or.
\r
3130 * UProperty.MASK_START..UProperty.MASK_LIMIT-1.
\r
3132 * @param value a value in the range
\r
3133 * UCharacter.getIntPropertyMinValue(prop)..
\r
3134 * UCharacter.getIntPropertyMaxValue(prop), with one exception.
\r
3135 * If prop is UProperty.GENERAL_CATEGORY_MASK, then value should not be
\r
3136 * a UCharacter.getType() result, but rather a mask value produced
\r
3137 * by logically ORing (1 << UCharacter.getType()) values together.
\r
3138 * This allows grouped categories such as [:L:] to be represented.
\r
3140 * @return a reference to this set
\r
3144 public UnicodeSet applyIntPropertyValue(int prop, int value) {
\r
3146 if (prop == UProperty.GENERAL_CATEGORY_MASK) {
\r
3147 applyFilter(new GeneralCategoryMaskFilter(value), UCharacterProperty.SRC_CHAR);
\r
3149 applyFilter(new IntPropertyFilter(prop, value), UCharacterProperty.getInstance().getSource(prop));
\r
3157 * Modifies this set to contain those code points which have the
\r
3158 * given value for the given property. Prior contents of this
\r
3161 * @param propertyAlias a property alias, either short or long.
\r
3162 * The name is matched loosely. See PropertyAliases.txt for names
\r
3163 * and a description of loose matching. If the value string is
\r
3164 * empty, then this string is interpreted as either a
\r
3165 * General_Category value alias, a Script value alias, a binary
\r
3166 * property alias, or a special ID. Special IDs are matched
\r
3167 * loosely and correspond to the following sets:
\r
3169 * "ANY" = [\u0000-\U0010FFFF],
\r
3170 * "ASCII" = [\u0000-\u007F].
\r
3172 * @param valueAlias a value alias, either short or long. The
\r
3173 * name is matched loosely. See PropertyValueAliases.txt for
\r
3174 * names and a description of loose matching. In addition to
\r
3175 * aliases listed, numeric values and canonical combining classes
\r
3176 * may be expressed numerically, e.g., ("nv", "0.5") or ("ccc",
\r
3177 * "220"). The value string may also be empty.
\r
3179 * @return a reference to this set
\r
3183 public UnicodeSet applyPropertyAlias(String propertyAlias, String valueAlias) {
\r
3184 return applyPropertyAlias(propertyAlias, valueAlias, null);
\r
3188 * Modifies this set to contain those code points which have the
\r
3189 * given value for the given property. Prior contents of this
\r
3191 * @param propertyAlias
\r
3192 * @param valueAlias
\r
3193 * @param symbols if not null, then symbols are first called to see if a property
\r
3194 * is available. If true, then everything else is skipped.
\r
3195 * @return this set
\r
3198 public UnicodeSet applyPropertyAlias(String propertyAlias,
\r
3199 String valueAlias, SymbolTable symbols) {
\r
3203 boolean mustNotBeEmpty = false, invert = false;
\r
3205 if (symbols != null
\r
3206 && (symbols instanceof XSymbolTable)
\r
3207 && ((XSymbolTable)symbols).applyPropertyAlias(propertyAlias, valueAlias, this)) {
\r
3211 if (valueAlias.length() > 0) {
\r
3212 p = UCharacter.getPropertyEnum(propertyAlias);
\r
3214 // Treat gc as gcm
\r
3215 if (p == UProperty.GENERAL_CATEGORY) {
\r
3216 p = UProperty.GENERAL_CATEGORY_MASK;
\r
3219 if ((p >= UProperty.BINARY_START && p < UProperty.BINARY_LIMIT) ||
\r
3220 (p >= UProperty.INT_START && p < UProperty.INT_LIMIT) ||
\r
3221 (p >= UProperty.MASK_START && p < UProperty.MASK_LIMIT)) {
\r
3223 v = UCharacter.getPropertyValueEnum(p, valueAlias);
\r
3224 } catch (IllegalArgumentException e) {
\r
3225 // Handle numeric CCC
\r
3226 if (p == UProperty.CANONICAL_COMBINING_CLASS ||
\r
3227 p == UProperty.LEAD_CANONICAL_COMBINING_CLASS ||
\r
3228 p == UProperty.TRAIL_CANONICAL_COMBINING_CLASS) {
\r
3229 v = Integer.parseInt(Utility.deleteRuleWhiteSpace(valueAlias));
\r
3230 // If the resultant set is empty then the numeric value
\r
3232 //mustNotBeEmpty = true;
\r
3233 // old code was wrong; anything between 0 and 255 is valid even if unused.
\r
3234 if (v < 0 || v > 255) throw e;
\r
3244 case UProperty.NUMERIC_VALUE:
\r
3246 double value = Double.parseDouble(Utility.deleteRuleWhiteSpace(valueAlias));
\r
3247 applyFilter(new NumericValueFilter(value), UCharacterProperty.SRC_CHAR);
\r
3250 case UProperty.NAME:
\r
3251 case UProperty.UNICODE_1_NAME:
\r
3253 // Must munge name, since
\r
3254 // UCharacter.charFromName() does not do
\r
3255 // 'loose' matching.
\r
3256 String buf = mungeCharName(valueAlias);
\r
3258 (p == UProperty.NAME) ?
\r
3259 UCharacter.getCharFromExtendedName(buf) :
\r
3260 UCharacter.getCharFromName1_0(buf);
\r
3262 throw new IllegalArgumentException("Invalid character name");
\r
3265 add_unchecked(ch);
\r
3268 case UProperty.AGE:
\r
3270 // Must munge name, since
\r
3271 // VersionInfo.getInstance() does not do
\r
3272 // 'loose' matching.
\r
3273 VersionInfo version = VersionInfo.getInstance(mungeCharName(valueAlias));
\r
3274 applyFilter(new VersionFilter(version), UCharacterProperty.SRC_PROPSVEC);
\r
3279 // p is a non-binary, non-enumerated property that we
\r
3280 // don't support (yet).
\r
3281 throw new IllegalArgumentException("Unsupported property");
\r
3286 // valueAlias is empty. Interpret as General Category, Script,
\r
3287 // Binary property, or ANY or ASCII. Upon success, p and v will
\r
3290 p = UProperty.GENERAL_CATEGORY_MASK;
\r
3291 v = UCharacter.getPropertyValueEnum(p, propertyAlias);
\r
3292 } catch (IllegalArgumentException e) {
\r
3294 p = UProperty.SCRIPT;
\r
3295 v = UCharacter.getPropertyValueEnum(p, propertyAlias);
\r
3296 } catch (IllegalArgumentException e2) {
\r
3298 p = UCharacter.getPropertyEnum(propertyAlias);
\r
3299 } catch (IllegalArgumentException e3) {
\r
3302 if (p >= UProperty.BINARY_START && p < UProperty.BINARY_LIMIT) {
\r
3304 } else if (p == -1) {
\r
3305 if (0 == UPropertyAliases.compare(ANY_ID, propertyAlias)) {
\r
3306 set(MIN_VALUE, MAX_VALUE);
\r
3308 } else if (0 == UPropertyAliases.compare(ASCII_ID, propertyAlias)) {
\r
3311 } else if (0 == UPropertyAliases.compare(ASSIGNED, propertyAlias)) {
\r
3312 // [:Assigned:]=[:^Cn:]
\r
3313 p = UProperty.GENERAL_CATEGORY_MASK;
\r
3314 v = (1<<UCharacter.UNASSIGNED);
\r
3317 // Property name was never matched.
\r
3318 throw new IllegalArgumentException("Invalid property alias: " + propertyAlias + "=" + valueAlias);
\r
3321 // Valid propery name, but it isn't binary, so the value
\r
3322 // must be supplied.
\r
3323 throw new IllegalArgumentException("Missing property value");
\r
3329 applyIntPropertyValue(p, v);
\r
3334 if (mustNotBeEmpty && isEmpty()) {
\r
3335 // mustNotBeEmpty is set to true if an empty set indicates
\r
3337 throw new IllegalArgumentException("Invalid property value");
\r
3343 //----------------------------------------------------------------
\r
3344 // Property set patterns
\r
3345 //----------------------------------------------------------------
\r
3348 * Return true if the given position, in the given pattern, appears
\r
3349 * to be the start of a property set pattern.
\r
3351 private static boolean resemblesPropertyPattern(String pattern, int pos) {
\r
3352 // Patterns are at least 5 characters long
\r
3353 if ((pos+5) > pattern.length()) {
\r
3357 // Look for an opening [:, [:^, \p, or \P
\r
3358 return pattern.regionMatches(pos, "[:", 0, 2) ||
\r
3359 pattern.regionMatches(true, pos, "\\p", 0, 2) ||
\r
3360 pattern.regionMatches(pos, "\\N", 0, 2);
\r
3364 * Return true if the given iterator appears to point at a
\r
3365 * property pattern. Regardless of the result, return with the
\r
3366 * iterator unchanged.
\r
3367 * @param chars iterator over the pattern characters. Upon return
\r
3368 * it will be unchanged.
\r
3369 * @param iterOpts RuleCharacterIterator options
\r
3371 private static boolean resemblesPropertyPattern(RuleCharacterIterator chars,
\r
3373 boolean result = false;
\r
3374 iterOpts &= ~RuleCharacterIterator.PARSE_ESCAPES;
\r
3375 Object pos = chars.getPos(null);
\r
3376 int c = chars.next(iterOpts);
\r
3377 if (c == '[' || c == '\\') {
\r
3378 int d = chars.next(iterOpts & ~RuleCharacterIterator.SKIP_WHITESPACE);
\r
3379 result = (c == '[') ? (d == ':') :
\r
3380 (d == 'N' || d == 'p' || d == 'P');
\r
3382 chars.setPos(pos);
\r
3387 * Parse the given property pattern at the given parse position.
\r
3388 * @param symbols TODO
\r
3390 private UnicodeSet applyPropertyPattern(String pattern, ParsePosition ppos, SymbolTable symbols) {
\r
3391 int pos = ppos.getIndex();
\r
3393 // On entry, ppos should point to one of the following locations:
\r
3395 // Minimum length is 5 characters, e.g. \p{L}
\r
3396 if ((pos+5) > pattern.length()) {
\r
3400 boolean posix = false; // true for [:pat:], false for \p{pat} \P{pat} \N{pat}
\r
3401 boolean isName = false; // true for \N{pat}, o/w false
\r
3402 boolean invert = false;
\r
3404 // Look for an opening [:, [:^, \p, or \P
\r
3405 if (pattern.regionMatches(pos, "[:", 0, 2)) {
\r
3407 pos = Utility.skipWhitespace(pattern, pos+2);
\r
3408 if (pos < pattern.length() && pattern.charAt(pos) == '^') {
\r
3412 } else if (pattern.regionMatches(true, pos, "\\p", 0, 2) ||
\r
3413 pattern.regionMatches(pos, "\\N", 0, 2)) {
\r
3414 char c = pattern.charAt(pos+1);
\r
3415 invert = (c == 'P');
\r
3416 isName = (c == 'N');
\r
3417 pos = Utility.skipWhitespace(pattern, pos+2);
\r
3418 if (pos == pattern.length() || pattern.charAt(pos++) != '{') {
\r
3419 // Syntax error; "\p" or "\P" not followed by "{"
\r
3423 // Open delimiter not seen
\r
3427 // Look for the matching close delimiter, either :] or }
\r
3428 int close = pattern.indexOf(posix ? ":]" : "}", pos);
\r
3430 // Syntax error; close delimiter missing
\r
3434 // Look for an '=' sign. If this is present, we will parse a
\r
3435 // medium \p{gc=Cf} or long \p{GeneralCategory=Format}
\r
3437 int equals = pattern.indexOf('=', pos);
\r
3438 String propName, valueName;
\r
3439 if (equals >= 0 && equals < close && !isName) {
\r
3440 // Equals seen; parse medium/long pattern
\r
3441 propName = pattern.substring(pos, equals);
\r
3442 valueName = pattern.substring(equals+1, close);
\r
3446 // Handle case where no '=' is seen, and \N{}
\r
3447 propName = pattern.substring(pos, close);
\r
3450 // Handle \N{name}
\r
3452 // This is a little inefficient since it means we have to
\r
3453 // parse "na" back to UProperty.NAME even though we already
\r
3454 // know it's UProperty.NAME. If we refactor the API to
\r
3455 // support args of (int, String) then we can remove
\r
3456 // "na" and make this a little more efficient.
\r
3457 valueName = propName;
\r
3462 applyPropertyAlias(propName, valueName, symbols);
\r
3468 // Move to the limit position after the close delimiter
\r
3469 ppos.setIndex(close + (posix ? 2 : 1));
\r
3475 * Parse a property pattern.
\r
3476 * @param chars iterator over the pattern characters. Upon return
\r
3477 * it will be advanced to the first character after the parsed
\r
3478 * pattern, or the end of the iteration if all characters are
\r
3480 * @param rebuiltPat the pattern that was parsed, rebuilt or
\r
3481 * copied from the input pattern, as appropriate.
\r
3482 * @param symbols TODO
\r
3484 private void applyPropertyPattern(RuleCharacterIterator chars,
\r
3485 StringBuffer rebuiltPat, SymbolTable symbols) {
\r
3486 String patStr = chars.lookahead();
\r
3487 ParsePosition pos = new ParsePosition(0);
\r
3488 applyPropertyPattern(patStr, pos, symbols);
\r
3489 if (pos.getIndex() == 0) {
\r
3490 syntaxError(chars, "Invalid property pattern");
\r
3492 chars.jumpahead(pos.getIndex());
\r
3493 rebuiltPat.append(patStr.substring(0, pos.getIndex()));
\r
3496 //----------------------------------------------------------------
\r
3497 // Case folding API
\r
3498 //----------------------------------------------------------------
\r
3501 * Bitmask for constructor and applyPattern() indicating that
\r
3502 * white space should be ignored. If set, ignore characters for
\r
3503 * which UCharacterProperty.isRuleWhiteSpace() returns true,
\r
3504 * unless they are quoted or escaped. This may be ORed together
\r
3505 * with other selectors.
\r
3508 public static final int IGNORE_SPACE = 1;
\r
3511 * Bitmask for constructor, applyPattern(), and closeOver()
\r
3512 * indicating letter case. This may be ORed together with other
\r
3515 * Enable case insensitive matching. E.g., "[ab]" with this flag
\r
3516 * will match 'a', 'A', 'b', and 'B'. "[^ab]" with this flag will
\r
3517 * match all except 'a', 'A', 'b', and 'B'. This performs a full
\r
3518 * closure over case mappings, e.g. U+017F for s.
\r
3520 * The resulting set is a superset of the input for the code points but
\r
3521 * not for the strings.
\r
3522 * It performs a case mapping closure of the code points and adds
\r
3523 * full case folding strings for the code points, and reduces strings of
\r
3524 * the original set to their full case folding equivalents.
\r
3526 * This is designed for case-insensitive matches, for example
\r
3527 * in regular expressions. The full code point case closure allows checking of
\r
3528 * an input character directly against the closure set.
\r
3529 * Strings are matched by comparing the case-folded form from the closure
\r
3530 * set with an incremental case folding of the string in question.
\r
3532 * The closure set will also contain single code points if the original
\r
3533 * set contained case-equivalent strings (like U+00DF for "ss" or "Ss" etc.).
\r
3534 * This is not necessary (that is, redundant) for the above matching method
\r
3535 * but results in the same closure sets regardless of whether the original
\r
3536 * set contained the code point or a string.
\r
3539 public static final int CASE = 2;
\r
3542 * Alias for UnicodeSet.CASE, for ease of porting from C++ where ICU4C
\r
3543 * also has both USET_CASE and USET_CASE_INSENSITIVE (see uset.h).
\r
3547 public static final int CASE_INSENSITIVE = 2;
\r
3550 * Bitmask for constructor, applyPattern(), and closeOver()
\r
3551 * indicating letter case. This may be ORed together with other
\r
3554 * Enable case insensitive matching. E.g., "[ab]" with this flag
\r
3555 * will match 'a', 'A', 'b', and 'B'. "[^ab]" with this flag will
\r
3556 * match all except 'a', 'A', 'b', and 'B'. This adds the lower-,
\r
3557 * title-, and uppercase mappings as well as the case folding
\r
3558 * of each existing element in the set.
\r
3561 public static final int ADD_CASE_MAPPINGS = 4;
\r
3563 // add the result of a full case mapping to the set
\r
3564 // use str as a temporary string to avoid constructing one
\r
3565 private static final void addCaseMapping(UnicodeSet set, int result, StringBuffer full) {
\r
3567 if(result > UCaseProps.MAX_STRING_LENGTH) {
\r
3568 // add a single-code point case mapping
\r
3571 // add a string case mapping from full with length result
\r
3572 set.add(full.toString());
\r
3573 full.setLength(0);
\r
3576 // result < 0: the code point mapped to itself, no need to add it
\r
3581 * Close this set over the given attribute. For the attribute
\r
3582 * CASE, the result is to modify this set so that:
\r
3584 * 1. For each character or string 'a' in this set, all strings
\r
3585 * 'b' such that foldCase(a) == foldCase(b) are added to this set.
\r
3586 * (For most 'a' that are single characters, 'b' will have
\r
3587 * b.length() == 1.)
\r
3589 * 2. For each string 'e' in the resulting set, if e !=
\r
3590 * foldCase(e), 'e' will be removed.
\r
3592 * Example: [aq\u00DF{Bc}{bC}{Fi}] => [aAqQ\u00DF\uFB01{ss}{bc}{fi}]
\r
3594 * (Here foldCase(x) refers to the operation
\r
3595 * UCharacter.foldCase(x, true), and a == b actually denotes
\r
3596 * a.equals(b), not pointer comparison.)
\r
3598 * @param attribute bitmask for attributes to close over.
\r
3599 * Currently only the CASE bit is supported. Any undefined bits
\r
3601 * @return a reference to this set.
\r
3604 public UnicodeSet closeOver(int attribute) {
\r
3606 if ((attribute & (CASE | ADD_CASE_MAPPINGS)) != 0) {
\r
3609 csp = UCaseProps.getSingleton();
\r
3610 } catch(IOException e) {
\r
3613 UnicodeSet foldSet = new UnicodeSet(this);
\r
3614 ULocale root = ULocale.ROOT;
\r
3616 // start with input set to guarantee inclusion
\r
3617 // CASE: remove strings because the strings will actually be reduced (folded);
\r
3618 // therefore, start with no strings and add only those needed
\r
3619 if((attribute & CASE) != 0) {
\r
3620 foldSet.strings.clear();
\r
3623 int n = getRangeCount();
\r
3625 StringBuffer full = new StringBuffer();
\r
3626 int locCache[] = new int[1];
\r
3628 for (int i=0; i<n; ++i) {
\r
3629 int start = getRangeStart(i);
\r
3630 int end = getRangeEnd(i);
\r
3632 if((attribute & CASE) != 0) {
\r
3633 // full case closure
\r
3634 for (int cp=start; cp<=end; ++cp) {
\r
3635 csp.addCaseClosure(cp, foldSet);
\r
3638 // add case mappings
\r
3639 // (does not add long s for regular s, or Kelvin for k, for example)
\r
3640 for (int cp=start; cp<=end; ++cp) {
\r
3641 result = csp.toFullLower(cp, null, full, root, locCache);
\r
3642 addCaseMapping(foldSet, result, full);
\r
3644 result = csp.toFullTitle(cp, null, full, root, locCache);
\r
3645 addCaseMapping(foldSet, result, full);
\r
3647 result = csp.toFullUpper(cp, null, full, root, locCache);
\r
3648 addCaseMapping(foldSet, result, full);
\r
3650 result = csp.toFullFolding(cp, full, 0);
\r
3651 addCaseMapping(foldSet, result, full);
\r
3655 if (!strings.isEmpty()) {
\r
3657 if ((attribute & CASE) != 0) {
\r
3658 Iterator it = strings.iterator();
\r
3659 while (it.hasNext()) {
\r
3660 str = UCharacter.foldCase((String)it.next(), 0);
\r
3661 if(!csp.addStringCaseClosure(str, foldSet)) {
\r
3662 foldSet.add(str); // does not map to code points: add the folded string itself
\r
3666 BreakIterator bi = BreakIterator.getWordInstance(root);
\r
3667 Iterator it = strings.iterator();
\r
3668 while (it.hasNext()) {
\r
3669 str = (String)it.next();
\r
3670 foldSet.add(UCharacter.toLowerCase(root, str));
\r
3671 foldSet.add(UCharacter.toTitleCase(root, str, bi));
\r
3672 foldSet.add(UCharacter.toUpperCase(root, str));
\r
3673 foldSet.add(UCharacter.foldCase(str, 0));
\r
3683 * Internal class for customizing UnicodeSet parsing of properties.
\r
3684 * TODO: extend to allow customizing of codepoint ranges
\r
3686 * @provisional This API might change or be removed in a future release.
\r
3689 abstract public static class XSymbolTable implements SymbolTable {
\r
3691 * Default constructor
\r
3693 * @provisional This API might change or be removed in a future release.
\r
3695 public XSymbolTable(){}
\r
3697 * Supplies default implementation for SymbolTable (no action).
\r
3699 * @provisional This API might change or be removed in a future release.
\r
3701 public UnicodeMatcher lookupMatcher(int i) {
\r
3705 * Apply a new property alias. Is called when parsing [:xxx=yyy:]. Results are to put into result.
\r
3706 * @param propertyName the xxx in [:xxx=yyy:]
\r
3707 * @param propertyValue the yyy in [:xxx=yyy:]
\r
3708 * @param result where the result is placed
\r
3709 * @return true if handled
\r
3711 * @provisional This API might change or be removed in a future release.
\r
3713 public boolean applyPropertyAlias(String propertyName, String propertyValue, UnicodeSet result) {
\r
3717 * Supplies default implementation for SymbolTable (no action).
\r
3719 * @provisional This API might change or be removed in a future release.
\r
3721 public char[] lookup(String s) {
\r
3725 * Supplies default implementation for SymbolTable (no action).
\r
3727 * @provisional This API might change or be removed in a future release.
\r
3729 public String parseReference(String text, ParsePosition pos, int limit) {
\r
3734 private boolean frozen;
\r
3737 * Is this frozen, according to the Freezable interface?
\r
3741 public boolean isFrozen() {
\r
3746 * Freeze this class, according to the Freezable interface.
\r
3750 public Object freeze() {
\r
3756 * Clone a thawed version of this class, according to the Freezable interface.
\r
3760 public Object cloneAsThawed() {
\r
3761 UnicodeSet result = (UnicodeSet) clone();
\r
3762 result.frozen = false;
\r
3766 // internal function
\r
3767 private void checkFrozen() {
\r
3769 throw new UnsupportedOperationException("Attempt to modify frozen object");
\r