Path: blob/master/src/java.base/share/classes/java/text/RuleBasedCollator.java
41152 views
/*1* Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved27* (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved28*29* The original version of this source code and documentation is copyrighted30* and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These31* materials are provided under terms of a License Agreement between Taligent32* and Sun. This technology is protected by multiple US and International33* patents. This notice and attribution to Taligent may not be removed.34* Taligent is a registered trademark of Taligent, Inc.35*36*/3738package java.text;3940import java.text.Normalizer;41import java.util.Vector;42import java.util.Locale;4344/**45* The {@code RuleBasedCollator} class is a concrete subclass of46* {@code Collator} that provides a simple, data-driven, table47* collator. With this class you can create a customized table-based48* {@code Collator}. {@code RuleBasedCollator} maps49* characters to sort keys.50*51* <p>52* {@code RuleBasedCollator} has the following restrictions53* for efficiency (other subclasses may be used for more complex languages) :54* <ol>55* <li>If a special collation rule controlled by a <modifier> is56* specified it applies to the whole collator object.57* <li>All non-mentioned characters are at the end of the58* collation order.59* </ol>60*61* <p>62* The collation table is composed of a list of collation rules, where each63* rule is of one of three forms:64* <pre>65* <modifier>66* <relation> <text-argument>67* <reset> <text-argument>68* </pre>69* The definitions of the rule elements is as follows:70* <UL>71* <LI><strong>Text-Argument</strong>: A text-argument is any sequence of72* characters, excluding special characters (that is, common73* whitespace characters [0009-000D, 0020] and rule syntax characters74* [0021-002F, 003A-0040, 005B-0060, 007B-007E]). If those75* characters are desired, you can put them in single quotes76* (e.g. ampersand => '&'). Note that unquoted white space characters77* are ignored; e.g. {@code b c} is treated as {@code bc}.78* <LI><strong>Modifier</strong>: There are currently two modifiers that79* turn on special collation rules.80* <UL>81* <LI>'@' : Turns on backwards sorting of accents (secondary82* differences), as in French.83* <LI>'!' : Turns on Thai/Lao vowel-consonant swapping. If this84* rule is in force when a Thai vowel of the range85* \U0E40-\U0E44 precedes a Thai consonant of the range86* \U0E01-\U0E2E OR a Lao vowel of the range \U0EC0-\U0EC487* precedes a Lao consonant of the range \U0E81-\U0EAE then88* the vowel is placed after the consonant for collation89* purposes.90* </UL>91* <p>'@' : Indicates that accents are sorted backwards, as in French.92* <LI><strong>Relation</strong>: The relations are the following:93* <UL>94* <LI>'<' : Greater, as a letter difference (primary)95* <LI>';' : Greater, as an accent difference (secondary)96* <LI>',' : Greater, as a case difference (tertiary)97* <LI>'=' : Equal98* </UL>99* <LI><strong>Reset</strong>: There is a single reset100* which is used primarily for contractions and expansions, but which101* can also be used to add a modification at the end of a set of rules.102* <p>'&' : Indicates that the next rule follows the position to where103* the reset text-argument would be sorted.104* </UL>105*106* <p>107* This sounds more complicated than it is in practice. For example, the108* following are equivalent ways of expressing the same thing:109* <blockquote>110* <pre>111* a < b < c112* a < b & b < c113* a < c & a < b114* </pre>115* </blockquote>116* Notice that the order is important, as the subsequent item goes immediately117* after the text-argument. The following are not equivalent:118* <blockquote>119* <pre>120* a < b & a < c121* a < c & a < b122* </pre>123* </blockquote>124* Either the text-argument must already be present in the sequence, or some125* initial substring of the text-argument must be present. (e.g. "a < b & ae <126* e" is valid since "a" is present in the sequence before "ae" is reset). In127* this latter case, "ae" is not entered and treated as a single character;128* instead, "e" is sorted as if it were expanded to two characters: "a"129* followed by an "e". This difference appears in natural languages: in130* traditional Spanish "ch" is treated as though it contracts to a single131* character (expressed as "c < ch < d"), while in traditional German132* a-umlaut is treated as though it expanded to two characters133* (expressed as "a,A < b,B ... &ae;\u00e3&AE;\u00c3").134* [\u00e3 and \u00c3 are, of course, the escape sequences for a-umlaut.]135* <p>136* <strong>Ignorable Characters</strong>137* <p>138* For ignorable characters, the first rule must start with a relation (the139* examples we have used above are really fragments; "a < b" really should be140* "< a < b"). If, however, the first relation is not "<", then all the all141* text-arguments up to the first "<" are ignorable. For example, ", - < a < b"142* makes "-" an ignorable character, as we saw earlier in the word143* "black-birds". In the samples for different languages, you see that most144* accents are ignorable.145*146* <p><strong>Normalization and Accents</strong>147* <p>148* {@code RuleBasedCollator} automatically processes its rule table to149* include both pre-composed and combining-character versions of150* accented characters. Even if the provided rule string contains only151* base characters and separate combining accent characters, the pre-composed152* accented characters matching all canonical combinations of characters from153* the rule string will be entered in the table.154* <p>155* This allows you to use a RuleBasedCollator to compare accented strings156* even when the collator is set to NO_DECOMPOSITION. There are two caveats,157* however. First, if the strings to be collated contain combining158* sequences that may not be in canonical order, you should set the collator to159* CANONICAL_DECOMPOSITION or FULL_DECOMPOSITION to enable sorting of160* combining sequences. Second, if the strings contain characters with161* compatibility decompositions (such as full-width and half-width forms),162* you must use FULL_DECOMPOSITION, since the rule tables only include163* canonical mappings.164*165* <p><strong>Errors</strong>166* <p>167* The following are errors:168* <UL>169* <LI>A text-argument contains unquoted punctuation symbols170* (e.g. "a < b-c < d").171* <LI>A relation or reset character not followed by a text-argument172* (e.g. "a < ,b").173* <LI>A reset where the text-argument (or an initial substring of the174* text-argument) is not already in the sequence.175* (e.g. "a < b & e < f")176* </UL>177* If you produce one of these errors, a {@code RuleBasedCollator} throws178* a {@code ParseException}.179*180* <p><strong>Examples</strong>181* <p>Simple: "< a < b < c < d"182* <p>Norwegian: "< a, A < b, B < c, C < d, D < e, E < f, F183* < g, G < h, H < i, I < j, J < k, K < l, L184* < m, M < n, N < o, O < p, P < q, Q < r, R185* < s, S < t, T < u, U < v, V < w, W < x, X186* < y, Y < z, Z187* < \u00E6, \u00C6188* < \u00F8, \u00D8189* < \u00E5 = a\u030A, \u00C5 = A\u030A;190* aa, AA"191*192* <p>193* To create a {@code RuleBasedCollator} object with specialized194* rules tailored to your needs, you construct the {@code RuleBasedCollator}195* with the rules contained in a {@code String} object. For example:196* <blockquote>197* <pre>198* String simple = "< a< b< c< d";199* RuleBasedCollator mySimple = new RuleBasedCollator(simple);200* </pre>201* </blockquote>202* Or:203* <blockquote>204* <pre>205* String Norwegian = "< a, A < b, B < c, C < d, D < e, E < f, F < g, G < h, H < i, I" +206* "< j, J < k, K < l, L < m, M < n, N < o, O < p, P < q, Q < r, R" +207* "< s, S < t, T < u, U < v, V < w, W < x, X < y, Y < z, Z" +208* "< \u00E6, \u00C6" + // Latin letter ae & AE209* "< \u00F8, \u00D8" + // Latin letter o & O with stroke210* "< \u00E5 = a\u030A," + // Latin letter a with ring above211* " \u00C5 = A\u030A;" + // Latin letter A with ring above212* " aa, AA";213* RuleBasedCollator myNorwegian = new RuleBasedCollator(Norwegian);214* </pre>215* </blockquote>216*217* <p>218* A new collation rules string can be created by concatenating rules219* strings. For example, the rules returned by {@link #getRules()} could220* be concatenated to combine multiple {@code RuleBasedCollator}s.221*222* <p>223* The following example demonstrates how to change the order of224* non-spacing accents,225* <blockquote>226* <pre>227* // old rule228* String oldRules = "=\u0301;\u0300;\u0302;\u0308" // main accents229* + ";\u0327;\u0303;\u0304;\u0305" // main accents230* + ";\u0306;\u0307;\u0309;\u030A" // main accents231* + ";\u030B;\u030C;\u030D;\u030E" // main accents232* + ";\u030F;\u0310;\u0311;\u0312" // main accents233* + "< a , A ; ae, AE ; \u00e6 , \u00c6"234* + "< b , B < c, C < e, E & C < d, D";235* // change the order of accent characters236* String addOn = "& \u0300 ; \u0308 ; \u0302";237* RuleBasedCollator myCollator = new RuleBasedCollator(oldRules + addOn);238* </pre>239* </blockquote>240*241* @see Collator242* @see CollationElementIterator243* @author Helena Shih, Laura Werner, Richard Gillam244* @since 1.1245*/246public class RuleBasedCollator extends Collator{247// IMPLEMENTATION NOTES: The implementation of the collation algorithm is248// divided across three classes: RuleBasedCollator, RBCollationTables, and249// CollationElementIterator. RuleBasedCollator contains the collator's250// transient state and includes the code that uses the other classes to251// implement comparison and sort-key building. RuleBasedCollator also252// contains the logic to handle French secondary accent sorting.253// A RuleBasedCollator has two CollationElementIterators. State doesn't254// need to be preserved in these objects between calls to compare() or255// getCollationKey(), but the objects persist anyway to avoid wasting extra256// creation time. compare() and getCollationKey() are synchronized to ensure257// thread safety with this scheme. The CollationElementIterator is responsible258// for generating collation elements from strings and returning one element at259// a time (sometimes there's a one-to-many or many-to-one mapping between260// characters and collation elements-- this class handles that).261// CollationElementIterator depends on RBCollationTables, which contains the262// collator's static state. RBCollationTables contains the actual data263// tables specifying the collation order of characters for a particular locale264// or use. It also contains the base logic that CollationElementIterator265// uses to map from characters to collation elements. A single RBCollationTables266// object is shared among all RuleBasedCollators for the same locale, and267// thus by all the CollationElementIterators they create.268269/**270* RuleBasedCollator constructor. This takes the table rules and builds271* a collation table out of them. Please see RuleBasedCollator class272* description for more details on the collation rule syntax.273* @see java.util.Locale274* @param rules the collation rules to build the collation table from.275* @throws ParseException A format exception276* will be thrown if the build process of the rules fails. For277* example, build rule "a < ? < d" will cause the constructor to278* throw the ParseException because the '?' is not quoted.279*/280public RuleBasedCollator(String rules) throws ParseException {281this(rules, Collator.CANONICAL_DECOMPOSITION);282}283284/**285* RuleBasedCollator constructor. This takes the table rules and builds286* a collation table out of them. Please see RuleBasedCollator class287* description for more details on the collation rule syntax.288* @see java.util.Locale289* @param rules the collation rules to build the collation table from.290* @param decomp the decomposition strength used to build the291* collation table and to perform comparisons.292* @throws ParseException A format exception293* will be thrown if the build process of the rules fails. For294* example, build rule "a < ? < d" will cause the constructor to295* throw the ParseException because the '?' is not quoted.296*/297RuleBasedCollator(String rules, int decomp) throws ParseException {298setStrength(Collator.TERTIARY);299setDecomposition(decomp);300tables = new RBCollationTables(rules, decomp);301}302303/**304* "Copy constructor." Used in clone() for performance.305*/306private RuleBasedCollator(RuleBasedCollator that) {307setStrength(that.getStrength());308setDecomposition(that.getDecomposition());309tables = that.tables;310}311312/**313* Gets the table-based rules for the collation object.314* @return returns the collation rules that the table collation object315* was created from.316*/317public String getRules()318{319return tables.getRules();320}321322/**323* Returns a CollationElementIterator for the given String.324*325* @param source the string to be collated326* @return a {@code CollationElementIterator} object327* @see java.text.CollationElementIterator328*/329public CollationElementIterator getCollationElementIterator(String source) {330return new CollationElementIterator( source, this );331}332333/**334* Returns a CollationElementIterator for the given CharacterIterator.335*336* @param source the character iterator to be collated337* @return a {@code CollationElementIterator} object338* @see java.text.CollationElementIterator339* @since 1.2340*/341public CollationElementIterator getCollationElementIterator(342CharacterIterator source) {343return new CollationElementIterator( source, this );344}345346/**347* Compares the character data stored in two different strings based on the348* collation rules. Returns information about whether a string is less349* than, greater than or equal to another string in a language.350* This can be overridden in a subclass.351*352* @throws NullPointerException if {@code source} or {@code target} is null.353*/354public synchronized int compare(String source, String target)355{356if (source == null || target == null) {357throw new NullPointerException();358}359360// The basic algorithm here is that we use CollationElementIterators361// to step through both the source and target strings. We compare each362// collation element in the source string against the corresponding one363// in the target, checking for differences.364//365// If a difference is found, we set <result> to LESS or GREATER to366// indicate whether the source string is less or greater than the target.367//368// However, it's not that simple. If we find a tertiary difference369// (e.g. 'A' vs. 'a') near the beginning of a string, it can be370// overridden by a primary difference (e.g. "A" vs. "B") later in371// the string. For example, "AA" < "aB", even though 'A' > 'a'.372//373// To keep track of this, we use strengthResult to keep track of the374// strength of the most significant difference that has been found375// so far. When we find a difference whose strength is greater than376// strengthResult, it overrides the last difference (if any) that377// was found.378379int result = Collator.EQUAL;380381if (sourceCursor == null) {382sourceCursor = getCollationElementIterator(source);383} else {384sourceCursor.setText(source);385}386if (targetCursor == null) {387targetCursor = getCollationElementIterator(target);388} else {389targetCursor.setText(target);390}391392int sOrder = 0, tOrder = 0;393394boolean initialCheckSecTer = getStrength() >= Collator.SECONDARY;395boolean checkSecTer = initialCheckSecTer;396boolean checkTertiary = getStrength() >= Collator.TERTIARY;397398boolean gets = true, gett = true;399400while(true) {401// Get the next collation element in each of the strings, unless402// we've been requested to skip it.403if (gets) sOrder = sourceCursor.next(); else gets = true;404if (gett) tOrder = targetCursor.next(); else gett = true;405406// If we've hit the end of one of the strings, jump out of the loop407if ((sOrder == CollationElementIterator.NULLORDER)||408(tOrder == CollationElementIterator.NULLORDER))409break;410411int pSOrder = CollationElementIterator.primaryOrder(sOrder);412int pTOrder = CollationElementIterator.primaryOrder(tOrder);413414// If there's no difference at this position, we can skip it415if (sOrder == tOrder) {416if (tables.isFrenchSec() && pSOrder != 0) {417if (!checkSecTer) {418// in french, a secondary difference more to the right is stronger,419// so accents have to be checked with each base element420checkSecTer = initialCheckSecTer;421// but tertiary differences are less important than the first422// secondary difference, so checking tertiary remains disabled423checkTertiary = false;424}425}426continue;427}428429// Compare primary differences first.430if ( pSOrder != pTOrder )431{432if (sOrder == 0) {433// The entire source element is ignorable.434// Skip to the next source element, but don't fetch another target element.435gett = false;436continue;437}438if (tOrder == 0) {439gets = false;440continue;441}442443// The source and target elements aren't ignorable, but it's still possible444// for the primary component of one of the elements to be ignorable....445446if (pSOrder == 0) // primary order in source is ignorable447{448// The source's primary is ignorable, but the target's isn't. We treat ignorables449// as a secondary difference, so remember that we found one.450if (checkSecTer) {451result = Collator.GREATER; // (strength is SECONDARY)452checkSecTer = false;453}454// Skip to the next source element, but don't fetch another target element.455gett = false;456}457else if (pTOrder == 0)458{459// record differences - see the comment above.460if (checkSecTer) {461result = Collator.LESS; // (strength is SECONDARY)462checkSecTer = false;463}464// Skip to the next source element, but don't fetch another target element.465gets = false;466} else {467// Neither of the orders is ignorable, and we already know that the primary468// orders are different because of the (pSOrder != pTOrder) test above.469// Record the difference and stop the comparison.470if (pSOrder < pTOrder) {471return Collator.LESS; // (strength is PRIMARY)472} else {473return Collator.GREATER; // (strength is PRIMARY)474}475}476} else { // else of if ( pSOrder != pTOrder )477// primary order is the same, but complete order is different. So there478// are no base elements at this point, only ignorables (Since the strings are479// normalized)480481if (checkSecTer) {482// a secondary or tertiary difference may still matter483short secSOrder = CollationElementIterator.secondaryOrder(sOrder);484short secTOrder = CollationElementIterator.secondaryOrder(tOrder);485if (secSOrder != secTOrder) {486// there is a secondary difference487result = (secSOrder < secTOrder) ? Collator.LESS : Collator.GREATER;488// (strength is SECONDARY)489checkSecTer = false;490// (even in french, only the first secondary difference within491// a base character matters)492} else {493if (checkTertiary) {494// a tertiary difference may still matter495short terSOrder = CollationElementIterator.tertiaryOrder(sOrder);496short terTOrder = CollationElementIterator.tertiaryOrder(tOrder);497if (terSOrder != terTOrder) {498// there is a tertiary difference499result = (terSOrder < terTOrder) ? Collator.LESS : Collator.GREATER;500// (strength is TERTIARY)501checkTertiary = false;502}503}504}505} // if (checkSecTer)506507} // if ( pSOrder != pTOrder )508} // while()509510if (sOrder != CollationElementIterator.NULLORDER) {511// (tOrder must be CollationElementIterator::NULLORDER,512// since this point is only reached when sOrder or tOrder is NULLORDER.)513// The source string has more elements, but the target string hasn't.514do {515if (CollationElementIterator.primaryOrder(sOrder) != 0) {516// We found an additional non-ignorable base character in the source string.517// This is a primary difference, so the source is greater518return Collator.GREATER; // (strength is PRIMARY)519}520else if (CollationElementIterator.secondaryOrder(sOrder) != 0) {521// Additional secondary elements mean the source string is greater522if (checkSecTer) {523result = Collator.GREATER; // (strength is SECONDARY)524checkSecTer = false;525}526}527} while ((sOrder = sourceCursor.next()) != CollationElementIterator.NULLORDER);528}529else if (tOrder != CollationElementIterator.NULLORDER) {530// The target string has more elements, but the source string hasn't.531do {532if (CollationElementIterator.primaryOrder(tOrder) != 0)533// We found an additional non-ignorable base character in the target string.534// This is a primary difference, so the source is less535return Collator.LESS; // (strength is PRIMARY)536else if (CollationElementIterator.secondaryOrder(tOrder) != 0) {537// Additional secondary elements in the target mean the source string is less538if (checkSecTer) {539result = Collator.LESS; // (strength is SECONDARY)540checkSecTer = false;541}542}543} while ((tOrder = targetCursor.next()) != CollationElementIterator.NULLORDER);544}545546// For IDENTICAL comparisons, we use a bitwise character comparison547// as a tiebreaker if all else is equal548if (result == 0 && getStrength() == IDENTICAL) {549int mode = getDecomposition();550Normalizer.Form form;551if (mode == CANONICAL_DECOMPOSITION) {552form = Normalizer.Form.NFD;553} else if (mode == FULL_DECOMPOSITION) {554form = Normalizer.Form.NFKD;555} else {556return source.compareTo(target);557}558559String sourceDecomposition = Normalizer.normalize(source, form);560String targetDecomposition = Normalizer.normalize(target, form);561return sourceDecomposition.compareTo(targetDecomposition);562}563return result;564}565566/**567* Transforms the string into a series of characters that can be compared568* with CollationKey.compareTo. This overrides java.text.Collator.getCollationKey.569* It can be overridden in a subclass.570*/571public synchronized CollationKey getCollationKey(String source)572{573//574// The basic algorithm here is to find all of the collation elements for each575// character in the source string, convert them to a char representation,576// and put them into the collation key. But it's trickier than that.577// Each collation element in a string has three components: primary (A vs B),578// secondary (A vs A-acute), and tertiary (A' vs a); and a primary difference579// at the end of a string takes precedence over a secondary or tertiary580// difference earlier in the string.581//582// To account for this, we put all of the primary orders at the beginning of the583// string, followed by the secondary and tertiary orders, separated by nulls.584//585// Here's a hypothetical example, with the collation element represented as586// a three-digit number, one digit for primary, one for secondary, etc.587//588// String: A a B \u00e9 <--(e-acute)589// Collation Elements: 101 100 201 510590//591// Collation Key: 1125<null>0001<null>1010592//593// To make things even trickier, secondary differences (accent marks) are compared594// starting at the *end* of the string in languages with French secondary ordering.595// But when comparing the accent marks on a single base character, they are compared596// from the beginning. To handle this, we reverse all of the accents that belong597// to each base character, then we reverse the entire string of secondary orderings598// at the end. Taking the same example above, a French collator might return599// this instead:600//601// Collation Key: 1125<null>1000<null>1010602//603if (source == null)604return null;605606if (primResult == null) {607primResult = new StringBuffer();608secResult = new StringBuffer();609terResult = new StringBuffer();610} else {611primResult.setLength(0);612secResult.setLength(0);613terResult.setLength(0);614}615int order = 0;616boolean compareSec = (getStrength() >= Collator.SECONDARY);617boolean compareTer = (getStrength() >= Collator.TERTIARY);618int secOrder = CollationElementIterator.NULLORDER;619int terOrder = CollationElementIterator.NULLORDER;620int preSecIgnore = 0;621622if (sourceCursor == null) {623sourceCursor = getCollationElementIterator(source);624} else {625sourceCursor.setText(source);626}627628// walk through each character629while ((order = sourceCursor.next()) !=630CollationElementIterator.NULLORDER)631{632secOrder = CollationElementIterator.secondaryOrder(order);633terOrder = CollationElementIterator.tertiaryOrder(order);634if (!CollationElementIterator.isIgnorable(order))635{636primResult.append((char) (CollationElementIterator.primaryOrder(order)637+ COLLATIONKEYOFFSET));638639if (compareSec) {640//641// accumulate all of the ignorable/secondary characters attached642// to a given base character643//644if (tables.isFrenchSec() && preSecIgnore < secResult.length()) {645//646// We're doing reversed secondary ordering and we've hit a base647// (non-ignorable) character. Reverse any secondary orderings648// that applied to the last base character. (see block comment above.)649//650RBCollationTables.reverse(secResult, preSecIgnore, secResult.length());651}652// Remember where we are in the secondary orderings - this is how far653// back to go if we need to reverse them later.654secResult.append((char)(secOrder+ COLLATIONKEYOFFSET));655preSecIgnore = secResult.length();656}657if (compareTer) {658terResult.append((char)(terOrder+ COLLATIONKEYOFFSET));659}660}661else662{663if (compareSec && secOrder != 0)664secResult.append((char)665(secOrder + tables.getMaxSecOrder() + COLLATIONKEYOFFSET));666if (compareTer && terOrder != 0)667terResult.append((char)668(terOrder + tables.getMaxTerOrder() + COLLATIONKEYOFFSET));669}670}671if (tables.isFrenchSec())672{673if (preSecIgnore < secResult.length()) {674// If we've accumulated any secondary characters after the last base character,675// reverse them.676RBCollationTables.reverse(secResult, preSecIgnore, secResult.length());677}678// And now reverse the entire secResult to get French secondary ordering.679RBCollationTables.reverse(secResult, 0, secResult.length());680}681primResult.append((char)0);682secResult.append((char)0);683secResult.append(terResult.toString());684primResult.append(secResult.toString());685686if (getStrength() == IDENTICAL) {687primResult.append((char)0);688int mode = getDecomposition();689if (mode == CANONICAL_DECOMPOSITION) {690primResult.append(Normalizer.normalize(source, Normalizer.Form.NFD));691} else if (mode == FULL_DECOMPOSITION) {692primResult.append(Normalizer.normalize(source, Normalizer.Form.NFKD));693} else {694primResult.append(source);695}696}697return new RuleBasedCollationKey(source, primResult.toString());698}699700/**701* Standard override; no change in semantics.702*/703public Object clone() {704// if we know we're not actually a subclass of RuleBasedCollator705// (this class really should have been made final), bypass706// Object.clone() and use our "copy constructor". This is faster.707if (getClass() == RuleBasedCollator.class) {708return new RuleBasedCollator(this);709}710else {711RuleBasedCollator result = (RuleBasedCollator) super.clone();712result.primResult = null;713result.secResult = null;714result.terResult = null;715result.sourceCursor = null;716result.targetCursor = null;717return result;718}719}720721/**722* Compares the equality of two collation objects.723* @param obj the table-based collation object to be compared with this.724* @return true if the current table-based collation object is the same725* as the table-based collation object obj; false otherwise.726*/727public boolean equals(Object obj) {728if (obj == null) return false;729if (!super.equals(obj)) return false; // super does class check730RuleBasedCollator other = (RuleBasedCollator) obj;731// all other non-transient information is also contained in rules.732return (getRules().equals(other.getRules()));733}734735/**736* Generates the hash code for the table-based collation object737*/738public int hashCode() {739return getRules().hashCode();740}741742/**743* Allows CollationElementIterator access to the tables object744*/745RBCollationTables getTables() {746return tables;747}748749// ==============================================================750// private751// ==============================================================752753static final int CHARINDEX = 0x70000000; // need look up in .commit()754static final int EXPANDCHARINDEX = 0x7E000000; // Expand index follows755static final int CONTRACTCHARINDEX = 0x7F000000; // contract indexes follow756static final int UNMAPPED = 0xFFFFFFFF;757758private static final int COLLATIONKEYOFFSET = 1;759760private RBCollationTables tables = null;761762// Internal objects that are cached across calls so that they don't have to763// be created/destroyed on every call to compare() and getCollationKey()764private StringBuffer primResult = null;765private StringBuffer secResult = null;766private StringBuffer terResult = null;767private CollationElementIterator sourceCursor = null;768private CollationElementIterator targetCursor = null;769}770771772