RuleBasedCollator.java 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. /* RuleBasedCollator.java -- Concrete Collator Class
  2. Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2005 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.text;
  32. import gnu.classpath.NotImplementedException;
  33. import java.util.ArrayList;
  34. import java.util.HashMap;
  35. /* Written using "Java Class Libraries", 2nd edition, plus online
  36. * API docs for JDK 1.2 from http://www.javasoft.com.
  37. * Status: Believed complete and correct
  38. */
  39. /**
  40. * This class is a concrete subclass of <code>Collator</code> suitable
  41. * for string collation in a wide variety of languages. An instance of
  42. * this class is normally returned by the <code>getInstance</code> method
  43. * of <code>Collator</code> with rules predefined for the requested
  44. * locale. However, an instance of this class can be created manually
  45. * with any desired rules.
  46. * <p>
  47. * Rules take the form of a <code>String</code> with the following syntax
  48. * <ul>
  49. * <li> Modifier: '@'</li>
  50. * <li> Relation: '&lt;' | ';' | ',' | '=' : &lt;text&gt;</li>
  51. * <li> Reset: '&amp;' : &lt;text&gt;</li>
  52. * </ul>
  53. * The modifier character indicates that accents sort backward as is the
  54. * case with French. The modifier applies to all rules <b>after</b>
  55. * the modifier but before the next primary sequence. If placed at the end
  56. * of the sequence if applies to all unknown accented character.
  57. * The relational operators specify how the text
  58. * argument relates to the previous term. The relation characters have
  59. * the following meanings:
  60. * <ul>
  61. * <li>'&lt;' - The text argument is greater than the prior term at the primary
  62. * difference level.</li>
  63. * <li>';' - The text argument is greater than the prior term at the secondary
  64. * difference level.</li>
  65. * <li>',' - The text argument is greater than the prior term at the tertiary
  66. * difference level.</li>
  67. * <li>'=' - The text argument is equal to the prior term</li>
  68. * </ul>
  69. * <p>
  70. * As for the text argument itself, this is any sequence of Unicode
  71. * characters not in the following ranges: 0x0009-0x000D, 0x0020-0x002F,
  72. * 0x003A-0x0040, 0x005B-0x0060, and 0x007B-0x007E. If these characters are
  73. * desired, they must be enclosed in single quotes. If any whitespace is
  74. * encountered, it is ignored. (For example, "a b" is equal to "ab").
  75. * <p>
  76. * The reset operation inserts the following rule at the point where the
  77. * text argument to it exists in the previously declared rule string. This
  78. * makes it easy to add new rules to an existing string by simply including
  79. * them in a reset sequence at the end. Note that the text argument, or
  80. * at least the first character of it, must be present somewhere in the
  81. * previously declared rules in order to be inserted properly. If this
  82. * is not satisfied, a <code>ParseException</code> will be thrown.
  83. * <p>
  84. * This system of configuring <code>RuleBasedCollator</code> is needlessly
  85. * complex and the people at Taligent who developed it (along with the folks
  86. * at Sun who accepted it into the Java standard library) deserve a slow
  87. * and agonizing death.
  88. * <p>
  89. * Here are a couple of example of rule strings:
  90. * <p>
  91. * "&lt; a &lt; b &lt; c" - This string says that a is greater than b which is
  92. * greater than c, with all differences being primary differences.
  93. * <p>
  94. * "&lt; a,A &lt; b,B &lt; c,C" - This string says that 'A' is greater than 'a' with
  95. * a tertiary strength comparison. Both 'b' and 'B' are greater than 'a' and
  96. * 'A' during a primary strength comparison. But 'B' is greater than 'b'
  97. * under a tertiary strength comparison.
  98. * <p>
  99. * "&lt; a &lt; c &amp; a &lt; b " - This sequence is identical in function to the
  100. * "&lt; a &lt; b &lt; c" rule string above. The '&amp;' reset symbol indicates that
  101. * the rule "&lt; b" is to be inserted after the text argument "a" in the
  102. * previous rule string segment.
  103. * <p>
  104. * "&lt; a &lt; b &amp; y &lt; z" - This is an error. The character 'y' does not appear
  105. * anywhere in the previous rule string segment so the rule following the
  106. * reset rule cannot be inserted.
  107. * <p>
  108. * "&lt; a &amp; A @ &lt; e &amp; E &lt; f&amp; F" - This sequence is equivalent to the following
  109. * "&lt; a &amp; A &lt; E &amp; e &lt; f &amp; F".
  110. * <p>
  111. * For a description of the various comparison strength types, see the
  112. * documentation for the <code>Collator</code> class.
  113. * <p>
  114. * As an additional complication to this already overly complex rule scheme,
  115. * if any characters precede the first rule, these characters are considered
  116. * ignorable. They will be treated as if they did not exist during
  117. * comparisons. For example, "- &lt; a &lt; b ..." would make '-' an ignorable
  118. * character such that the strings "high-tech" and "hightech" would
  119. * be considered identical.
  120. * <p>
  121. * A <code>ParseException</code> will be thrown for any of the following
  122. * conditions:
  123. * <ul>
  124. * <li>Unquoted punctuation characters in a text argument.</li>
  125. * <li>A relational or reset operator not followed by a text argument</li>
  126. * <li>A reset operator where the text argument is not present in
  127. * the previous rule string section.</li>
  128. * </ul>
  129. *
  130. * @author Aaron M. Renn (arenn@urbanophile.com)
  131. * @author Tom Tromey (tromey@cygnus.com)
  132. * @author Guilhem Lavaux (guilhem@kaffe.org)
  133. */
  134. public class RuleBasedCollator extends Collator
  135. {
  136. /**
  137. * This class describes what rank has a character (or a sequence of characters)
  138. * in the lexicographic order. Each element in a rule has a collation element.
  139. */
  140. static final class CollationElement
  141. {
  142. final String key;
  143. final int primary;
  144. final short secondary;
  145. final short tertiary;
  146. final short equality;
  147. final boolean ignore;
  148. final String expansion;
  149. CollationElement(String key, int primary, short secondary, short tertiary,
  150. short equality, String expansion, boolean ignore)
  151. {
  152. this.key = key;
  153. this.primary = primary;
  154. this.secondary = secondary;
  155. this.tertiary = tertiary;
  156. this.equality = equality;
  157. this.ignore = ignore;
  158. this.expansion = expansion;
  159. }
  160. int getValue()
  161. {
  162. return (primary << 16) + (secondary << 8) + tertiary;
  163. }
  164. }
  165. /**
  166. * Basic collation instruction (internal format) to build the series of
  167. * collation elements. It contains an instruction which specifies the new
  168. * state of the generator. The sequence of instruction should not contain
  169. * RESET (it is used by
  170. * {@link #mergeRules(int,java.lang.String,java.util.ArrayList,java.util.ArrayList)})
  171. * as a temporary state while merging two sets of instructions.
  172. */
  173. private static final class CollationSorter
  174. {
  175. static final int GREATERP = 0;
  176. static final int GREATERS = 1;
  177. static final int GREATERT = 2;
  178. static final int EQUAL = 3;
  179. static final int RESET = 4;
  180. static final int INVERSE_SECONDARY = 5;
  181. final int comparisonType;
  182. final String textElement;
  183. final int hashText;
  184. final int offset;
  185. final boolean ignore;
  186. String expansionOrdering;
  187. private CollationSorter(final int comparisonType, final String textElement,
  188. final int offset, final boolean ignore)
  189. {
  190. this.comparisonType = comparisonType;
  191. this.textElement = textElement;
  192. this.offset = offset;
  193. this.ignore = ignore;
  194. hashText = textElement.hashCode();
  195. }
  196. }
  197. /**
  198. * This is the original rule string.
  199. */
  200. private String rules;
  201. /**
  202. * This is the table of collation element values
  203. */
  204. private CollationElement[] ce_table;
  205. /**
  206. * Quick-prefix finder.
  207. */
  208. HashMap<String,CollationElement> prefix_tree;
  209. /**
  210. * This is the value of the last sequence entered into
  211. * <code>ce_table</code>. It is used to compute the
  212. * ordering value of unspecified character.
  213. */
  214. private int last_primary_value;
  215. /**
  216. * This is the value of the last secondary sequence of the
  217. * primary 0, entered into
  218. * <code>ce_table</code>. It is used to compute the
  219. * ordering value of an unspecified accented character.
  220. */
  221. private int last_tertiary_value;
  222. /**
  223. * This variable is true if accents need to be sorted
  224. * in the other direction.
  225. */
  226. private boolean inverseAccentComparison;
  227. /**
  228. * This collation element is special to unknown sequence.
  229. * The JDK uses it to mark and sort the characters which has
  230. * no collation rules.
  231. */
  232. static final CollationElement SPECIAL_UNKNOWN_SEQ =
  233. new CollationElement("", (short) 32767, (short) 0, (short) 0,
  234. (short) 0, null, false);
  235. /**
  236. * This method initializes a new instance of <code>RuleBasedCollator</code>
  237. * with the specified collation rules. Note that an application normally
  238. * obtains an instance of <code>RuleBasedCollator</code> by calling the
  239. * <code>getInstance</code> method of <code>Collator</code>. That method
  240. * automatically loads the proper set of rules for the desired locale.
  241. *
  242. * @param rules The collation rule string.
  243. *
  244. * @exception ParseException If the rule string contains syntax errors.
  245. */
  246. public RuleBasedCollator(String rules) throws ParseException
  247. {
  248. if (rules.equals(""))
  249. throw new ParseException("empty rule set", 0);
  250. this.rules = rules;
  251. buildCollationVector(parseString(rules));
  252. buildPrefixAccess();
  253. }
  254. /**
  255. * This method returns the number of common characters at the beginning
  256. * of the string of the two parameters.
  257. *
  258. * @param prefix A string considered as a prefix to test against
  259. * the other string.
  260. * @param s A string to test the prefix against.
  261. * @return The number of common characters.
  262. */
  263. static int findPrefixLength(String prefix, String s)
  264. {
  265. int index;
  266. int len = prefix.length();
  267. for (index = 0; index < len && index < s.length(); ++index)
  268. {
  269. if (prefix.charAt(index) != s.charAt(index))
  270. return index;
  271. }
  272. return index;
  273. }
  274. /**
  275. * Here we are merging two sets of sorting instructions: 'patch' into 'main'. This methods
  276. * checks whether it is possible to find an anchor point for the rules to be merged and
  277. * then insert them at that precise point.
  278. *
  279. * @param offset Offset in the string containing rules of the beginning of the rules
  280. * being merged in.
  281. * @param starter Text of the rules being merged.
  282. * @param main Repository of all already parsed rules.
  283. * @param patch Rules to be merged into the repository.
  284. * @throws ParseException if it is impossible to find an anchor point for the new rules.
  285. */
  286. private void mergeRules(int offset, String starter, ArrayList<CollationSorter> main,
  287. ArrayList<CollationSorter> patch)
  288. throws ParseException
  289. {
  290. int insertion_point = -1;
  291. int max_length = 0;
  292. /* We must check that no rules conflict with another already present. If it
  293. * is the case delete the old rule.
  294. */
  295. /* For the moment good old O(N^2) algorithm.
  296. */
  297. for (int i = 0; i < patch.size(); i++)
  298. {
  299. int j = 0;
  300. while (j < main.size())
  301. {
  302. CollationSorter rule1 = patch.get(i);
  303. CollationSorter rule2 = main.get(j);
  304. if (rule1.textElement.equals(rule2.textElement))
  305. main.remove(j);
  306. else
  307. j++;
  308. }
  309. }
  310. // Find the insertion point... O(N)
  311. for (int i = 0; i < main.size(); i++)
  312. {
  313. CollationSorter sorter = main.get(i);
  314. int length = findPrefixLength(starter, sorter.textElement);
  315. if (length > max_length)
  316. {
  317. max_length = length;
  318. insertion_point = i+1;
  319. }
  320. }
  321. if (insertion_point < 0)
  322. throw new ParseException("no insertion point found for " + starter, offset);
  323. if (max_length < starter.length())
  324. {
  325. /*
  326. * We need to expand the first entry. It must be sorted
  327. * like if it was the reference key itself (like the spec
  328. * said. So the first entry is special: the element is
  329. * replaced by the specified text element for the sorting.
  330. * This text replace the old one for comparisons. However
  331. * to preserve the behaviour we replace the first key (corresponding
  332. * to the found prefix) by a new code rightly ordered in the
  333. * sequence. The rest of the subsequence must be appended
  334. * to the end of the sequence.
  335. */
  336. CollationSorter sorter = patch.get(0);
  337. sorter.expansionOrdering = starter.substring(max_length); // Skip the first good prefix element
  338. main.add(insertion_point, sorter);
  339. /*
  340. * This is a new set of rules. Append to the list.
  341. */
  342. patch.remove(0);
  343. insertion_point++;
  344. }
  345. // Now insert all elements of patch at the insertion point.
  346. for (int i = 0; i < patch.size(); i++)
  347. main.add(i+insertion_point, patch.get(i));
  348. }
  349. /**
  350. * This method parses a string and build a set of sorting instructions. The parsing
  351. * may only be partial on the case the rules are to be merged sometime later.
  352. *
  353. * @param stop_on_reset If this parameter is true then the parser stops when it
  354. * encounters a reset instruction. In the other case, it tries to parse the subrules
  355. * and merged it in the same repository.
  356. * @param v Output vector for the set of instructions.
  357. * @param base_offset Offset in the string to begin parsing.
  358. * @param rules Rules to be parsed.
  359. * @return -1 if the parser reached the end of the string, an integer representing the
  360. * offset in the string at which it stopped parsing.
  361. * @throws ParseException if something turned wrong during the parsing. To get details
  362. * decode the message.
  363. */
  364. private int subParseString(boolean stop_on_reset, ArrayList<CollationSorter> v,
  365. int base_offset, String rules)
  366. throws ParseException
  367. {
  368. boolean ignoreChars = (base_offset == 0);
  369. int operator = -1;
  370. StringBuilder sb = new StringBuilder();
  371. boolean doubleQuote = false;
  372. boolean eatingChars = false;
  373. boolean nextIsModifier = false;
  374. boolean isModifier = false;
  375. int i;
  376. main_parse_loop:
  377. for (i = 0; i < rules.length(); i++)
  378. {
  379. char c = rules.charAt(i);
  380. int type = -1;
  381. if (!eatingChars &&
  382. ((c >= 0x09 && c <= 0x0D) || (c == 0x20)))
  383. continue;
  384. isModifier = nextIsModifier;
  385. nextIsModifier = false;
  386. if (eatingChars && c != '\'')
  387. {
  388. doubleQuote = false;
  389. sb.append(c);
  390. continue;
  391. }
  392. if (doubleQuote && eatingChars)
  393. {
  394. sb.append(c);
  395. doubleQuote = false;
  396. continue;
  397. }
  398. switch (c)
  399. {
  400. case '!':
  401. throw new ParseException
  402. ("Modifier '!' is not yet supported by Classpath", i + base_offset);
  403. case '<':
  404. type = CollationSorter.GREATERP;
  405. break;
  406. case ';':
  407. type = CollationSorter.GREATERS;
  408. break;
  409. case ',':
  410. type = CollationSorter.GREATERT;
  411. break;
  412. case '=':
  413. type = CollationSorter.EQUAL;
  414. break;
  415. case '\'':
  416. eatingChars = !eatingChars;
  417. doubleQuote = true;
  418. break;
  419. case '@':
  420. if (ignoreChars)
  421. throw new ParseException
  422. ("comparison list has not yet been started. You may only use"
  423. + "(<,;=&)", i + base_offset);
  424. // Inverse the order of secondaries from now on.
  425. nextIsModifier = true;
  426. type = CollationSorter.INVERSE_SECONDARY;
  427. break;
  428. case '&':
  429. type = CollationSorter.RESET;
  430. if (stop_on_reset)
  431. break main_parse_loop;
  432. break;
  433. default:
  434. if (operator < 0)
  435. throw new ParseException
  436. ("operator missing at " + (i + base_offset), i + base_offset);
  437. if (! eatingChars
  438. && ((c >= 0x21 && c <= 0x2F)
  439. || (c >= 0x3A && c <= 0x40)
  440. || (c >= 0x5B && c <= 0x60)
  441. || (c >= 0x7B && c <= 0x7E)))
  442. throw new ParseException
  443. ("unquoted punctuation character '" + c + "'", i + base_offset);
  444. //type = ignoreChars ? CollationSorter.IGNORE : -1;
  445. sb.append(c);
  446. break;
  447. }
  448. if (type < 0)
  449. continue;
  450. if (operator < 0)
  451. {
  452. operator = type;
  453. continue;
  454. }
  455. if (sb.length() == 0 && !isModifier)
  456. throw new ParseException
  457. ("text element empty at " + (i+base_offset), i+base_offset);
  458. if (operator == CollationSorter.RESET)
  459. {
  460. /* Reposition in the sorting list at the position
  461. * indicated by the text element.
  462. */
  463. String subrules = rules.substring(i);
  464. ArrayList<CollationSorter> sorted_rules = new ArrayList<CollationSorter>();
  465. int idx;
  466. // Parse the subrules but do not iterate through all
  467. // sublist. This is the privilege of the first call.
  468. idx = subParseString(true, sorted_rules, base_offset+i, subrules);
  469. // Merge new parsed rules into the list.
  470. mergeRules(base_offset+i, sb.toString(), v, sorted_rules);
  471. sb.setLength(0);
  472. // Reset state to none.
  473. operator = -1;
  474. type = -1;
  475. // We have found a new subrule at 'idx' but it has not been parsed.
  476. if (idx >= 0)
  477. {
  478. i += idx-1;
  479. continue main_parse_loop;
  480. }
  481. else
  482. // No more rules.
  483. break main_parse_loop;
  484. }
  485. String textElement = sb.toString();
  486. if (operator == CollationSorter.GREATERP)
  487. ignoreChars = false;
  488. CollationSorter sorter = new CollationSorter(operator, textElement,
  489. base_offset + rules.length(),
  490. ignoreChars);
  491. sb.setLength(0);
  492. v.add(sorter);
  493. operator = type;
  494. }
  495. if (operator >= 0)
  496. {
  497. int pos = rules.length() + base_offset;
  498. if ((sb.length() != 0 && nextIsModifier)
  499. || (sb.length() == 0 && !nextIsModifier && !eatingChars))
  500. throw new ParseException("text element empty at " + pos, pos);
  501. if (operator == CollationSorter.GREATERP)
  502. ignoreChars = false;
  503. CollationSorter sorter = new CollationSorter(operator, sb.toString(),
  504. base_offset+pos, ignoreChars);
  505. v.add(sorter);
  506. }
  507. if (i == rules.length())
  508. return -1;
  509. else
  510. return i;
  511. }
  512. /**
  513. * This method creates a copy of this object.
  514. *
  515. * @return A copy of this object.
  516. */
  517. public Object clone()
  518. {
  519. return super.clone();
  520. }
  521. /**
  522. * This method completely parses a string 'rules' containing sorting rules.
  523. *
  524. * @param rules String containing the rules to be parsed.
  525. * @return A set of sorting instructions stored in a Vector.
  526. * @throws ParseException if something turned wrong during the parsing. To get details
  527. * decode the message.
  528. */
  529. private ArrayList<CollationSorter> parseString(String rules)
  530. throws ParseException
  531. {
  532. ArrayList<CollationSorter> v = new ArrayList<CollationSorter>();
  533. // result of the first subParseString is not absolute (may be -1 or a
  534. // positive integer). But we do not care.
  535. subParseString(false, v, 0, rules);
  536. return v;
  537. }
  538. /**
  539. * This method uses the sorting instructions built by {@link #parseString}
  540. * to build collation elements which can be directly used to sort strings.
  541. *
  542. * @param parsedElements Parsed instructions stored in a ArrayList.
  543. * @throws ParseException if the order of the instructions are not valid.
  544. */
  545. private void buildCollationVector(ArrayList<CollationSorter> parsedElements)
  546. throws ParseException
  547. {
  548. int primary_seq = 0;
  549. int last_tertiary_seq = 0;
  550. short secondary_seq = 0;
  551. short tertiary_seq = 0;
  552. short equality_seq = 0;
  553. boolean inverseComparisons = false;
  554. final boolean DECREASING = false;
  555. final boolean INCREASING = true;
  556. boolean secondaryType = INCREASING;
  557. ArrayList<CollationElement> v = new ArrayList<CollationElement>();
  558. // elts is completely sorted.
  559. element_loop:
  560. for (int i = 0; i < parsedElements.size(); i++)
  561. {
  562. CollationSorter elt = parsedElements.get(i);
  563. switch (elt.comparisonType)
  564. {
  565. case CollationSorter.GREATERP:
  566. primary_seq++;
  567. if (inverseComparisons)
  568. {
  569. secondary_seq = Short.MAX_VALUE;
  570. secondaryType = DECREASING;
  571. }
  572. else
  573. {
  574. secondary_seq = 0;
  575. secondaryType = INCREASING;
  576. }
  577. tertiary_seq = 0;
  578. equality_seq = 0;
  579. inverseComparisons = false;
  580. break;
  581. case CollationSorter.GREATERS:
  582. if (secondaryType == DECREASING)
  583. secondary_seq--;
  584. else
  585. secondary_seq++;
  586. tertiary_seq = 0;
  587. equality_seq = 0;
  588. break;
  589. case CollationSorter.INVERSE_SECONDARY:
  590. inverseComparisons = true;
  591. continue element_loop;
  592. case CollationSorter.GREATERT:
  593. tertiary_seq++;
  594. if (primary_seq == 0)
  595. last_tertiary_seq = tertiary_seq;
  596. equality_seq = 0;
  597. break;
  598. case CollationSorter.EQUAL:
  599. equality_seq++;
  600. break;
  601. case CollationSorter.RESET:
  602. throw new ParseException
  603. ("Invalid reached state 'RESET'. Internal error", elt.offset);
  604. default:
  605. throw new ParseException
  606. ("Invalid unknown state '" + elt.comparisonType + "'", elt.offset);
  607. }
  608. v.add(new CollationElement(elt.textElement, primary_seq,
  609. secondary_seq, tertiary_seq,
  610. equality_seq, elt.expansionOrdering, elt.ignore));
  611. }
  612. this.inverseAccentComparison = inverseComparisons;
  613. ce_table = v.toArray(new CollationElement[v.size()]);
  614. last_primary_value = primary_seq+1;
  615. last_tertiary_value = last_tertiary_seq+1;
  616. }
  617. /**
  618. * Build a tree where all keys are the texts of collation elements and data is
  619. * the collation element itself. The tree is used when extracting all prefix
  620. * for a given text.
  621. */
  622. private void buildPrefixAccess()
  623. {
  624. prefix_tree = new HashMap<String,CollationElement>();
  625. for (int i = 0; i < ce_table.length; i++)
  626. {
  627. CollationElement e = ce_table[i];
  628. prefix_tree.put(e.key, e);
  629. }
  630. }
  631. /**
  632. * This method returns an integer which indicates whether the first
  633. * specified <code>String</code> is less than, greater than, or equal to
  634. * the second. The value depends not only on the collation rules in
  635. * effect, but also the strength and decomposition settings of this object.
  636. *
  637. * @param source The first <code>String</code> to compare.
  638. * @param target A second <code>String</code> to compare to the first.
  639. *
  640. * @return A negative integer if source &lt; target, a positive integer
  641. * if source &gt; target, or 0 if source == target.
  642. */
  643. public int compare(String source, String target)
  644. {
  645. CollationElementIterator cs, ct;
  646. CollationElement ord1block = null;
  647. CollationElement ord2block = null;
  648. boolean advance_block_1 = true;
  649. boolean advance_block_2 = true;
  650. cs = getCollationElementIterator(source);
  651. ct = getCollationElementIterator(target);
  652. for(;;)
  653. {
  654. int ord1;
  655. int ord2;
  656. /*
  657. * We have to check whether the characters are ignorable.
  658. * If it is the case then forget them.
  659. */
  660. if (advance_block_1)
  661. {
  662. ord1block = cs.nextBlock();
  663. if (ord1block != null && ord1block.ignore)
  664. continue;
  665. }
  666. if (advance_block_2)
  667. {
  668. ord2block = ct.nextBlock();
  669. if (ord2block != null && ord2block.ignore)
  670. {
  671. advance_block_1 = false;
  672. continue;
  673. }
  674. }
  675. else
  676. advance_block_2 = true;
  677. if (!advance_block_1)
  678. advance_block_1 = true;
  679. if (ord1block != null)
  680. ord1 = ord1block.getValue();
  681. else
  682. {
  683. if (ord2block == null)
  684. return 0;
  685. return -1;
  686. }
  687. if (ord2block == null)
  688. return 1;
  689. ord2 = ord2block.getValue();
  690. // We know chars are totally equal, so skip
  691. if (ord1 == ord2)
  692. {
  693. if (getStrength() == IDENTICAL)
  694. if (!ord1block.key.equals(ord2block.key))
  695. return ord1block.key.compareTo(ord2block.key);
  696. continue;
  697. }
  698. // Check for primary strength differences
  699. int prim1 = CollationElementIterator.primaryOrder(ord1);
  700. int prim2 = CollationElementIterator.primaryOrder(ord2);
  701. if (prim1 == 0 && getStrength() < TERTIARY)
  702. {
  703. advance_block_2 = false;
  704. continue;
  705. }
  706. else if (prim2 == 0 && getStrength() < TERTIARY)
  707. {
  708. advance_block_1 = false;
  709. continue;
  710. }
  711. if (prim1 < prim2)
  712. return -1;
  713. else if (prim1 > prim2)
  714. return 1;
  715. else if (getStrength() == PRIMARY)
  716. continue;
  717. // Check for secondary strength differences
  718. int sec1 = CollationElementIterator.secondaryOrder(ord1);
  719. int sec2 = CollationElementIterator.secondaryOrder(ord2);
  720. if (sec1 < sec2)
  721. return -1;
  722. else if (sec1 > sec2)
  723. return 1;
  724. else if (getStrength() == SECONDARY)
  725. continue;
  726. // Check for tertiary differences
  727. int tert1 = CollationElementIterator.tertiaryOrder(ord1);
  728. int tert2 = CollationElementIterator.tertiaryOrder(ord2);
  729. if (tert1 < tert2)
  730. return -1;
  731. else if (tert1 > tert2)
  732. return 1;
  733. else if (getStrength() == TERTIARY)
  734. continue;
  735. // Apparently JDK does this (at least for my test case).
  736. return ord1block.key.compareTo(ord2block.key);
  737. }
  738. }
  739. /**
  740. * This method tests this object for equality against the specified
  741. * object. This will be true if and only if the specified object is
  742. * another reference to this object.
  743. *
  744. * @param obj The <code>Object</code> to compare against this object.
  745. *
  746. * @return <code>true</code> if the specified object is equal to this object,
  747. * <code>false</code> otherwise.
  748. */
  749. public boolean equals(Object obj)
  750. {
  751. if (obj == this)
  752. return true;
  753. else
  754. return false;
  755. }
  756. /**
  757. * This method builds a default collation element without invoking
  758. * the database created from the rules passed to the constructor.
  759. *
  760. * @param c Character which needs a collation element.
  761. * @return A valid brand new CollationElement instance.
  762. */
  763. CollationElement getDefaultElement(char c)
  764. {
  765. int v;
  766. // Preliminary support for generic accent sorting inversion (I don't know if all
  767. // characters in the range should be sorted backward). This is the place
  768. // to fix this if needed.
  769. if (inverseAccentComparison && (c >= 0x02B9 && c <= 0x0361))
  770. v = 0x0361 - ((int) c - 0x02B9);
  771. else
  772. v = (short) c;
  773. return new CollationElement("" + c, last_primary_value + v,
  774. (short) 0, (short) 0, (short) 0, null, false);
  775. }
  776. /**
  777. * This method builds a default collation element for an accented character
  778. * without invoking the database created from the rules passed to the constructor.
  779. *
  780. * @param c Character which needs a collation element.
  781. * @return A valid brand new CollationElement instance.
  782. */
  783. CollationElement getDefaultAccentedElement(char c)
  784. {
  785. int v;
  786. // Preliminary support for generic accent sorting inversion (I don't know if all
  787. // characters in the range should be sorted backward). This is the place
  788. // to fix this if needed.
  789. if (inverseAccentComparison && (c >= 0x02B9 && c <= 0x0361))
  790. v = 0x0361 - ((int) c - 0x02B9);
  791. else
  792. v = (short) c;
  793. return new CollationElement("" + c, (short) 0,
  794. (short) 0, (short) (last_tertiary_value + v), (short) 0, null, false);
  795. }
  796. /**
  797. * This method returns an instance for <code>CollationElementIterator</code>
  798. * for the specified <code>String</code> under the collation rules for this
  799. * object.
  800. *
  801. * @param source The <code>String</code> to return the
  802. * <code>CollationElementIterator</code> instance for.
  803. *
  804. * @return A <code>CollationElementIterator</code> for the specified
  805. * <code>String</code>.
  806. */
  807. public CollationElementIterator getCollationElementIterator(String source)
  808. {
  809. return new CollationElementIterator(this, source);
  810. }
  811. /**
  812. * This method returns an instance of <code>CollationElementIterator</code>
  813. * for the <code>String</code> represented by the specified
  814. * <code>CharacterIterator</code>.
  815. *
  816. * @param source The <code>CharacterIterator</code> with the desired <code>String</code>.
  817. *
  818. * @return A <code>CollationElementIterator</code> for the specified <code>String</code>.
  819. */
  820. public CollationElementIterator getCollationElementIterator(CharacterIterator source)
  821. {
  822. return new CollationElementIterator(this, source);
  823. }
  824. /**
  825. * This method returns an instance of <code>CollationKey</code> for the
  826. * specified <code>String</code>. The object returned will have a
  827. * more efficient mechanism for its comparison function that could
  828. * provide speed benefits if multiple comparisons are performed, such
  829. * as during a sort.
  830. *
  831. * @param source The <code>String</code> to create a <code>CollationKey</code> for.
  832. *
  833. * @return A <code>CollationKey</code> for the specified <code>String</code>.
  834. */
  835. public CollationKey getCollationKey(String source)
  836. {
  837. CollationElementIterator cei = getCollationElementIterator(source);
  838. ArrayList<Integer> vect = new ArrayList<Integer>();
  839. int ord = cei.next();
  840. cei.reset(); //set to start of string
  841. while (ord != CollationElementIterator.NULLORDER)
  842. {
  843. // If the primary order is null, it means this is an ignorable
  844. // character.
  845. if (CollationElementIterator.primaryOrder(ord) == 0)
  846. {
  847. ord = cei.next();
  848. continue;
  849. }
  850. switch (getStrength())
  851. {
  852. case PRIMARY:
  853. ord = CollationElementIterator.primaryOrder(ord);
  854. break;
  855. case SECONDARY:
  856. ord = CollationElementIterator.primaryOrder(ord) << 8;
  857. ord |= CollationElementIterator.secondaryOrder(ord);
  858. default:
  859. break;
  860. }
  861. vect.add(Integer.valueOf(ord));
  862. ord = cei.next(); //increment to next key
  863. }
  864. Integer[] objarr = vect.toArray(new Integer[vect.size()]);
  865. byte[] key = new byte[objarr.length * 4];
  866. for (int i = 0; i < objarr.length; i++)
  867. {
  868. int j = objarr[i].intValue();
  869. key [i * 4] = (byte) ((j & 0xFF000000) >> 24);
  870. key [i * 4 + 1] = (byte) ((j & 0x00FF0000) >> 16);
  871. key [i * 4 + 2] = (byte) ((j & 0x0000FF00) >> 8);
  872. key [i * 4 + 3] = (byte) (j & 0x000000FF);
  873. }
  874. return new CollationKey(this, source, key);
  875. }
  876. /**
  877. * This method returns a <code>String</code> containing the collation rules
  878. * for this object.
  879. *
  880. * @return The collation rules for this object.
  881. */
  882. public String getRules()
  883. {
  884. return rules;
  885. }
  886. /**
  887. * This method returns a hash value for this object.
  888. *
  889. * @return A hash value for this object.
  890. */
  891. public int hashCode()
  892. {
  893. return System.identityHashCode(this);
  894. }
  895. }