/
CharacterKeyAnalyzer.java
110 lines (89 loc) · 3.15 KB
/
CharacterKeyAnalyzer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/*
* Copyright 2005-2010 Roger Kapsi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ardverk.collection;
/**
* A {@link KeyAnalyzer} for {@link Character}s
*/
public class CharacterKeyAnalyzer extends AbstractKeyAnalyzer<Character> {
private static final long serialVersionUID = 3928565962744720753L;
/**
* A singleton instance of the {@link CharacterKeyAnalyzer}.
*/
public static final CharacterKeyAnalyzer INSTANCE
= new CharacterKeyAnalyzer();
/**
* The length of a {@link Character} in bits
*/
public static final int LENGTH = Character.SIZE;
/**
* A bit mask where the first bit is 1 and the others are zero
*/
private static final int MSB = 0x8000;
/**
* Returns a bit mask where the given bit is set
*/
private static int mask(int bit) {
return MSB >>> bit;
}
@Override
public int bitsPerElement() {
return 1;
}
@Override
public int lengthInBits(Character key) {
return LENGTH;
}
@Override
public boolean isBitSet(Character key, int bitIndex, int lengthInBits) {
return (key & mask(bitIndex)) != 0;
}
@Override
public int bitIndex(Character key, int offsetInBits, int lengthInBits,
Character other, int otherOffsetInBits, int otherLengthInBits) {
if (offsetInBits != 0 || otherOffsetInBits != 0) {
throw new IllegalArgumentException("offsetInBits=" + offsetInBits
+ ", otherOffsetInBits=" + otherOffsetInBits);
}
char keyValue = key.charValue();
if (keyValue == Character.MIN_VALUE) {
return NULL_BIT_KEY;
}
if (other == null) {
other = Character.MIN_VALUE;
}
char otherValue = (other != null ? other.charValue() : Character.MIN_VALUE);
if (keyValue != otherValue) {
int xorValue = keyValue ^ otherValue;
for (int i = 0; i < LENGTH; i++) {
if ((xorValue & mask(i)) != 0) {
return i;
}
}
}
return KeyAnalyzer.EQUAL_BIT_KEY;
}
@Override
public boolean isPrefix(Character prefix, int offsetInBits,
int lengthInBits, Character key) {
int value1 = (prefix.charValue() << offsetInBits);
int value2 = key.charValue();
int mask = 0;
for(int i = 0; i < lengthInBits; i++) {
mask |= (0x1 << i);
}
return (value1 & mask) == (value2 & mask);
}
}