1 | /* |
2 | * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0, |
3 | * and the EPL 1.0 (http://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 | protected CompareModeDefault(String name, int strength, |
24 | boolean binaryUnsigned) { |
25 | super(name, strength, binaryUnsigned); |
26 | collator = CompareMode.getCollator(name); |
27 | if (collator == null) { |
28 | throw DbException.throwInternalError(name); |
29 | } |
30 | collator.setStrength(strength); |
31 | int cacheSize = SysProperties.COLLATOR_CACHE_SIZE; |
32 | if (cacheSize != 0) { |
33 | collationKeys = SmallLRUCache.newInstance(cacheSize); |
34 | } else { |
35 | collationKeys = null; |
36 | } |
37 | } |
38 | |
39 | @Override |
40 | public int compareString(String a, String b, boolean ignoreCase) { |
41 | if (ignoreCase) { |
42 | // this is locale sensitive |
43 | a = a.toUpperCase(); |
44 | b = b.toUpperCase(); |
45 | } |
46 | int comp; |
47 | if (collationKeys != null) { |
48 | CollationKey aKey = getKey(a); |
49 | CollationKey bKey = getKey(b); |
50 | comp = aKey.compareTo(bKey); |
51 | } else { |
52 | comp = collator.compare(a, b); |
53 | } |
54 | return comp; |
55 | } |
56 | |
57 | @Override |
58 | public boolean equalsChars(String a, int ai, String b, int bi, |
59 | boolean ignoreCase) { |
60 | return compareString(a.substring(ai, ai + 1), b.substring(bi, bi + 1), |
61 | ignoreCase) == 0; |
62 | } |
63 | |
64 | private CollationKey getKey(String a) { |
65 | synchronized (collationKeys) { |
66 | CollationKey key = collationKeys.get(a); |
67 | if (key == null) { |
68 | key = collator.getCollationKey(a); |
69 | collationKeys.put(a, key); |
70 | } |
71 | return key; |
72 | } |
73 | } |
74 | |
75 | } |