| 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.nio.charset.Charset; |
| 9 |
import java.text.CollationKey; |
| 10 |
import java.text.Collator; |
| 11 |
import java.util.Comparator; |
| 12 |
import java.util.Locale; |
| 13 |
|
| 14 |
import org.h2.util.Bits; |
| 15 |
|
| 16 |
/** |
| 17 |
* The charset collator sorts strings according to the order in the given charset. |
| 18 |
*/ |
| 19 |
public class CharsetCollator extends Collator { |
| 20 |
|
| 21 |
/** |
| 22 |
* The comparator used to compare byte arrays. |
| 23 |
*/ |
| 24 |
static final Comparator<byte[]> COMPARATOR = Bits::compareNotNullSigned; |
| 25 |
|
| 26 |
private final Charset charset; |
| 27 |
|
| 28 |
public CharsetCollator(Charset charset) { |
| 29 |
this.charset = charset; |
| 30 |
} |
| 31 |
|
| 32 |
public Charset getCharset() { |
| 33 |
return charset; |
| 34 |
} |
| 35 |
|
| 36 |
@Override |
| 37 |
public int compare(String source, String target) { |
| 38 |
return COMPARATOR.compare(toBytes(source), toBytes(target)); |
| 39 |
} |
| 40 |
|
| 41 |
/** |
| 42 |
* Convert the source to bytes, using the character set. |
| 43 |
* |
| 44 |
* @param source the source |
| 45 |
* @return the bytes |
| 46 |
*/ |
| 47 |
byte[] toBytes(String source) { |
| 48 |
if (getStrength() <= Collator.SECONDARY) { |
| 49 |
// TODO perform case-insensitive comparison properly |
| 50 |
source = source.toUpperCase(Locale.ROOT); |
| 51 |
} |
| 52 |
return source.getBytes(charset); |
| 53 |
} |
| 54 |
|
| 55 |
@Override |
| 56 |
public CollationKey getCollationKey(String source) { |
| 57 |
return new CharsetCollationKey(source); |
| 58 |
} |
| 59 |
|
| 60 |
@Override |
| 61 |
public int hashCode() { |
| 62 |
return 255; |
| 63 |
} |
| 64 |
|
| 65 |
private class CharsetCollationKey extends CollationKey { |
| 66 |
|
| 67 |
private final byte[] bytes; |
| 68 |
|
| 69 |
CharsetCollationKey(String source) { |
| 70 |
super(source); |
| 71 |
bytes = toBytes(source); |
| 72 |
} |
| 73 |
|
| 74 |
@Override |
| 75 |
public int compareTo(CollationKey target) { |
| 76 |
return COMPARATOR.compare(bytes, target.toByteArray()); |
| 77 |
} |
| 78 |
|
| 79 |
@Override |
| 80 |
public byte[] toByteArray() { |
| 81 |
return bytes; |
| 82 |
} |
| 83 |
|
| 84 |
} |
| 85 |
} |