Debian Codegraph @

src/uk/me/parabola/imgfmt/app/srt/Sort.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2010, 2011.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 3 or
6 * version 2 as published by the Free Software Foundation.
7 *
8 * This program 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 */
13
14 package uk.me.parabola.imgfmt.app.srt;
15
16 import java.nio.ByteBuffer;
17 import java.nio.CharBuffer;
18 import java.nio.charset.CharacterCodingException;
19 import java.nio.charset.Charset;
20 import java.nio.charset.CharsetEncoder;
21 import java.nio.charset.CodingErrorAction;
22 import java.nio.charset.StandardCharsets;
23 import java.text.CollationKey;
24 import java.text.Collator;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.List;
28 import java.util.Map;
29
30 import uk.me.parabola.imgfmt.ExitException;
31 import uk.me.parabola.imgfmt.app.Label;
32
33 /**
34 * Represents the sorting positions for all the characters in a codepage.
35 *
36 * A map contains a file that determines how the characters are to be sorted. So we
37 * have to have to be able to create such a file and sort with exactly the same rules
38 * as is contained in it.
39 *
40 * What about the java {@link java.text.RuleBasedCollator}? It turns out that it is possible to
41 * make it work in the way we need it to, although it doesn't help with creating the srt file.
42 * Also it is significantly slower than this implementation, so this one is staying. I also
43 * found that sorting with the sort keys and the collator gave different results in some
44 * cases. This implementation does not.
45 *
46 * Be careful when benchmarking. With small lists (< 10000 entries) repeated runs cause some
47 * pretty aggressive optimisation to kick in. This tends to favour this implementation which has
48 * much tighter loops that the java7 or ICU implementations, but this may not be realised with
49 * real workloads.
50 *
51 * @author Steve Ratcliffe
52 */
53 public class Sort {
54 private static final byte[] ZERO_KEY = new byte[4];
55 private static final Integer NO_ORDER = 0;
56
57 private int codepage;
58 private int id1; // Unknown - identifies the sort
59 private int id2; // Unknown - identifies the sort
60
61 private String description;
62 private Charset charset;
63
64 private Page[] pages = new Page[256];
65
66 private final List<CodePosition> expansions = new ArrayList<>();
67 private int maxExpSize = 1;
68
69 private CharsetEncoder encoder;
70 private boolean multi;
71 private int maxPage;
72 private int headerLen = SRTHeader.HEADER_LEN;
73 private int header3Len = -1;
74
75 private int maxPrimary = 0; // max seen while loading resource/sort/cp*.txt file. == 10690 for cp65001.txt on 18Oct2021
76
77 public Sort() {
78 pages[0] = new Page();
79 }
80
81 public void add(int ch, int primary, int secondary, int tertiary, int flags) {
82 ensurePage(ch >>> 8);
83 if (getPrimary(ch) != 0)
84 throw new ExitException(String.format("Repeated primary index 0x%x", ch & 0xff));
85 if (primary > maxPrimary)
86 maxPrimary = primary;
87 setPrimary(ch, primary);
88 setSecondary(ch, secondary);
89 setTertiary(ch, tertiary);
90
91 setFlags(ch, flags);
92 int numExp = (flags >> 4) & 0xf;
93 if (numExp + 1 > maxExpSize)
94 maxExpSize = numExp + 1;
95 }
96
97 public char[] encode(String s) {
98 char[] chars = null;
99 try {
100 if (isMulti()) {
101 chars = s.toCharArray();
102 } else {
103 ByteBuffer out = encoder.encode(CharBuffer.wrap(s));
104 byte[] bval = out.array();
105 chars = new char[bval.length];
106 for (int i = 0; i < bval.length; i++)
107 chars[i] = (char) (bval[i] & 0xff);
108 }
109 } catch (CharacterCodingException e) {
110 }
111 return chars;
112 }
113
114 /**
115 * Get the prefix of the name of the given length.
116 * @param name the name
117 * @param prefixLen the length
118 * @return String with wanted length, possibly padded with trailing zeros.
119 */
120 public char[] getPrefix(String name, int prefixLen) {
121 char[] chars = encode(name);
122 return Arrays.copyOf(chars, prefixLen);
123 }
124
125 /**
126 * Run after all sorting order points have been added.
127 *
128 * Make sure that all tertiary values of secondary ignorable are greater
129 * than any normal tertiary value.
130 *
131 * And the same for secondaries on primary ignorable.
132 */
133 public void finish() {
134 int maxSecondary = 0;
135 int maxTertiary = 0;
136 for (Page p : pages) {
137 if (p == null)
138 continue;
139
140 for (int i = 0; i < 256; i++) {
141 if (((p.flags[i] >>> 4) & 0xf) == 0) {
142 if (p.getPrimary(i) != 0) {
143 int second = p.getSecondary(i);
144 maxSecondary = Math.max(maxSecondary, second);
145 if (second != 0) {
146 maxTertiary = Math.max(maxTertiary, p.getTertiary(i));
147 }
148 }
149 }
150 }
151 }
152
153 for (Page p : pages) {
154 if (p == null)
155 continue;
156
157 for (int i = 0; i < 256; i++) {
158 if (((p.flags[i] >>> 4) & 0xf) != 0) continue;
159
160 if (p.getPrimary(i) == 0) {
161 if (p.getSecondary(i) == 0) {
162 if (p.getTertiary(i) != 0) {
163 p.setTertiary(i, p.getTertiary(i) + maxTertiary);
164 }
165 } else {
166 p.setSecondary(i, p.getSecondary(i) + maxSecondary);
167 }
168 }
169 }
170 }
171 }
172
173 /**
174 * Return a table indexed by a character value in the target codepage, that gives the complete sort
175 * position of the character.
176 *
177 * This is only used for testing.
178 *
179 * @return A table of sort positions.
180 */
181 public char[] getSortPositions() {
182 char[] tab = new char[256];
183
184 for (int i = 1; i < 256; i++) {
185 tab[i] = (char) (((getPrimary(i) << 8) & 0xff00) | ((getSecondary(i) << 4) & 0xf0) | (getTertiary(i) & 0xf));
186 }
187
188 return tab;
189 }
190
191 /**
192 * Create a sort key for a given unicode string. The sort key can be compared instead of the original strings
193 * and will compare based on the sorting represented by this Sort class.
194 *
195 * Using a sort key is more efficient if many comparisons are being done (for example if you are sorting a
196 * list of strings).
197 *
198 * @param object This is saved in the sort key for later retrieval and plays no part in the sorting.
199 * @param s The string for which the sort key is to be created.
200 * @param second Secondary sort key.
201 * @param cache A cache for the created keys. This is for saving memory so it is essential that this
202 * is managed by the caller.
203 * @return A sort key.
204 */
205 public <T> SortKey<T> createSortKey(T object, String s, int second, Map<String, byte[]> cache) {
206 if (s.length() == 0)
207 return new SrtSortKey<>(object, ZERO_KEY, second);
208
209 // If there is a cache then look up and return the key.
210 // This is primarily for memory management, not for speed.
211 byte[] key;
212 if (cache != null) {
213 key = cache.get(s);
214 if (key != null)
215 return new SrtSortKey<>(object, key, second);
216 }
217
218 try {
219 char[] chars;
220 if (isMulti()) {
221 chars = s.toCharArray();
222 } else {
223 ByteBuffer out = encoder.encode(CharBuffer.wrap(s));
224 byte[] bval = out.array();
225 chars = new char[bval.length];
226 for (int i = 0; i < bval.length; i++)
227 chars[i] = (char) (bval[i] & 0xff);
228 }
229 key = makeKey(chars);
230 if (cache != null)
231 cache.put(s, key);
232
233 return new SrtSortKey<>(object, key, second);
234 } catch (CharacterCodingException e) {
235 return new SrtSortKey<>(object, ZERO_KEY);
236 }
237 }
238
239 /**
240 * Create a sort key based on a Label.
241 *
242 * The label will contain the actual characters (after transliteration for example)
243 * @param object This is saved in the sort key for later retrieval and plays no part in the sorting.
244 * @param label The label, the actual written bytes/chars will be used as input to the sort.
245 * @param second Secondary sort key.
246 * @param cache A cache for the created keys. This is for saving memory so it is essential that this
247 * is managed by the caller.
248 * @return A sort key.
249 */
250 public <T> SortKey<T> createSortKey(T object, Label label, int second, Map<Label, byte[]> cache) {
251 if (label.getLength() == 0)
252 return new SrtSortKey<>(object, ZERO_KEY, second);
253 byte[] key;
254 if (cache != null) {
255 key = cache.get(label);
256 if (key != null)
257 return new SrtSortKey<>(object, key, second);
258 }
259
260 char[] encText = label.getEncText();
261 key = makeKey(encText);
262 if (cache != null)
263 cache.put(label, key);
264
265 return new SrtSortKey<>(object, key, second);
266 }
267
268 /**
269 * Create a sort key based on a Label, return key for partial name if prefix / suffix is found, else key for full name.
270 *
271 * The label will contain the actual characters (after transliteration for example)
272 * @param object This is saved in the sort key for later retrieval and plays no part in the sorting.
273 * @param label The label, the actual written bytes/chars will be used as input to the sort.
274 * @param second Secondary sort key.
275 * @param cache A cache for the created keys. This is for saving memory so it is essential that this
276 * is managed by the caller.
277 * @return A sort key.
278 */
279 public <T> SortKey<T> createSortKeyPartial(T object, Label label, int second, Map<Label, byte[]> cache) {
280 if (label.getLength() == 0)
281 return new SrtSortKey<>(object, ZERO_KEY, second);
282 byte[] key;
283 if (cache != null) {
284 key = cache.get(label);
285 if (key != null)
286 return new SrtSortKey<>(object, key, second);
287 }
288
289 char[] encText = label.getEncText();
290 int prefix = -1;
291 for (int i = 0; i < encText.length; i++) {
292 char c = encText[i];
293 if (c == 0x1e || c == 0x1b) {
294 prefix = i;
295 break;
296 }
297 }
298 int suffix = -1;
299 for (int i = 0; i < encText.length; i++) {
300 char c = encText[i];
301 if (c == 0x1f || c == 0x1c) {
302 suffix = i;
303 break;
304 }
305 }
306
307 if (prefix > 0 || suffix > 0) {
308 int partLen;
309 if (prefix > 0 && suffix > 0)
310 partLen = suffix - prefix-1;
311 else if (prefix > 0) {
312 partLen = encText.length - (prefix + 1);
313 }
314 else {
315 partLen = suffix ;
316 }
317 // extract partial name without creating trailing zeros
318 char[] newEncText = new char[partLen];
319 System.arraycopy(encText, prefix+1, newEncText, 0, partLen);
320 encText = newEncText;
321 }
322
323 key = makeKey(encText);
324 if (cache != null)
325 cache.put(label, key);
326
327 return new SrtSortKey<>(object, key, second);
328 }
329
330 /**
331 * Convenient version of create sort key method.
332 * @see #createSortKey(Object, String, int, Map)
333 */
334 public <T> SortKey<T> createSortKey(T object, String s, int second) {
335 return createSortKey(object, s, second, null);
336 }
337
338 /**
339 * Convenient version of create sort key method.
340 *
341 * @see #createSortKey(Object, String, int, Map)
342 */
343 public <T> SortKey<T> createSortKey(T object, String s) {
344 return createSortKey(object, s, 0, null);
345 }
346
347 public <T> SortKey<T> createSortKey(T object, Label label) {
348 return createSortKey(object, label, 0, null);
349 }
350
351 public <T> SortKey<T> createSortKey(T object, Label label, int second) {
352 return createSortKey(object, label, second, null);
353 }
354
355 /**
356 * Create the key and trim it to the needed length if that saves memory.
357 * @param chars character array
358 * @return byte array
359 */
360 private byte[] makeKey(char[] chars) {
361 // In theory you could have a string where every character expands into maxExpSize separate characters
362 // in the key. However if we allocate enough space to deal with the worst case, then we waste a
363 // vast amount of memory. So allocate a minimal amount of space, try it and if it fails reallocate the
364 // maximum amount.
365 //
366 // We need +1 for the null bytes, we also +2 for a couple of expanded characters. For a complete
367 // german map this was always enough in tests.
368 byte[] key = new byte[(chars.length + 1 + 2) * 4];
369 int needed;
370 try {
371 needed = fillCompleteKey(chars, key);
372 } catch (ArrayIndexOutOfBoundsException e) {
373 // Ok try again with the max possible key size allocated.
374 key = new byte[(chars.length+1) * 4 * maxExpSize];
375 needed = fillCompleteKey(chars, key);
376 }
377 // check if we can save bytes by copying
378 int neededBytes = needed;
379 int padding2 = 8 - (needed & 7);
380 if (padding2 != 8)
381 neededBytes += padding2;
382 if (neededBytes < key.length)
383 key = Arrays.copyOf(key, needed);
384 return key;
385 }
386
387 /**
388 * Fill in the key from the given byte string.
389 *
390 * @param bVal The string for which we are creating the sort key.
391 * @param key The sort key. This will be filled in.
392 * @return the needed number of bytes in case the buffer was large enough
393 */
394 private int fillCompleteKey(char[] bVal, byte[] key) {
395 int start = fillKey(Collator.PRIMARY, bVal, key, 0);
396 start = fillKey(Collator.SECONDARY, bVal, key, start);
397 return fillKey(Collator.TERTIARY, bVal, key, start);
398 }
399
400 private static int writeSort(int strength, int pos, byte[] outKey, int start) {
401 if (strength == Collator.PRIMARY)
402 outKey[start++] = (byte) ((pos >> 8) & 0xff); // for 2 byte charsets
403 outKey[start++] = (byte) (pos & 0xff);
404 return start;
405 }
406
407 /**
408 * Fill in the output key for a given strength.
409 *
410 * @param input The input string in a particular 8 bit codepage.
411 * @param outKey The output sort key.
412 * @param start The index into the output key to start at.
413 * @return The next position in the output key.
414 */
415 private int fillKey(int type, char[] input, byte[] outKey, int start) {
416 int index = start;
417 for (char c : input) {
418
419 if (!hasPage(c >>> 8)) {
420 if (isMulti() && type == Collator.PRIMARY) // attempt to avoid conflict with defined sorts. Be consistent with SrtCollator
421 index = writeSort(type, c + maxPrimary, outKey, index);
422 continue;
423 }
424
425 int exp = (getFlags(c) >> 4) & 0xf;
426 if (exp == 0) {
427 index = writePos(type, c, outKey, index);
428 } else {
429 // now have to redirect to a list of input chars, get the list via the primary value always.
430 int idx = getPrimary(c);
431 for (int i = idx - 1; i < idx + exp; i++) {
432 int pos = expansions.get(i).getPosition(type);
433 index = writeSort(type, pos, outKey, index);
434 }
435 }
436 }
437
438 if (type == Collator.PRIMARY)
439 outKey[index++] = '\0';
440 outKey[index++] = '\0';
441 return index;
442 }
443
444 public int getPrimary(int ch) {
445 return this.pages[ch >>> 8].getPrimary(ch);
446 }
447
448 public int getSecondary(int ch) {
449 return this.pages[ch >>> 8].getSecondary(ch);
450 }
451
452 public int getTertiary(int ch) {
453 return this.pages[ch >>> 8].getTertiary(ch);
454 }
455
456 public byte getFlags(int ch) {
457 assert ch >= 0;
458 return this.pages[ch >>> 8].flags[ch & 0xff];
459 }
460
461 public int getCodepage() {
462 return codepage;
463 }
464
465 public Charset getCharset() {
466 return charset;
467 }
468
469 public int getId1() {
470 return id1;
471 }
472
473 public void setId1(int id1) {
474 this.id1 = id1;
475 }
476
477 public int getId2() {
478 return id2;
479 }
480
481 public void setId2(int id2) {
482 this.id2 = id2 & 0x7fff;
483 }
484
485 /**
486 * Get the sort order as a single integer.
487 * A combination of id1 and id2. I think that they are arbitrary so may as well treat them as one.
488 *
489 * @return id1 and id2 as if they were a little endian 2 byte integer.
490 */
491 public int getSortOrderId() {
492 return (this.id2 << 16) + (this.id1 & 0xffff);
493 }
494
495 /**
496 * Set the sort order as a single integer.
497 * @param id The sort order id.
498 */
499 public void setSortOrderId(int id) {
500 id1 = id & 0xffff;
501 id2 = (id >>> 16) & 0x7fff;
502 }
503
504 public void setCodepage(int codepage) {
505 this.codepage = codepage;
506 charset = charsetFromCodepage(codepage);
507
508 encoder = charset.newEncoder();
509 encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
510 }
511
512 public String getDescription() {
513 return description;
514 }
515
516 public void setDescription(String description) {
517 this.description = description;
518 }
519
520 /**
521 * Get the expansion with the given index, one based.
522 * @param val The one-based index number of the extension.
523 */
524 public CodePosition getExpansion(int val) {
525 return expansions.get(val - 1);
526 }
527
528 public Collator getCollator() {
529 return new SrtCollator(codepage);
530 }
531
532 public int getExpansionSize() {
533 return expansions.size();
534 }
535
536 public String toString() {
537 return String.format("sort cp=%d order=%08x", codepage, getSortOrderId());
538 }
539
540 private void setPrimary(int ch, int val) {
541 this.pages[ch >>> 8].setPrimary(ch, val);
542 }
543
544 private void setSecondary(int ch, int val) {
545 this.pages[ch >>> 8].setSecondary(ch, val);
546 }
547
548 private void setTertiary(int ch, int val) {
549 this.pages[ch >>> 8].setTertiary(ch, val);
550 }
551
552 private void setFlags(int ch, int val) {
553 this.pages[ch >>> 8].flags[ch & 0xff] = (byte) val;
554 }
555
556 public static Charset charsetFromCodepage(int codepage) {
557 Charset charset;
558 switch (codepage) {
559 case 0:
560 charset = StandardCharsets.US_ASCII;
561 break;
562 case 65001:
563 charset = StandardCharsets.UTF_8;
564 break;
565 case 932:
566 // Java uses "ms932" for code page 932
567 // (Windows-31J, Shift-JIS + MS extensions)
568 charset = Charset.forName("ms932");
569 break;
570 default:
571 charset = Charset.forName("cp" + codepage);
572 break;
573 }
574 return charset;
575 }
576
577 public void setMulti(boolean multi) {
578 this.multi = multi;
579 }
580
581 public boolean isMulti() {
582 return multi;
583 }
584
585 public int getPos(int type, int ch) {
586 return pages[ch >>> 8].getPos(type, ch);
587 }
588
589 public int writePos(int type, int ch, byte[] outkey, int start) {
590 return pages[ch >>> 8].writePos(type, ch, outkey, start);
591 }
592
593 /**
594 * Ensure that the given page exists in the page array.
595 *
596 * @param n The page index.
597 */
598 private void ensurePage(int n) {
599 assert n == 0 || isMulti();
600 if (n > pages.length)
601 pages = Arrays.copyOf(pages, n + 1);
602 if (this.pages[n] == null) {
603 this.pages[n] = new Page();
604 if (n > maxPage)
605 maxPage = n;
606 }
607 }
608
609 /**
610 * Allocate space for up to n pages.
611 * @param n Number of pages
612 */
613 public void setMaxPage(int n) {
614 pages = Arrays.copyOf(pages, n + 1);
615 }
616
617 /**
618 * The max page, top 8+ bits of the character that we have information on.
619 */
620 public int getMaxPage() {
621 return maxPage;
622 }
623
624 /**
625 * @return True if there is at least one character with the given page/block number.
626 */
627 public boolean hasPage(int p) {
628 return pages[p] != null;
629 }
630
631 /**
632 * Holds the sort positions of a 256 character block.
633 */
634 private static class Page {
635 private final char[] primary = new char[256];
636 private final byte[] secondary = new byte[256];
637 private final byte[] tertiary = new byte[256];
638 private final byte[] flags = new byte[256];
639
640 int getPrimary(int ch) {
641 return primary[ch & 0xff];
642 }
643
644 void setPrimary(int ch, int val) {
645 primary[ch & 0xff] = (char) val;
646 }
647
648 int getSecondary(int ch) {
649 return secondary[ch & 0xff] & 0xff;
650 }
651
652 void setSecondary(int ch, int val) {
653 secondary[ch & 0xff] = (byte) val;
654 }
655
656 int getTertiary(int ch) {
657 return tertiary[ch & 0xff] & 0xff;
658 }
659
660 void setTertiary(int ch, int val) {
661 tertiary[ch & 0xff] = (byte) val;
662 }
663
664 /**
665 * Get the sort position data for a given strength for a character.
666 * @param type The collation strength PRIMARY, SECONDARY etc.
667 * @param ch The character.
668 * @return The sorting weight for the given character.
669 */
670 public int getPos(int type, int ch) {
671 switch (type) {
672 case Collator.PRIMARY:
673 return getPrimary(ch);
674 case Collator.SECONDARY:
675 return getSecondary(ch);
676 case Collator.TERTIARY:
677 return getTertiary(ch);
678 default:
679 assert false : "bad collation type passed";
680 return 0;
681 }
682 }
683
684 /**
685 * Write a sort position for a given character to a sort key.
686 * @param strength The sort strength type.
687 * @param ch The character.
688 * @param outKey The output key.
689 * @param start The offset into outKey, the new position is written here.
690 * @return The new start offset, after the key information has been written.
691 */
692 public int writePos(int strength, int ch, byte[] outKey, int start) {
693 int pos = getPos(strength, ch);
694 if (pos != 0)
695 start = writeSort(strength, pos, outKey, start);
696 return start;
697 }
698 }
699
700 /**
701 * A collator that works with this sort. This should be used if you just need to compare two
702 * strings against each other once.
703 *
704 * The sort key is better when the comparison must be done several times as in a sort operation.
705 *
706 * This implementation has the same effect when used for sorting as the sort keys.
707 */
708 public class SrtCollator extends Collator {
709 private final int codepage;
710
711 private SrtCollator(int codepage) {
712 this.codepage = codepage;
713 }
714
715 public int compare(String source, String target) {
716 if (source == target)
717 return 0;
718
719 char[] chars1;
720 char[] chars2;
721 if (isMulti()) {
722 chars1 = source.toCharArray();
723 chars2 = target.toCharArray();
724 } else {
725 CharBuffer in1 = CharBuffer.wrap(source);
726 CharBuffer in2 = CharBuffer.wrap(target);
727 try {
728 byte[] bytes1 = encoder.encode(in1).array();
729 byte[] bytes2 = encoder.encode(in2).array();
730 chars1 = new char[bytes1.length];
731 for (int i = 0; i < bytes1.length; i++)
732 chars1[i] = (char) (bytes1[i] & 0xff);
733 chars2 = new char[bytes2.length];
734 for (int i = 0; i < bytes2.length; i++)
735 chars2[i] = (char) (bytes2[i] & 0xff);
736 } catch (CharacterCodingException e) {
737 throw new ExitException("character encoding failed unexpectedly", e);
738 }
739 }
740
741 int strength = getStrength();
742 int res = compareOneStrength(chars1, chars2, Collator.PRIMARY);
743
744 if (res == 0 && strength != PRIMARY) {
745 res = compareOneStrength(chars1, chars2, Collator.SECONDARY);
746 if (res == 0 && strength != SECONDARY) {
747 res = compareOneStrength(chars1, chars2, Collator.TERTIARY);
748 }
749 }
750
751 return res;
752 }
753
754 /**
755 * Compare the bytes against primary, secondary or tertiary arrays.
756 * @param char1 Bytes for the first string in the codepage encoding.
757 * @param char2 Bytes for the second string in the codepage encoding.
758 * @return Comparison result -1, 0 or 1.
759 */
760 public int compareOneStrength(char[] char1, char[] char2, int type) {
761 PositionIterator it1 = new PositionIterator(char1, type);
762 PositionIterator it2 = new PositionIterator(char2, type);
763
764 while (it1.hasNext() || it2.hasNext()) {
765 int p1 = it1.next();
766 int p2 = it2.next();
767
768 if (p1 < p2) {
769 return -1;
770 } else if (p1 > p2) {
771 return 1;
772 }
773 }
774
775 return 0;
776 }
777
778 /**
779 * Compare the bytes against primary, secondary or tertiary arrays.
780 * @param char1 Bytes for the first string in the codepage encoding.
781 * @param char2 Bytes for the second string in the codepage encoding.
782 * @return Comparison result -1, 0 or 1.
783 */
784 public int compareOneStrengthWithLength(char[] char1, char[] char2, int type, int len) {
785 PositionIterator it1 = new PositionIterator(char1, type);
786 PositionIterator it2 = new PositionIterator(char2, type);
787
788 int todo = len;
789 while (it1.hasNext() || it2.hasNext()) {
790 int p1 = it1.next();
791 int p2 = it2.next();
792 if (--todo < 0)
793 return 0;
794 if (p1 < p2) {
795 return -1;
796 } else if (p1 > p2) {
797 return 1;
798 }
799 }
800
801 return 0;
802 }
803
804 public CollationKey getCollationKey(String source) {
805 throw new UnsupportedOperationException("use Sort.createSortKey() instead");
806 }
807
808 public boolean equals(Object o) {
809 if (this == o) return true;
810 if (o == null || getClass() != o.getClass()) return false;
811
812 SrtCollator that = (SrtCollator) o;
813
814 if (codepage != that.codepage) return false;
815 return true;
816 }
817
818 public int hashCode() {
819 return codepage;
820 }
821
822 class PositionIterator {
823 private final char[] chars;
824 private final int len;
825 private final int type;
826
827 private int pos;
828
829 private int expStart;
830 private int expEnd;
831 private int expPos;
832
833 PositionIterator(char[] chars, int type) {
834 this.chars = chars;
835 this.len = chars.length;
836 this.type = type;
837 }
838
839 public boolean hasNext() {
840 return pos < len || expPos != 0;
841 }
842
843 /**
844 * Get the next sort order value for the input string. Does not ever return values
845 * that are ignorable. Returns NO_ORDER at (and beyond) the end of the string, this
846 * value sorts less than any other and so makes shorter strings sort first.
847 * @return The next non-ignored sort position. At the end of the string it returns
848 * NO_ORDER.
849 */
850 public int next() {
851 int next;
852 if (expPos == 0) {
853
854 do {
855 if (pos >= len) {
856 next = NO_ORDER;
857 break;
858 }
859
860 // Get the first non-ignorable at this level
861 int c = chars[pos++];
862 if (!hasPage(c >>> 8)) {
863 if (isMulti() && type == Collator.PRIMARY) // order by char itself if no sortpos
864 return (c + maxPrimary) & 0xffff; // attempt to avoid conflict with defined sorts. Be consistent with fillKey
865 next = 0;
866 continue;
867 }
868
869 int nExpand = (getFlags(c) >> 4) & 0xf;
870 // Check if this is an expansion.
871 if (nExpand > 0) {
872 expStart = getPrimary(c) - 1;
873 expEnd = expStart + nExpand;
874 expPos = expStart;
875 next = expansions.get(expPos).getPosition(type);
876
877 if (++expPos > expEnd)
878 expPos = 0;
879 } else {
880 next = getPos(type, c);
881 }
882
883 } while (next == 0);
884 } else {
885 next = expansions.get(expPos).getPosition(type);
886 if (++expPos > expEnd)
887 expPos = 0;
888 }
889
890 return next;
891 }
892 }
893 }
894
895 public void setExpansions(List<CodePosition> expansionList) {
896 expansions.clear();
897 expansions.addAll(expansionList);
898 }
899
900 public int getHeaderLen() {
901 return headerLen;
902 }
903
904 public void setHeaderLen(int headerLen) {
905 this.headerLen = headerLen;
906 }
907
908 public int getHeader3Len() {
909 if (header3Len < 0)
910 header3Len = isMulti() ? SRTHeader.HEADER3_MULTI_LEN : SRTHeader.HEADER3_LEN;
911 return header3Len;
912 }
913
914 public void setHeader3Len(int header3Len) {
915 this.header3Len = header3Len;
916 }
917
918 }