Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-multiarch-jdk8u
Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/text/RuleBasedCollator.java
38829 views
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
39
package java.text;
40
41
import java.text.Normalizer;
42
import java.util.Vector;
43
import 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
*/
246
public class RuleBasedCollator extends Collator{
247
// IMPLEMENTATION NOTES: The implementation of the collation algorithm is
248
// divided across three classes: RuleBasedCollator, RBCollationTables, and
249
// CollationElementIterator. RuleBasedCollator contains the collator's
250
// transient state and includes the code that uses the other classes to
251
// implement comparison and sort-key building. RuleBasedCollator also
252
// contains the logic to handle French secondary accent sorting.
253
// A RuleBasedCollator has two CollationElementIterators. State doesn't
254
// need to be preserved in these objects between calls to compare() or
255
// getCollationKey(), but the objects persist anyway to avoid wasting extra
256
// creation time. compare() and getCollationKey() are synchronized to ensure
257
// thread safety with this scheme. The CollationElementIterator is responsible
258
// for generating collation elements from strings and returning one element at
259
// a time (sometimes there's a one-to-many or many-to-one mapping between
260
// characters and collation elements-- this class handles that).
261
// CollationElementIterator depends on RBCollationTables, which contains the
262
// collator's static state. RBCollationTables contains the actual data
263
// tables specifying the collation order of characters for a particular locale
264
// or use. It also contains the base logic that CollationElementIterator
265
// uses to map from characters to collation elements. A single RBCollationTables
266
// object is shared among all RuleBasedCollators for the same locale, and
267
// thus by all the CollationElementIterators they create.
268
269
/**
270
* RuleBasedCollator constructor. This takes the table rules and builds
271
* a collation table out of them. Please see RuleBasedCollator class
272
* description for more details on the collation rule syntax.
273
* @see java.util.Locale
274
* @param rules the collation rules to build the collation table from.
275
* @exception ParseException A format exception
276
* will be thrown if the build process of the rules fails. For
277
* example, build rule "a &lt; ? &lt; d" will cause the constructor to
278
* throw the ParseException because the '?' is not quoted.
279
*/
280
public RuleBasedCollator(String rules) throws ParseException {
281
this(rules, Collator.CANONICAL_DECOMPOSITION);
282
}
283
284
/**
285
* RuleBasedCollator constructor. This takes the table rules and builds
286
* a collation table out of them. Please see RuleBasedCollator class
287
* description for more details on the collation rule syntax.
288
* @see java.util.Locale
289
* @param rules the collation rules to build the collation table from.
290
* @param decomp the decomposition strength used to build the
291
* collation table and to perform comparisons.
292
* @exception ParseException A format exception
293
* will be thrown if the build process of the rules fails. For
294
* example, build rule "a < ? < d" will cause the constructor to
295
* throw the ParseException because the '?' is not quoted.
296
*/
297
RuleBasedCollator(String rules, int decomp) throws ParseException {
298
setStrength(Collator.TERTIARY);
299
setDecomposition(decomp);
300
tables = new RBCollationTables(rules, decomp);
301
}
302
303
/**
304
* "Copy constructor." Used in clone() for performance.
305
*/
306
private RuleBasedCollator(RuleBasedCollator that) {
307
setStrength(that.getStrength());
308
setDecomposition(that.getDecomposition());
309
tables = that.tables;
310
}
311
312
/**
313
* Gets the table-based rules for the collation object.
314
* @return returns the collation rules that the table collation object
315
* was created from.
316
*/
317
public String getRules()
318
{
319
return tables.getRules();
320
}
321
322
/**
323
* Returns a CollationElementIterator for the given String.
324
*
325
* @param source the string to be collated
326
* @return a {@code CollationElementIterator} object
327
* @see java.text.CollationElementIterator
328
*/
329
public CollationElementIterator getCollationElementIterator(String source) {
330
return new CollationElementIterator( source, this );
331
}
332
333
/**
334
* Returns a CollationElementIterator for the given CharacterIterator.
335
*
336
* @param source the character iterator to be collated
337
* @return a {@code CollationElementIterator} object
338
* @see java.text.CollationElementIterator
339
* @since 1.2
340
*/
341
public CollationElementIterator getCollationElementIterator(
342
CharacterIterator source) {
343
return new CollationElementIterator( source, this );
344
}
345
346
/**
347
* Compares the character data stored in two different strings based on the
348
* collation rules. Returns information about whether a string is less
349
* than, greater than or equal to another string in a language.
350
* This can be overriden in a subclass.
351
*
352
* @exception NullPointerException if <code>source</code> or <code>target</code> is null.
353
*/
354
public synchronized int compare(String source, String target)
355
{
356
if (source == null || target == null) {
357
throw new NullPointerException();
358
}
359
360
// The basic algorithm here is that we use CollationElementIterators
361
// to step through both the source and target strings. We compare each
362
// collation element in the source string against the corresponding one
363
// in the target, checking for differences.
364
//
365
// If a difference is found, we set <result> to LESS or GREATER to
366
// 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 difference
369
// (e.g. 'A' vs. 'a') near the beginning of a string, it can be
370
// overridden by a primary difference (e.g. "A" vs. "B") later in
371
// the string. For example, "AA" < "aB", even though 'A' > 'a'.
372
//
373
// To keep track of this, we use strengthResult to keep track of the
374
// strength of the most significant difference that has been found
375
// so far. When we find a difference whose strength is greater than
376
// strengthResult, it overrides the last difference (if any) that
377
// was found.
378
379
int result = Collator.EQUAL;
380
381
if (sourceCursor == null) {
382
sourceCursor = getCollationElementIterator(source);
383
} else {
384
sourceCursor.setText(source);
385
}
386
if (targetCursor == null) {
387
targetCursor = getCollationElementIterator(target);
388
} else {
389
targetCursor.setText(target);
390
}
391
392
int sOrder = 0, tOrder = 0;
393
394
boolean initialCheckSecTer = getStrength() >= Collator.SECONDARY;
395
boolean checkSecTer = initialCheckSecTer;
396
boolean checkTertiary = getStrength() >= Collator.TERTIARY;
397
398
boolean gets = true, gett = true;
399
400
while(true) {
401
// Get the next collation element in each of the strings, unless
402
// we've been requested to skip it.
403
if (gets) sOrder = sourceCursor.next(); else gets = true;
404
if (gett) tOrder = targetCursor.next(); else gett = true;
405
406
// If we've hit the end of one of the strings, jump out of the loop
407
if ((sOrder == CollationElementIterator.NULLORDER)||
408
(tOrder == CollationElementIterator.NULLORDER))
409
break;
410
411
int pSOrder = CollationElementIterator.primaryOrder(sOrder);
412
int pTOrder = CollationElementIterator.primaryOrder(tOrder);
413
414
// If there's no difference at this position, we can skip it
415
if (sOrder == tOrder) {
416
if (tables.isFrenchSec() && pSOrder != 0) {
417
if (!checkSecTer) {
418
// in french, a secondary difference more to the right is stronger,
419
// so accents have to be checked with each base element
420
checkSecTer = initialCheckSecTer;
421
// but tertiary differences are less important than the first
422
// secondary difference, so checking tertiary remains disabled
423
checkTertiary = false;
424
}
425
}
426
continue;
427
}
428
429
// Compare primary differences first.
430
if ( pSOrder != pTOrder )
431
{
432
if (sOrder == 0) {
433
// The entire source element is ignorable.
434
// Skip to the next source element, but don't fetch another target element.
435
gett = false;
436
continue;
437
}
438
if (tOrder == 0) {
439
gets = false;
440
continue;
441
}
442
443
// The source and target elements aren't ignorable, but it's still possible
444
// for the primary component of one of the elements to be ignorable....
445
446
if (pSOrder == 0) // primary order in source is ignorable
447
{
448
// The source's primary is ignorable, but the target's isn't. We treat ignorables
449
// as a secondary difference, so remember that we found one.
450
if (checkSecTer) {
451
result = Collator.GREATER; // (strength is SECONDARY)
452
checkSecTer = false;
453
}
454
// Skip to the next source element, but don't fetch another target element.
455
gett = false;
456
}
457
else if (pTOrder == 0)
458
{
459
// record differences - see the comment above.
460
if (checkSecTer) {
461
result = Collator.LESS; // (strength is SECONDARY)
462
checkSecTer = false;
463
}
464
// Skip to the next source element, but don't fetch another target element.
465
gets = false;
466
} else {
467
// Neither of the orders is ignorable, and we already know that the primary
468
// orders are different because of the (pSOrder != pTOrder) test above.
469
// Record the difference and stop the comparison.
470
if (pSOrder < pTOrder) {
471
return Collator.LESS; // (strength is PRIMARY)
472
} else {
473
return 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 there
478
// are no base elements at this point, only ignorables (Since the strings are
479
// normalized)
480
481
if (checkSecTer) {
482
// a secondary or tertiary difference may still matter
483
short secSOrder = CollationElementIterator.secondaryOrder(sOrder);
484
short secTOrder = CollationElementIterator.secondaryOrder(tOrder);
485
if (secSOrder != secTOrder) {
486
// there is a secondary difference
487
result = (secSOrder < secTOrder) ? Collator.LESS : Collator.GREATER;
488
// (strength is SECONDARY)
489
checkSecTer = false;
490
// (even in french, only the first secondary difference within
491
// a base character matters)
492
} else {
493
if (checkTertiary) {
494
// a tertiary difference may still matter
495
short terSOrder = CollationElementIterator.tertiaryOrder(sOrder);
496
short terTOrder = CollationElementIterator.tertiaryOrder(tOrder);
497
if (terSOrder != terTOrder) {
498
// there is a tertiary difference
499
result = (terSOrder < terTOrder) ? Collator.LESS : Collator.GREATER;
500
// (strength is TERTIARY)
501
checkTertiary = false;
502
}
503
}
504
}
505
} // if (checkSecTer)
506
507
} // if ( pSOrder != pTOrder )
508
} // while()
509
510
if (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.
514
do {
515
if (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 greater
518
return Collator.GREATER; // (strength is PRIMARY)
519
}
520
else if (CollationElementIterator.secondaryOrder(sOrder) != 0) {
521
// Additional secondary elements mean the source string is greater
522
if (checkSecTer) {
523
result = Collator.GREATER; // (strength is SECONDARY)
524
checkSecTer = false;
525
}
526
}
527
} while ((sOrder = sourceCursor.next()) != CollationElementIterator.NULLORDER);
528
}
529
else if (tOrder != CollationElementIterator.NULLORDER) {
530
// The target string has more elements, but the source string hasn't.
531
do {
532
if (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 less
535
return Collator.LESS; // (strength is PRIMARY)
536
else if (CollationElementIterator.secondaryOrder(tOrder) != 0) {
537
// Additional secondary elements in the target mean the source string is less
538
if (checkSecTer) {
539
result = Collator.LESS; // (strength is SECONDARY)
540
checkSecTer = false;
541
}
542
}
543
} while ((tOrder = targetCursor.next()) != CollationElementIterator.NULLORDER);
544
}
545
546
// For IDENTICAL comparisons, we use a bitwise character comparison
547
// as a tiebreaker if all else is equal
548
if (result == 0 && getStrength() == IDENTICAL) {
549
int mode = getDecomposition();
550
Normalizer.Form form;
551
if (mode == CANONICAL_DECOMPOSITION) {
552
form = Normalizer.Form.NFD;
553
} else if (mode == FULL_DECOMPOSITION) {
554
form = Normalizer.Form.NFKD;
555
} else {
556
return source.compareTo(target);
557
}
558
559
String sourceDecomposition = Normalizer.normalize(source, form);
560
String targetDecomposition = Normalizer.normalize(target, form);
561
return sourceDecomposition.compareTo(targetDecomposition);
562
}
563
return result;
564
}
565
566
/**
567
* Transforms the string into a series of characters that can be compared
568
* with CollationKey.compareTo. This overrides java.text.Collator.getCollationKey.
569
* It can be overriden in a subclass.
570
*/
571
public synchronized CollationKey getCollationKey(String source)
572
{
573
//
574
// The basic algorithm here is to find all of the collation elements for each
575
// 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 difference
579
// at the end of a string takes precedence over a secondary or tertiary
580
// difference earlier in the string.
581
//
582
// To account for this, we put all of the primary orders at the beginning of the
583
// string, followed by the secondary and tertiary orders, separated by nulls.
584
//
585
// Here's a hypothetical example, with the collation element represented as
586
// 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 510
590
//
591
// Collation Key: 1125<null>0001<null>1010
592
//
593
// To make things even trickier, secondary differences (accent marks) are compared
594
// 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 compared
596
// from the beginning. To handle this, we reverse all of the accents that belong
597
// to each base character, then we reverse the entire string of secondary orderings
598
// at the end. Taking the same example above, a French collator might return
599
// this instead:
600
//
601
// Collation Key: 1125<null>1000<null>1010
602
//
603
if (source == null)
604
return null;
605
606
if (primResult == null) {
607
primResult = new StringBuffer();
608
secResult = new StringBuffer();
609
terResult = new StringBuffer();
610
} else {
611
primResult.setLength(0);
612
secResult.setLength(0);
613
terResult.setLength(0);
614
}
615
int order = 0;
616
boolean compareSec = (getStrength() >= Collator.SECONDARY);
617
boolean compareTer = (getStrength() >= Collator.TERTIARY);
618
int secOrder = CollationElementIterator.NULLORDER;
619
int terOrder = CollationElementIterator.NULLORDER;
620
int preSecIgnore = 0;
621
622
if (sourceCursor == null) {
623
sourceCursor = getCollationElementIterator(source);
624
} else {
625
sourceCursor.setText(source);
626
}
627
628
// walk through each character
629
while ((order = sourceCursor.next()) !=
630
CollationElementIterator.NULLORDER)
631
{
632
secOrder = CollationElementIterator.secondaryOrder(order);
633
terOrder = CollationElementIterator.tertiaryOrder(order);
634
if (!CollationElementIterator.isIgnorable(order))
635
{
636
primResult.append((char) (CollationElementIterator.primaryOrder(order)
637
+ COLLATIONKEYOFFSET));
638
639
if (compareSec) {
640
//
641
// accumulate all of the ignorable/secondary characters attached
642
// to a given base character
643
//
644
if (tables.isFrenchSec() && preSecIgnore < secResult.length()) {
645
//
646
// We're doing reversed secondary ordering and we've hit a base
647
// (non-ignorable) character. Reverse any secondary orderings
648
// that applied to the last base character. (see block comment above.)
649
//
650
RBCollationTables.reverse(secResult, preSecIgnore, secResult.length());
651
}
652
// Remember where we are in the secondary orderings - this is how far
653
// back to go if we need to reverse them later.
654
secResult.append((char)(secOrder+ COLLATIONKEYOFFSET));
655
preSecIgnore = secResult.length();
656
}
657
if (compareTer) {
658
terResult.append((char)(terOrder+ COLLATIONKEYOFFSET));
659
}
660
}
661
else
662
{
663
if (compareSec && secOrder != 0)
664
secResult.append((char)
665
(secOrder + tables.getMaxSecOrder() + COLLATIONKEYOFFSET));
666
if (compareTer && terOrder != 0)
667
terResult.append((char)
668
(terOrder + tables.getMaxTerOrder() + COLLATIONKEYOFFSET));
669
}
670
}
671
if (tables.isFrenchSec())
672
{
673
if (preSecIgnore < secResult.length()) {
674
// If we've accumulated any secondary characters after the last base character,
675
// reverse them.
676
RBCollationTables.reverse(secResult, preSecIgnore, secResult.length());
677
}
678
// And now reverse the entire secResult to get French secondary ordering.
679
RBCollationTables.reverse(secResult, 0, secResult.length());
680
}
681
primResult.append((char)0);
682
secResult.append((char)0);
683
secResult.append(terResult.toString());
684
primResult.append(secResult.toString());
685
686
if (getStrength() == IDENTICAL) {
687
primResult.append((char)0);
688
int mode = getDecomposition();
689
if (mode == CANONICAL_DECOMPOSITION) {
690
primResult.append(Normalizer.normalize(source, Normalizer.Form.NFD));
691
} else if (mode == FULL_DECOMPOSITION) {
692
primResult.append(Normalizer.normalize(source, Normalizer.Form.NFKD));
693
} else {
694
primResult.append(source);
695
}
696
}
697
return new RuleBasedCollationKey(source, primResult.toString());
698
}
699
700
/**
701
* Standard override; no change in semantics.
702
*/
703
public Object clone() {
704
// if we know we're not actually a subclass of RuleBasedCollator
705
// (this class really should have been made final), bypass
706
// Object.clone() and use our "copy constructor". This is faster.
707
if (getClass() == RuleBasedCollator.class) {
708
return new RuleBasedCollator(this);
709
}
710
else {
711
RuleBasedCollator result = (RuleBasedCollator) super.clone();
712
result.primResult = null;
713
result.secResult = null;
714
result.terResult = null;
715
result.sourceCursor = null;
716
result.targetCursor = null;
717
return result;
718
}
719
}
720
721
/**
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 same
725
* as the table-based collation object obj; false otherwise.
726
*/
727
public boolean equals(Object obj) {
728
if (obj == null) return false;
729
if (!super.equals(obj)) return false; // super does class check
730
RuleBasedCollator other = (RuleBasedCollator) obj;
731
// all other non-transient information is also contained in rules.
732
return (getRules().equals(other.getRules()));
733
}
734
735
/**
736
* Generates the hash code for the table-based collation object
737
*/
738
public int hashCode() {
739
return getRules().hashCode();
740
}
741
742
/**
743
* Allows CollationElementIterator access to the tables object
744
*/
745
RBCollationTables getTables() {
746
return tables;
747
}
748
749
// ==============================================================
750
// private
751
// ==============================================================
752
753
final static int CHARINDEX = 0x70000000; // need look up in .commit()
754
final static int EXPANDCHARINDEX = 0x7E000000; // Expand index follows
755
final static int CONTRACTCHARINDEX = 0x7F000000; // contract indexes follow
756
final static int UNMAPPED = 0xFFFFFFFF;
757
758
private final static int COLLATIONKEYOFFSET = 1;
759
760
private RBCollationTables tables = null;
761
762
// Internal objects that are cached across calls so that they don't have to
763
// be created/destroyed on every call to compare() and getCollationKey()
764
private StringBuffer primResult = null;
765
private StringBuffer secResult = null;
766
private StringBuffer terResult = null;
767
private CollationElementIterator sourceCursor = null;
768
private CollationElementIterator targetCursor = null;
769
}
770
771