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.classification.InterfaceAudience;
24 import org.apache.hadoop.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 public enum BitwiseOp {
38
39 AND,
40
41 OR,
42
43 XOR
44 }
45 protected BitwiseOp bitOperator;
46
47
48
49
50
51
52 public BitComparator(byte[] value, BitwiseOp bitOperator) {
53 super(value);
54 this.bitOperator = bitOperator;
55 }
56
57
58
59
60 public BitwiseOp getOperator() {
61 return bitOperator;
62 }
63
64
65
66
67 public byte [] toByteArray() {
68 ComparatorProtos.BitComparator.Builder builder =
69 ComparatorProtos.BitComparator.newBuilder();
70 builder.setComparable(super.convert());
71 ComparatorProtos.BitComparator.BitwiseOp bitwiseOpPb =
72 ComparatorProtos.BitComparator.BitwiseOp.valueOf(bitOperator.name());
73 builder.setBitwiseOp(bitwiseOpPb);
74 return builder.build().toByteArray();
75 }
76
77
78
79
80
81
82
83 public static BitComparator parseFrom(final byte [] pbBytes)
84 throws DeserializationException {
85 ComparatorProtos.BitComparator proto;
86 try {
87 proto = ComparatorProtos.BitComparator.parseFrom(pbBytes);
88 } catch (InvalidProtocolBufferException e) {
89 throw new DeserializationException(e);
90 }
91 BitwiseOp bitwiseOp = BitwiseOp.valueOf(proto.getBitwiseOp().name());
92 return new BitComparator(proto.getComparable().getValue().toByteArray(),bitwiseOp);
93 }
94
95
96
97
98
99
100 boolean areSerializedFieldsEqual(ByteArrayComparable other) {
101 if (other == this) return true;
102 if (!(other instanceof BitComparator)) return false;
103
104 BitComparator comparator = (BitComparator)other;
105 return super.areSerializedFieldsEqual(other)
106 && this.getOperator().equals(comparator.getOperator());
107 }
108
109 @Override
110 public int compareTo(byte[] value, int offset, int length) {
111 if (length != this.value.length) {
112 return 1;
113 }
114 int b = 0;
115
116 for (int i = length - 1; i >= 0 && b == 0; i--) {
117 switch (bitOperator) {
118 case AND:
119 b = (this.value[i] & value[i+offset]) & 0xff;
120 break;
121 case OR:
122 b = (this.value[i] | value[i+offset]) & 0xff;
123 break;
124 case XOR:
125 b = (this.value[i] ^ value[i+offset]) & 0xff;
126 break;
127 }
128 }
129 return b == 0 ? 1 : 0;
130 }
131 }
132