1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.hadoop.hbase.filter;
21
22 import com.google.protobuf.InvalidProtocolBufferException;
23 import org.apache.hadoop.hbase.classification.InterfaceAudience;
24 import org.apache.hadoop.hbase.classification.InterfaceStability;
25 import org.apache.hadoop.hbase.exceptions.DeserializationException;
26 import org.apache.hadoop.hbase.protobuf.generated.ComparatorProtos;
27
28
29
30
31
32 @InterfaceAudience.Public
33 @InterfaceStability.Stable
34 public class BitComparator extends ByteArrayComparable {
35
36
37 @InterfaceAudience.Public
38 @InterfaceStability.Stable
39 public enum BitwiseOp {
40
41 AND,
42
43 OR,
44
45 XOR
46 }
47 protected BitwiseOp bitOperator;
48
49
50
51
52
53
54 public BitComparator(byte[] value, BitwiseOp bitOperator) {
55 super(value);
56 this.bitOperator = bitOperator;
57 }
58
59
60
61
62 public BitwiseOp getOperator() {
63 return bitOperator;
64 }
65
66
67
68
69 public byte [] toByteArray() {
70 ComparatorProtos.BitComparator.Builder builder =
71 ComparatorProtos.BitComparator.newBuilder();
72 builder.setComparable(super.convert());
73 ComparatorProtos.BitComparator.BitwiseOp bitwiseOpPb =
74 ComparatorProtos.BitComparator.BitwiseOp.valueOf(bitOperator.name());
75 builder.setBitwiseOp(bitwiseOpPb);
76 return builder.build().toByteArray();
77 }
78
79
80
81
82
83
84
85 public static BitComparator parseFrom(final byte [] pbBytes)
86 throws DeserializationException {
87 ComparatorProtos.BitComparator proto;
88 try {
89 proto = ComparatorProtos.BitComparator.parseFrom(pbBytes);
90 } catch (InvalidProtocolBufferException e) {
91 throw new DeserializationException(e);
92 }
93 BitwiseOp bitwiseOp = BitwiseOp.valueOf(proto.getBitwiseOp().name());
94 return new BitComparator(proto.getComparable().getValue().toByteArray(),bitwiseOp);
95 }
96
97
98
99
100
101
102 boolean areSerializedFieldsEqual(ByteArrayComparable other) {
103 if (other == this) return true;
104 if (!(other instanceof BitComparator)) return false;
105
106 BitComparator comparator = (BitComparator)other;
107 return super.areSerializedFieldsEqual(other)
108 && this.getOperator().equals(comparator.getOperator());
109 }
110
111 @Override
112 public int compareTo(byte[] value, int offset, int length) {
113 if (length != this.value.length) {
114 return 1;
115 }
116 int b = 0;
117
118 for (int i = length - 1; i >= 0 && b == 0; i--) {
119 switch (bitOperator) {
120 case AND:
121 b = (this.value[i] & value[i+offset]) & 0xff;
122 break;
123 case OR:
124 b = (this.value[i] | value[i+offset]) & 0xff;
125 break;
126 case XOR:
127 b = (this.value[i] ^ value[i+offset]) & 0xff;
128 break;
129 }
130 }
131 return b == 0 ? 1 : 0;
132 }
133 }
134