Fixed register sorting
[Mograsim.git] / plugins / net.mograsim.plugin.core / src / net / mograsim / plugin / util / NumberRespectingStringComparator.java
1 package net.mograsim.plugin.util;
2
3 import java.math.BigInteger;
4 import java.util.Comparator;
5 import java.util.regex.Matcher;
6 import java.util.regex.Pattern;
7
8 /**
9  * Compares Strings respecting integers that appear in the strings with positions in common.<br>
10  * Note that 0003 , 03 and 3 are considered to be at the same level; however if there is no further difference, lexicographic ordering is
11  * applied to ensure the comparator meets the {@link Comparator contract} (this will sort "foor_02" before "foo_2").
12  *
13  * @author Christian Femers
14  *
15  */
16 public class NumberRespectingStringComparator implements Comparator<String>
17 {
18         public static final NumberRespectingStringComparator CASE_SENSITIVE = new NumberRespectingStringComparator();
19
20         private static final Pattern PATTERN = Pattern.compile("\\d+", Pattern.DOTALL);
21
22         private final Comparator<CharSequence> comp = CharSequence::compare;
23
24         private NumberRespectingStringComparator()
25         {
26         }
27
28         @Override
29         public int compare(String o1, String o2)
30         {
31                 Matcher m1 = PATTERN.matcher(o1);
32                 Matcher m2 = PATTERN.matcher(o2);
33                 int pos1 = 0;
34                 int pos2 = 0;
35                 while (m1.find() && m2.find() && m1.start() - pos1 == m2.start() - pos2)
36                 {
37                         int charsCompRes = comp.compare(o1.subSequence(pos1, m1.start()), o2.subSequence(pos2, m2.start()));
38                         if (charsCompRes != 0)
39                                 return charsCompRes;
40
41                         BigInteger num1 = new BigInteger(m1.group());
42                         BigInteger num2 = new BigInteger(m2.group());
43                         int compRes = num1.compareTo(num2);
44                         if (compRes != 0)
45                                 return compRes;
46
47                         pos1 = m1.end();
48                         pos2 = m2.end();
49                 }
50                 int restCompRes = comp.compare(o1.substring(pos1), o2.substring(pos2));
51                 if (restCompRes != 0)
52                         return restCompRes;
53                 return comp.compare(o1, o2);
54         }
55 }