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