1/*
2 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26/*
27 * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
28 * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
29 *
30 *   The original version of this source code and documentation is copyrighted
31 * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
32 * materials are provided under terms of a License Agreement between Taligent
33 * and Sun. This technology is protected by multiple US and International
34 * patents. This notice and attribution to Taligent may not be removed.
35 *   Taligent is a registered trademark of Taligent, Inc.
36 *
37 */
38
39package java.text;
40
41import java.text.Normalizer;
42import java.util.Vector;
43import java.util.Locale;
44
45/**
46 * The <code>RuleBasedCollator</code> class is a concrete subclass of
47 * <code>Collator</code> that provides a simple, data-driven, table
48 * collator.  With this class you can create a customized table-based
49 * <code>Collator</code>.  <code>RuleBasedCollator</code> maps
50 * characters to sort keys.
51 *
52 * <p>
53 * <code>RuleBasedCollator</code> has the following restrictions
54 * for efficiency (other subclasses may be used for more complex languages) :
55 * <ol>
56 * <li>If a special collation rule controlled by a &lt;modifier&gt; is
57      specified it applies to the whole collator object.
58 * <li>All non-mentioned characters are at the end of the
59 *     collation order.
60 * </ol>
61 *
62 * <p>
63 * The collation table is composed of a list of collation rules, where each
64 * rule is of one of three forms:
65 * <pre>
66 *    &lt;modifier&gt;
67 *    &lt;relation&gt; &lt;text-argument&gt;
68 *    &lt;reset&gt; &lt;text-argument&gt;
69 * </pre>
70 * The definitions of the rule elements is as follows:
71 * <UL>
72 *    <LI><strong>Text-Argument</strong>: A text-argument is any sequence of
73 *        characters, excluding special characters (that is, common
74 *        whitespace characters [0009-000D, 0020] and rule syntax characters
75 *        [0021-002F, 003A-0040, 005B-0060, 007B-007E]). If those
76 *        characters are desired, you can put them in single quotes
77 *        (e.g. ampersand =&gt; '&amp;'). Note that unquoted white space characters
78 *        are ignored; e.g. <code>b c</code> is treated as <code>bc</code>.
79 *    <LI><strong>Modifier</strong>: There are currently two modifiers that
80 *        turn on special collation rules.
81 *        <UL>
82 *            <LI>'@' : Turns on backwards sorting of accents (secondary
83 *                      differences), as in French.
84 *            <LI>'!' : Turns on Thai/Lao vowel-consonant swapping.  If this
85 *                      rule is in force when a Thai vowel of the range
86 *                      &#92;U0E40-&#92;U0E44 precedes a Thai consonant of the range
87 *                      &#92;U0E01-&#92;U0E2E OR a Lao vowel of the range &#92;U0EC0-&#92;U0EC4
88 *                      precedes a Lao consonant of the range &#92;U0E81-&#92;U0EAE then
89 *                      the vowel is placed after the consonant for collation
90 *                      purposes.
91 *        </UL>
92 *        <p>'@' : Indicates that accents are sorted backwards, as in French.
93 *    <LI><strong>Relation</strong>: The relations are the following:
94 *        <UL>
95 *            <LI>'&lt;' : Greater, as a letter difference (primary)
96 *            <LI>';' : Greater, as an accent difference (secondary)
97 *            <LI>',' : Greater, as a case difference (tertiary)
98 *            <LI>'=' : Equal
99 *        </UL>
100 *    <LI><strong>Reset</strong>: There is a single reset
101 *        which is used primarily for contractions and expansions, but which
102 *        can also be used to add a modification at the end of a set of rules.
103 *        <p>'&amp;' : Indicates that the next rule follows the position to where
104 *            the reset text-argument would be sorted.
105 * </UL>
106 *
107 * <p>
108 * This sounds more complicated than it is in practice. For example, the
109 * following are equivalent ways of expressing the same thing:
110 * <blockquote>
111 * <pre>
112 * a &lt; b &lt; c
113 * a &lt; b &amp; b &lt; c
114 * a &lt; c &amp; a &lt; b
115 * </pre>
116 * </blockquote>
117 * Notice that the order is important, as the subsequent item goes immediately
118 * after the text-argument. The following are not equivalent:
119 * <blockquote>
120 * <pre>
121 * a &lt; b &amp; a &lt; c
122 * a &lt; c &amp; a &lt; b
123 * </pre>
124 * </blockquote>
125 * Either the text-argument must already be present in the sequence, or some
126 * initial substring of the text-argument must be present. (e.g. "a &lt; b &amp; ae &lt;
127 * e" is valid since "a" is present in the sequence before "ae" is reset). In
128 * this latter case, "ae" is not entered and treated as a single character;
129 * instead, "e" is sorted as if it were expanded to two characters: "a"
130 * followed by an "e". This difference appears in natural languages: in
131 * traditional Spanish "ch" is treated as though it contracts to a single
132 * character (expressed as "c &lt; ch &lt; d"), while in traditional German
133 * a-umlaut is treated as though it expanded to two characters
134 * (expressed as "a,A &lt; b,B ... &amp;ae;&#92;u00e3&amp;AE;&#92;u00c3").
135 * [&#92;u00e3 and &#92;u00c3 are, of course, the escape sequences for a-umlaut.]
136 * <p>
137 * <strong>Ignorable Characters</strong>
138 * <p>
139 * For ignorable characters, the first rule must start with a relation (the
140 * examples we have used above are really fragments; "a &lt; b" really should be
141 * "&lt; a &lt; b"). If, however, the first relation is not "&lt;", then all the all
142 * text-arguments up to the first "&lt;" are ignorable. For example, ", - &lt; a &lt; b"
143 * makes "-" an ignorable character, as we saw earlier in the word
144 * "black-birds". In the samples for different languages, you see that most
145 * accents are ignorable.
146 *
147 * <p><strong>Normalization and Accents</strong>
148 * <p>
149 * <code>RuleBasedCollator</code> automatically processes its rule table to
150 * include both pre-composed and combining-character versions of
151 * accented characters.  Even if the provided rule string contains only
152 * base characters and separate combining accent characters, the pre-composed
153 * accented characters matching all canonical combinations of characters from
154 * the rule string will be entered in the table.
155 * <p>
156 * This allows you to use a RuleBasedCollator to compare accented strings
157 * even when the collator is set to NO_DECOMPOSITION.  There are two caveats,
158 * however.  First, if the strings to be collated contain combining
159 * sequences that may not be in canonical order, you should set the collator to
160 * CANONICAL_DECOMPOSITION or FULL_DECOMPOSITION to enable sorting of
161 * combining sequences.  Second, if the strings contain characters with
162 * compatibility decompositions (such as full-width and half-width forms),
163 * you must use FULL_DECOMPOSITION, since the rule tables only include
164 * canonical mappings.
165 *
166 * <p><strong>Errors</strong>
167 * <p>
168 * The following are errors:
169 * <UL>
170 *     <LI>A text-argument contains unquoted punctuation symbols
171 *        (e.g. "a &lt; b-c &lt; d").
172 *     <LI>A relation or reset character not followed by a text-argument
173 *        (e.g. "a &lt; ,b").
174 *     <LI>A reset where the text-argument (or an initial substring of the
175 *         text-argument) is not already in the sequence.
176 *         (e.g. "a &lt; b &amp; e &lt; f")
177 * </UL>
178 * If you produce one of these errors, a <code>RuleBasedCollator</code> throws
179 * a <code>ParseException</code>.
180 *
181 * <p><strong>Examples</strong>
182 * <p>Simple:     "&lt; a &lt; b &lt; c &lt; d"
183 * <p>Norwegian:  "&lt; a, A &lt; b, B &lt; c, C &lt; d, D &lt; e, E &lt; f, F
184 *                 &lt; g, G &lt; h, H &lt; i, I &lt; j, J &lt; k, K &lt; l, L
185 *                 &lt; m, M &lt; n, N &lt; o, O &lt; p, P &lt; q, Q &lt; r, R
186 *                 &lt; s, S &lt; t, T &lt; u, U &lt; v, V &lt; w, W &lt; x, X
187 *                 &lt; y, Y &lt; z, Z
188 *                 &lt; &#92;u00E6, &#92;u00C6
189 *                 &lt; &#92;u00F8, &#92;u00D8
190 *                 &lt; &#92;u00E5 = a&#92;u030A, &#92;u00C5 = A&#92;u030A;
191 *                      aa, AA"
192 *
193 * <p>
194 * To create a <code>RuleBasedCollator</code> object with specialized
195 * rules tailored to your needs, you construct the <code>RuleBasedCollator</code>
196 * with the rules contained in a <code>String</code> object. For example:
197 * <blockquote>
198 * <pre>
199 * String simple = "&lt; a&lt; b&lt; c&lt; d";
200 * RuleBasedCollator mySimple = new RuleBasedCollator(simple);
201 * </pre>
202 * </blockquote>
203 * Or:
204 * <blockquote>
205 * <pre>
206 * String Norwegian = "&lt; a, A &lt; b, B &lt; c, C &lt; d, D &lt; e, E &lt; f, F &lt; g, G &lt; h, H &lt; i, I" +
207 *                    "&lt; j, J &lt; k, K &lt; l, L &lt; m, M &lt; n, N &lt; o, O &lt; p, P &lt; q, Q &lt; r, R" +
208 *                    "&lt; s, S &lt; t, T &lt; u, U &lt; v, V &lt; w, W &lt; x, X &lt; y, Y &lt; z, Z" +
209 *                    "&lt; &#92;u00E6, &#92;u00C6" +     // Latin letter ae &amp; AE
210 *                    "&lt; &#92;u00F8, &#92;u00D8" +     // Latin letter o &amp; O with stroke
211 *                    "&lt; &#92;u00E5 = a&#92;u030A," +  // Latin letter a with ring above
212 *                    "  &#92;u00C5 = A&#92;u030A;" +  // Latin letter A with ring above
213 *                    "  aa, AA";
214 * RuleBasedCollator myNorwegian = new RuleBasedCollator(Norwegian);
215 * </pre>
216 * </blockquote>
217 *
218 * <p>
219 * A new collation rules string can be created by concatenating rules
220 * strings. For example, the rules returned by {@link #getRules()} could
221 * be concatenated to combine multiple <code>RuleBasedCollator</code>s.
222 *
223 * <p>
224 * The following example demonstrates how to change the order of
225 * non-spacing accents,
226 * <blockquote>
227 * <pre>
228 * // old rule
229 * String oldRules = "=&#92;u0301;&#92;u0300;&#92;u0302;&#92;u0308"    // main accents
230 *                 + ";&#92;u0327;&#92;u0303;&#92;u0304;&#92;u0305"    // main accents
231 *                 + ";&#92;u0306;&#92;u0307;&#92;u0309;&#92;u030A"    // main accents
232 *                 + ";&#92;u030B;&#92;u030C;&#92;u030D;&#92;u030E"    // main accents
233 *                 + ";&#92;u030F;&#92;u0310;&#92;u0311;&#92;u0312"    // main accents
234 *                 + "&lt; a , A ; ae, AE ; &#92;u00e6 , &#92;u00c6"
235 *                 + "&lt; b , B &lt; c, C &lt; e, E &amp; C &lt; d, D";
236 * // change the order of accent characters
237 * String addOn = "&amp; &#92;u0300 ; &#92;u0308 ; &#92;u0302";
238 * RuleBasedCollator myCollator = new RuleBasedCollator(oldRules + addOn);
239 * </pre>
240 * </blockquote>
241 *
242 * @see        Collator
243 * @see        CollationElementIterator
244 * @author     Helena Shih, Laura Werner, Richard Gillam
245 * @since 1.1
246 */
247public class RuleBasedCollator extends Collator{
248    // IMPLEMENTATION NOTES:  The implementation of the collation algorithm is
249    // divided across three classes: RuleBasedCollator, RBCollationTables, and
250    // CollationElementIterator.  RuleBasedCollator contains the collator's
251    // transient state and includes the code that uses the other classes to
252    // implement comparison and sort-key building.  RuleBasedCollator also
253    // contains the logic to handle French secondary accent sorting.
254    // A RuleBasedCollator has two CollationElementIterators.  State doesn't
255    // need to be preserved in these objects between calls to compare() or
256    // getCollationKey(), but the objects persist anyway to avoid wasting extra
257    // creation time.  compare() and getCollationKey() are synchronized to ensure
258    // thread safety with this scheme.  The CollationElementIterator is responsible
259    // for generating collation elements from strings and returning one element at
260    // a time (sometimes there's a one-to-many or many-to-one mapping between
261    // characters and collation elements-- this class handles that).
262    // CollationElementIterator depends on RBCollationTables, which contains the
263    // collator's static state.  RBCollationTables contains the actual data
264    // tables specifying the collation order of characters for a particular locale
265    // or use.  It also contains the base logic that CollationElementIterator
266    // uses to map from characters to collation elements.  A single RBCollationTables
267    // object is shared among all RuleBasedCollators for the same locale, and
268    // thus by all the CollationElementIterators they create.
269
270    /**
271     * RuleBasedCollator constructor.  This takes the table rules and builds
272     * a collation table out of them.  Please see RuleBasedCollator class
273     * description for more details on the collation rule syntax.
274     * @see java.util.Locale
275     * @param rules the collation rules to build the collation table from.
276     * @exception ParseException A format exception
277     * will be thrown if the build process of the rules fails. For
278     * example, build rule "a &lt; ? &lt; d" will cause the constructor to
279     * throw the ParseException because the '?' is not quoted.
280     */
281    public RuleBasedCollator(String rules) throws ParseException {
282        this(rules, Collator.CANONICAL_DECOMPOSITION);
283    }
284
285    /**
286     * RuleBasedCollator constructor.  This takes the table rules and builds
287     * a collation table out of them.  Please see RuleBasedCollator class
288     * description for more details on the collation rule syntax.
289     * @see java.util.Locale
290     * @param rules the collation rules to build the collation table from.
291     * @param decomp the decomposition strength used to build the
292     * collation table and to perform comparisons.
293     * @exception ParseException A format exception
294     * will be thrown if the build process of the rules fails. For
295     * example, build rule "a < ? < d" will cause the constructor to
296     * throw the ParseException because the '?' is not quoted.
297     */
298    RuleBasedCollator(String rules, int decomp) throws ParseException {
299        setStrength(Collator.TERTIARY);
300        setDecomposition(decomp);
301        tables = new RBCollationTables(rules, decomp);
302    }
303
304    /**
305     * "Copy constructor."  Used in clone() for performance.
306     */
307    private RuleBasedCollator(RuleBasedCollator that) {
308        setStrength(that.getStrength());
309        setDecomposition(that.getDecomposition());
310        tables = that.tables;
311    }
312
313    /**
314     * Gets the table-based rules for the collation object.
315     * @return returns the collation rules that the table collation object
316     * was created from.
317     */
318    public String getRules()
319    {
320        return tables.getRules();
321    }
322
323    /**
324     * Returns a CollationElementIterator for the given String.
325     *
326     * @param source the string to be collated
327     * @return a {@code CollationElementIterator} object
328     * @see java.text.CollationElementIterator
329     */
330    public CollationElementIterator getCollationElementIterator(String source) {
331        return new CollationElementIterator( source, this );
332    }
333
334    /**
335     * Returns a CollationElementIterator for the given CharacterIterator.
336     *
337     * @param source the character iterator to be collated
338     * @return a {@code CollationElementIterator} object
339     * @see java.text.CollationElementIterator
340     * @since 1.2
341     */
342    public CollationElementIterator getCollationElementIterator(
343                                                CharacterIterator source) {
344        return new CollationElementIterator( source, this );
345    }
346
347    /**
348     * Compares the character data stored in two different strings based on the
349     * collation rules.  Returns information about whether a string is less
350     * than, greater than or equal to another string in a language.
351     * This can be overriden in a subclass.
352     *
353     * @exception NullPointerException if <code>source</code> or <code>target</code> is null.
354     */
355    public synchronized int compare(String source, String target)
356    {
357        if (source == null || target == null) {
358            throw new NullPointerException();
359        }
360
361        // The basic algorithm here is that we use CollationElementIterators
362        // to step through both the source and target strings.  We compare each
363        // collation element in the source string against the corresponding one
364        // in the target, checking for differences.
365        //
366        // If a difference is found, we set <result> to LESS or GREATER to
367        // indicate whether the source string is less or greater than the target.
368        //
369        // However, it's not that simple.  If we find a tertiary difference
370        // (e.g. 'A' vs. 'a') near the beginning of a string, it can be
371        // overridden by a primary difference (e.g. "A" vs. "B") later in
372        // the string.  For example, "AA" < "aB", even though 'A' > 'a'.
373        //
374        // To keep track of this, we use strengthResult to keep track of the
375        // strength of the most significant difference that has been found
376        // so far.  When we find a difference whose strength is greater than
377        // strengthResult, it overrides the last difference (if any) that
378        // was found.
379
380        int result = Collator.EQUAL;
381
382        if (sourceCursor == null) {
383            sourceCursor = getCollationElementIterator(source);
384        } else {
385            sourceCursor.setText(source);
386        }
387        if (targetCursor == null) {
388            targetCursor = getCollationElementIterator(target);
389        } else {
390            targetCursor.setText(target);
391        }
392
393        int sOrder = 0, tOrder = 0;
394
395        boolean initialCheckSecTer = getStrength() >= Collator.SECONDARY;
396        boolean checkSecTer = initialCheckSecTer;
397        boolean checkTertiary = getStrength() >= Collator.TERTIARY;
398
399        boolean gets = true, gett = true;
400
401        while(true) {
402            // Get the next collation element in each of the strings, unless
403            // we've been requested to skip it.
404            if (gets) sOrder = sourceCursor.next(); else gets = true;
405            if (gett) tOrder = targetCursor.next(); else gett = true;
406
407            // If we've hit the end of one of the strings, jump out of the loop
408            if ((sOrder == CollationElementIterator.NULLORDER)||
409                (tOrder == CollationElementIterator.NULLORDER))
410                break;
411
412            int pSOrder = CollationElementIterator.primaryOrder(sOrder);
413            int pTOrder = CollationElementIterator.primaryOrder(tOrder);
414
415            // If there's no difference at this position, we can skip it
416            if (sOrder == tOrder) {
417                if (tables.isFrenchSec() && pSOrder != 0) {
418                    if (!checkSecTer) {
419                        // in french, a secondary difference more to the right is stronger,
420                        // so accents have to be checked with each base element
421                        checkSecTer = initialCheckSecTer;
422                        // but tertiary differences are less important than the first
423                        // secondary difference, so checking tertiary remains disabled
424                        checkTertiary = false;
425                    }
426                }
427                continue;
428            }
429
430            // Compare primary differences first.
431            if ( pSOrder != pTOrder )
432            {
433                if (sOrder == 0) {
434                    // The entire source element is ignorable.
435                    // Skip to the next source element, but don't fetch another target element.
436                    gett = false;
437                    continue;
438                }
439                if (tOrder == 0) {
440                    gets = false;
441                    continue;
442                }
443
444                // The source and target elements aren't ignorable, but it's still possible
445                // for the primary component of one of the elements to be ignorable....
446
447                if (pSOrder == 0)  // primary order in source is ignorable
448                {
449                    // The source's primary is ignorable, but the target's isn't.  We treat ignorables
450                    // as a secondary difference, so remember that we found one.
451                    if (checkSecTer) {
452                        result = Collator.GREATER;  // (strength is SECONDARY)
453                        checkSecTer = false;
454                    }
455                    // Skip to the next source element, but don't fetch another target element.
456                    gett = false;
457                }
458                else if (pTOrder == 0)
459                {
460                    // record differences - see the comment above.
461                    if (checkSecTer) {
462                        result = Collator.LESS;  // (strength is SECONDARY)
463                        checkSecTer = false;
464                    }
465                    // Skip to the next source element, but don't fetch another target element.
466                    gets = false;
467                } else {
468                    // Neither of the orders is ignorable, and we already know that the primary
469                    // orders are different because of the (pSOrder != pTOrder) test above.
470                    // Record the difference and stop the comparison.
471                    if (pSOrder < pTOrder) {
472                        return Collator.LESS;  // (strength is PRIMARY)
473                    } else {
474                        return Collator.GREATER;  // (strength is PRIMARY)
475                    }
476                }
477            } else { // else of if ( pSOrder != pTOrder )
478                // primary order is the same, but complete order is different. So there
479                // are no base elements at this point, only ignorables (Since the strings are
480                // normalized)
481
482                if (checkSecTer) {
483                    // a secondary or tertiary difference may still matter
484                    short secSOrder = CollationElementIterator.secondaryOrder(sOrder);
485                    short secTOrder = CollationElementIterator.secondaryOrder(tOrder);
486                    if (secSOrder != secTOrder) {
487                        // there is a secondary difference
488                        result = (secSOrder < secTOrder) ? Collator.LESS : Collator.GREATER;
489                                                // (strength is SECONDARY)
490                        checkSecTer = false;
491                        // (even in french, only the first secondary difference within
492                        //  a base character matters)
493                    } else {
494                        if (checkTertiary) {
495                            // a tertiary difference may still matter
496                            short terSOrder = CollationElementIterator.tertiaryOrder(sOrder);
497                            short terTOrder = CollationElementIterator.tertiaryOrder(tOrder);
498                            if (terSOrder != terTOrder) {
499                                // there is a tertiary difference
500                                result = (terSOrder < terTOrder) ? Collator.LESS : Collator.GREATER;
501                                                // (strength is TERTIARY)
502                                checkTertiary = false;
503                            }
504                        }
505                    }
506                } // if (checkSecTer)
507
508            }  // if ( pSOrder != pTOrder )
509        } // while()
510
511        if (sOrder != CollationElementIterator.NULLORDER) {
512            // (tOrder must be CollationElementIterator::NULLORDER,
513            //  since this point is only reached when sOrder or tOrder is NULLORDER.)
514            // The source string has more elements, but the target string hasn't.
515            do {
516                if (CollationElementIterator.primaryOrder(sOrder) != 0) {
517                    // We found an additional non-ignorable base character in the source string.
518                    // This is a primary difference, so the source is greater
519                    return Collator.GREATER; // (strength is PRIMARY)
520                }
521                else if (CollationElementIterator.secondaryOrder(sOrder) != 0) {
522                    // Additional secondary elements mean the source string is greater
523                    if (checkSecTer) {
524                        result = Collator.GREATER;  // (strength is SECONDARY)
525                        checkSecTer = false;
526                    }
527                }
528            } while ((sOrder = sourceCursor.next()) != CollationElementIterator.NULLORDER);
529        }
530        else if (tOrder != CollationElementIterator.NULLORDER) {
531            // The target string has more elements, but the source string hasn't.
532            do {
533                if (CollationElementIterator.primaryOrder(tOrder) != 0)
534                    // We found an additional non-ignorable base character in the target string.
535                    // This is a primary difference, so the source is less
536                    return Collator.LESS; // (strength is PRIMARY)
537                else if (CollationElementIterator.secondaryOrder(tOrder) != 0) {
538                    // Additional secondary elements in the target mean the source string is less
539                    if (checkSecTer) {
540                        result = Collator.LESS;  // (strength is SECONDARY)
541                        checkSecTer = false;
542                    }
543                }
544            } while ((tOrder = targetCursor.next()) != CollationElementIterator.NULLORDER);
545        }
546
547        // For IDENTICAL comparisons, we use a bitwise character comparison
548        // as a tiebreaker if all else is equal
549        if (result == 0 && getStrength() == IDENTICAL) {
550            int mode = getDecomposition();
551            Normalizer.Form form;
552            if (mode == CANONICAL_DECOMPOSITION) {
553                form = Normalizer.Form.NFD;
554            } else if (mode == FULL_DECOMPOSITION) {
555                form = Normalizer.Form.NFKD;
556            } else {
557                return source.compareTo(target);
558            }
559
560            String sourceDecomposition = Normalizer.normalize(source, form);
561            String targetDecomposition = Normalizer.normalize(target, form);
562            return sourceDecomposition.compareTo(targetDecomposition);
563        }
564        return result;
565    }
566
567    /**
568     * Transforms the string into a series of characters that can be compared
569     * with CollationKey.compareTo. This overrides java.text.Collator.getCollationKey.
570     * It can be overriden in a subclass.
571     */
572    public synchronized CollationKey getCollationKey(String source)
573    {
574        //
575        // The basic algorithm here is to find all of the collation elements for each
576        // character in the source string, convert them to a char representation,
577        // and put them into the collation key.  But it's trickier than that.
578        // Each collation element in a string has three components: primary (A vs B),
579        // secondary (A vs A-acute), and tertiary (A' vs a); and a primary difference
580        // at the end of a string takes precedence over a secondary or tertiary
581        // difference earlier in the string.
582        //
583        // To account for this, we put all of the primary orders at the beginning of the
584        // string, followed by the secondary and tertiary orders, separated by nulls.
585        //
586        // Here's a hypothetical example, with the collation element represented as
587        // a three-digit number, one digit for primary, one for secondary, etc.
588        //
589        // String:              A     a     B   \u00e9 <--(e-acute)
590        // Collation Elements: 101   100   201  510
591        //
592        // Collation Key:      1125<null>0001<null>1010
593        //
594        // To make things even trickier, secondary differences (accent marks) are compared
595        // starting at the *end* of the string in languages with French secondary ordering.
596        // But when comparing the accent marks on a single base character, they are compared
597        // from the beginning.  To handle this, we reverse all of the accents that belong
598        // to each base character, then we reverse the entire string of secondary orderings
599        // at the end.  Taking the same example above, a French collator might return
600        // this instead:
601        //
602        // Collation Key:      1125<null>1000<null>1010
603        //
604        if (source == null)
605            return null;
606
607        if (primResult == null) {
608            primResult = new StringBuffer();
609            secResult = new StringBuffer();
610            terResult = new StringBuffer();
611        } else {
612            primResult.setLength(0);
613            secResult.setLength(0);
614            terResult.setLength(0);
615        }
616        int order = 0;
617        boolean compareSec = (getStrength() >= Collator.SECONDARY);
618        boolean compareTer = (getStrength() >= Collator.TERTIARY);
619        int secOrder = CollationElementIterator.NULLORDER;
620        int terOrder = CollationElementIterator.NULLORDER;
621        int preSecIgnore = 0;
622
623        if (sourceCursor == null) {
624            sourceCursor = getCollationElementIterator(source);
625        } else {
626            sourceCursor.setText(source);
627        }
628
629        // walk through each character
630        while ((order = sourceCursor.next()) !=
631               CollationElementIterator.NULLORDER)
632        {
633            secOrder = CollationElementIterator.secondaryOrder(order);
634            terOrder = CollationElementIterator.tertiaryOrder(order);
635            if (!CollationElementIterator.isIgnorable(order))
636            {
637                primResult.append((char) (CollationElementIterator.primaryOrder(order)
638                                    + COLLATIONKEYOFFSET));
639
640                if (compareSec) {
641                    //
642                    // accumulate all of the ignorable/secondary characters attached
643                    // to a given base character
644                    //
645                    if (tables.isFrenchSec() && preSecIgnore < secResult.length()) {
646                        //
647                        // We're doing reversed secondary ordering and we've hit a base
648                        // (non-ignorable) character.  Reverse any secondary orderings
649                        // that applied to the last base character.  (see block comment above.)
650                        //
651                        RBCollationTables.reverse(secResult, preSecIgnore, secResult.length());
652                    }
653                    // Remember where we are in the secondary orderings - this is how far
654                    // back to go if we need to reverse them later.
655                    secResult.append((char)(secOrder+ COLLATIONKEYOFFSET));
656                    preSecIgnore = secResult.length();
657                }
658                if (compareTer) {
659                    terResult.append((char)(terOrder+ COLLATIONKEYOFFSET));
660                }
661            }
662            else
663            {
664                if (compareSec && secOrder != 0)
665                    secResult.append((char)
666                        (secOrder + tables.getMaxSecOrder() + COLLATIONKEYOFFSET));
667                if (compareTer && terOrder != 0)
668                    terResult.append((char)
669                        (terOrder + tables.getMaxTerOrder() + COLLATIONKEYOFFSET));
670            }
671        }
672        if (tables.isFrenchSec())
673        {
674            if (preSecIgnore < secResult.length()) {
675                // If we've accumulated any secondary characters after the last base character,
676                // reverse them.
677                RBCollationTables.reverse(secResult, preSecIgnore, secResult.length());
678            }
679            // And now reverse the entire secResult to get French secondary ordering.
680            RBCollationTables.reverse(secResult, 0, secResult.length());
681        }
682        primResult.append((char)0);
683        secResult.append((char)0);
684        secResult.append(terResult.toString());
685        primResult.append(secResult.toString());
686
687        if (getStrength() == IDENTICAL) {
688            primResult.append((char)0);
689            int mode = getDecomposition();
690            if (mode == CANONICAL_DECOMPOSITION) {
691                primResult.append(Normalizer.normalize(source, Normalizer.Form.NFD));
692            } else if (mode == FULL_DECOMPOSITION) {
693                primResult.append(Normalizer.normalize(source, Normalizer.Form.NFKD));
694            } else {
695                primResult.append(source);
696            }
697        }
698        return new RuleBasedCollationKey(source, primResult.toString());
699    }
700
701    /**
702     * Standard override; no change in semantics.
703     */
704    public Object clone() {
705        // if we know we're not actually a subclass of RuleBasedCollator
706        // (this class really should have been made final), bypass
707        // Object.clone() and use our "copy constructor".  This is faster.
708        if (getClass() == RuleBasedCollator.class) {
709            return new RuleBasedCollator(this);
710        }
711        else {
712            RuleBasedCollator result = (RuleBasedCollator) super.clone();
713            result.primResult = null;
714            result.secResult = null;
715            result.terResult = null;
716            result.sourceCursor = null;
717            result.targetCursor = null;
718            return result;
719        }
720    }
721
722    /**
723     * Compares the equality of two collation objects.
724     * @param obj the table-based collation object to be compared with this.
725     * @return true if the current table-based collation object is the same
726     * as the table-based collation object obj; false otherwise.
727     */
728    public boolean equals(Object obj) {
729        if (obj == null) return false;
730        if (!super.equals(obj)) return false;  // super does class check
731        RuleBasedCollator other = (RuleBasedCollator) obj;
732        // all other non-transient information is also contained in rules.
733        return (getRules().equals(other.getRules()));
734    }
735
736    /**
737     * Generates the hash code for the table-based collation object
738     */
739    public int hashCode() {
740        return getRules().hashCode();
741    }
742
743    /**
744     * Allows CollationElementIterator access to the tables object
745     */
746    RBCollationTables getTables() {
747        return tables;
748    }
749
750    // ==============================================================
751    // private
752    // ==============================================================
753
754    static final int CHARINDEX = 0x70000000;  // need look up in .commit()
755    static final int EXPANDCHARINDEX = 0x7E000000; // Expand index follows
756    static final int CONTRACTCHARINDEX = 0x7F000000;  // contract indexes follow
757    static final int UNMAPPED = 0xFFFFFFFF;
758
759    private static final int COLLATIONKEYOFFSET = 1;
760
761    private RBCollationTables tables = null;
762
763    // Internal objects that are cached across calls so that they don't have to
764    // be created/destroyed on every call to compare() and getCollationKey()
765    private StringBuffer primResult = null;
766    private StringBuffer secResult = null;
767    private StringBuffer terResult = null;
768    private CollationElementIterator sourceCursor = null;
769    private CollationElementIterator targetCursor = null;
770}
771