Debian Codegraph @

src/main/org/h2/value/CompareModeDefault.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.value;
7
8 import java.text.CollationKey;
9 import java.text.Collator;
10
11 import org.h2.engine.SysProperties;
12 import org.h2.message.DbException;
13 import org.h2.util.SmallLRUCache;
14
15 /**
16 * The default implementation of CompareMode. It uses java.text.Collator.
17 */
18 public class CompareModeDefault extends CompareMode {
19
20 private final Collator collator;
21 private final SmallLRUCache<String, CollationKey> collationKeys;
22
23 private volatile CompareModeDefault caseInsensitive;
24
25 protected CompareModeDefault(String name, int strength) {
26 super(name, strength);
27 collator = CompareMode.getCollator(name);
28 if (collator == null) {
29 throw DbException.getInternalError(name);
30 }
31 collator.setStrength(strength);
32 int cacheSize = SysProperties.COLLATOR_CACHE_SIZE;
33 if (cacheSize != 0) {
34 collationKeys = SmallLRUCache.newInstance(cacheSize);
35 } else {
36 collationKeys = null;
37 }
38 }
39
40 @Override
41 public int compareString(String a, String b, boolean ignoreCase) {
42 if (ignoreCase && getStrength() > Collator.SECONDARY) {
43 CompareModeDefault i = caseInsensitive;
44 if (i == null) {
45 caseInsensitive = i = new CompareModeDefault(getName(), Collator.SECONDARY);
46 }
47 return i.compareString(a, b, false);
48 }
49 int comp;
50 if (collationKeys != null) {
51 CollationKey aKey = getKey(a);
52 CollationKey bKey = getKey(b);
53 comp = aKey.compareTo(bKey);
54 } else {
55 comp = collator.compare(a, b);
56 }
57 return comp;
58 }
59
60 @Override
61 public boolean equalsChars(String a, int ai, String b, int bi,
62 boolean ignoreCase) {
63 return compareString(a.substring(ai, ai + 1), b.substring(bi, bi + 1),
64 ignoreCase) == 0;
65 }
66
67 private CollationKey getKey(String a) {
68 synchronized (collationKeys) {
69 CollationKey key = collationKeys.get(a);
70 if (key == null) {
71 key = collator.getCollationKey(a);
72 collationKeys.put(a, key);
73 }
74 return key;
75 }
76 }
77
78 }