1 /*
2 * Copyright 2010 The Apache Software Foundation
3 *
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 */
20
21 package org.apache.hadoop.hbase.filter;
22
23 import java.io.DataInput;
24 import java.io.DataOutput;
25 import java.io.IOException;
26
27 /**
28 * A bit comparator which performs the specified bitwise operation on each of the bytes
29 * with the specified byte array. Then returns whether the result is non-zero.
30 */
31 public class BitComparator extends WritableByteArrayComparable {
32
33 /** Nullary constructor for Writable, do not use */
34 public BitComparator() {}
35
36 /** Bit operators. */
37 public enum BitwiseOp {
38 /** and */
39 AND,
40 /** or */
41 OR,
42 /** xor */
43 XOR
44 }
45 protected BitwiseOp bitOperator;
46
47 /**
48 * Constructor
49 * @param value value
50 * @param bitOperator operator to use on the bit comparison
51 */
52 public BitComparator(byte[] value, BitwiseOp bitOperator) {
53 super(value);
54 this.bitOperator = bitOperator;
55 }
56
57 /**
58 * @return the bitwise operator
59 */
60 public BitwiseOp getOperator() {
61 return bitOperator;
62 }
63
64 @Override
65 public void readFields(DataInput in) throws IOException {
66 super.readFields(in);
67 bitOperator = BitwiseOp.valueOf(in.readUTF());
68 }
69
70 @Override
71 public void write(DataOutput out) throws IOException {
72 super.write(out);
73 out.writeUTF(bitOperator.name());
74 }
75
76 @Override
77 public int compareTo(byte[] value) {
78 if (value.length != this.value.length) {
79 return 1;
80 }
81 int b = 0;
82 //Iterating backwards is faster because we can quit after one non-zero byte.
83 for (int i = value.length - 1; i >= 0 && b == 0; i--) {
84 switch (bitOperator) {
85 case AND:
86 b = (this.value[i] & value[i]) & 0xff;
87 break;
88 case OR:
89 b = (this.value[i] | value[i]) & 0xff;
90 break;
91 case XOR:
92 b = (this.value[i] ^ value[i]) & 0xff;
93 break;
94 }
95 }
96 return b == 0 ? 1 : 0;
97 }
98 }
99