View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.filter;
19  
20  import java.util.ArrayList;
21  import java.util.Arrays;
22  import java.util.Comparator;
23  import java.util.List;
24  import java.util.Objects;
25  import java.util.PriorityQueue;
26  
27  import org.apache.hadoop.hbase.Cell;
28  import org.apache.hadoop.hbase.KeyValueUtil;
29  import org.apache.hadoop.hbase.classification.InterfaceAudience;
30  import org.apache.hadoop.hbase.classification.InterfaceStability;
31  import org.apache.hadoop.hbase.exceptions.DeserializationException;
32  import org.apache.hadoop.hbase.protobuf.generated.FilterProtos;
33  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.BytesBytesPair;
34  import org.apache.hadoop.hbase.util.ByteStringer;
35  import org.apache.hadoop.hbase.util.Bytes;
36  import org.apache.hadoop.hbase.util.Pair;
37  import org.apache.hadoop.hbase.util.UnsafeAccess;
38  import org.apache.hadoop.hbase.util.UnsafeAvailChecker;
39  
40  import com.google.common.annotations.VisibleForTesting;
41  import com.google.protobuf.InvalidProtocolBufferException;
42  
43  /**
44   * This is optimized version of a standard FuzzyRowFilter Filters data based on fuzzy row key.
45   * Performs fast-forwards during scanning. It takes pairs (row key, fuzzy info) to match row keys.
46   * Where fuzzy info is a byte array with 0 or 1 as its values:
47   * <ul>
48   * <li>0 - means that this byte in provided row key is fixed, i.e. row key's byte at same position
49   * must match</li>
50   * <li>1 - means that this byte in provided row key is NOT fixed, i.e. row key's byte at this
51   * position can be different from the one in provided row key</li>
52   * </ul>
53   * Example: Let's assume row key format is userId_actionId_year_month. Length of userId is fixed and
54   * is 4, length of actionId is 2 and year and month are 4 and 2 bytes long respectively. Let's
55   * assume that we need to fetch all users that performed certain action (encoded as "99") in Jan of
56   * any year. Then the pair (row key, fuzzy info) would be the following: row key = "????_99_????_01"
57   * (one can use any value instead of "?") fuzzy info =
58   * "\x01\x01\x01\x01\x00\x00\x00\x00\x01\x01\x01\x01\x00\x00\x00" I.e. fuzzy info tells the matching
59   * mask is "????_99_????_01", where at ? can be any value.
60   */
61  @InterfaceAudience.Public
62  @InterfaceStability.Evolving
63  public class FuzzyRowFilter extends FilterBase {
64    private static final boolean UNSAFE_UNALIGNED = UnsafeAvailChecker.unaligned();
65    private List<Pair<byte[], byte[]>> fuzzyKeysData;
66    private boolean done = false;
67  
68    /**
69     * The index of a last successfully found matching fuzzy string (in fuzzyKeysData). We will start
70     * matching next KV with this one. If they do not match then we will return back to the one-by-one
71     * iteration over fuzzyKeysData.
72     */
73    private int lastFoundIndex = -1;
74  
75    /**
76     * Row tracker (keeps all next rows after SEEK_NEXT_USING_HINT was returned)
77     */
78    private RowTracker tracker;
79  
80    public FuzzyRowFilter(List<Pair<byte[], byte[]>> fuzzyKeysData) {
81      List<Pair<byte[], byte[]>> fuzzyKeyDataCopy = new ArrayList<>(fuzzyKeysData.size());
82  
83      for (Pair<byte[], byte[]> aFuzzyKeysData : fuzzyKeysData) {
84        if (aFuzzyKeysData.getFirst().length != aFuzzyKeysData.getSecond().length) {
85          Pair<String, String> readable =
86            new Pair<>(Bytes.toStringBinary(aFuzzyKeysData.getFirst()), Bytes.toStringBinary(aFuzzyKeysData.getSecond()));
87          throw new IllegalArgumentException("Fuzzy pair lengths do not match: " + readable);
88        }
89  
90        Pair<byte[], byte[]> p = new Pair<>();
91        // create a copy of pair bytes so that they are not modified by the filter.
92        p.setFirst(Arrays.copyOf(aFuzzyKeysData.getFirst(), aFuzzyKeysData.getFirst().length));
93        p.setSecond(Arrays.copyOf(aFuzzyKeysData.getSecond(), aFuzzyKeysData.getSecond().length));
94  
95        // update mask ( 0 -> -1 (0xff), 1 -> 2)
96        p.setSecond(preprocessMask(p.getSecond()));
97        preprocessSearchKey(p);
98  
99        fuzzyKeyDataCopy.add(p);
100     }
101     this.fuzzyKeysData = fuzzyKeyDataCopy;
102     this.tracker = new RowTracker();
103   }
104 
105   private void preprocessSearchKey(Pair<byte[], byte[]> p) {
106     if (!UNSAFE_UNALIGNED) {
107       return;
108     }
109     byte[] key = p.getFirst();
110     byte[] mask = p.getSecond();
111     for (int i = 0; i < mask.length; i++) {
112       // set non-fixed part of a search key to 0.
113       if (mask[i] == 2) {
114         key[i] = 0;
115       }
116     }
117   }
118 
119   /**
120    * We need to preprocess mask array, as since we treat 2's as unfixed positions and -1 (0xff) as
121    * fixed positions
122    * @param mask
123    * @return mask array
124    */
125   private byte[] preprocessMask(byte[] mask) {
126     if (!UNSAFE_UNALIGNED) {
127       return mask;
128     }
129     if (isPreprocessedMask(mask)) return mask;
130     for (int i = 0; i < mask.length; i++) {
131       if (mask[i] == 0) {
132         mask[i] = -1; // 0 -> -1
133       } else if (mask[i] == 1) {
134         mask[i] = 2;// 1 -> 2
135       }
136     }
137     return mask;
138   }
139 
140   private boolean isPreprocessedMask(byte[] mask) {
141     for (int i = 0; i < mask.length; i++) {
142       if (mask[i] != -1 && mask[i] != 2) {
143         return false;
144       }
145     }
146     return true;
147   }
148 
149   @Override
150   public ReturnCode filterKeyValue(Cell c) {
151     final int startIndex = lastFoundIndex >= 0 ? lastFoundIndex : 0;
152     final int size = fuzzyKeysData.size();
153     for (int i = startIndex; i < size + startIndex; i++) {
154       final int index = i % size;
155       Pair<byte[], byte[]> fuzzyData = fuzzyKeysData.get(index);
156       // This shift is idempotent - always end up with 0 and -1 as mask values.
157       for (int j = 0; j < fuzzyData.getSecond().length; j++) {
158         fuzzyData.getSecond()[j] >>= 2;
159       }
160       SatisfiesCode satisfiesCode =
161           satisfies(isReversed(), c.getRowArray(), c.getRowOffset(), c.getRowLength(),
162             fuzzyData.getFirst(), fuzzyData.getSecond());
163       if (satisfiesCode == SatisfiesCode.YES) {
164         lastFoundIndex = index;
165         return ReturnCode.INCLUDE;
166       }
167     }
168     // NOT FOUND -> seek next using hint
169     lastFoundIndex = -1;
170 
171     return ReturnCode.SEEK_NEXT_USING_HINT;
172 
173   }
174 
175   @Override
176   public Cell getNextCellHint(Cell currentCell) {
177     boolean result = tracker.updateTracker(currentCell);
178     if (result == false) {
179       done = true;
180       return null;
181     }
182     byte[] nextRowKey = tracker.nextRow();
183     return KeyValueUtil.createFirstOnRow(nextRowKey);
184   }
185 
186   /**
187    * If we have multiple fuzzy keys, row tracker should improve overall performance. It calculates
188    * all next rows (one per every fuzzy key) and put them (the fuzzy key is bundled) into a priority
189    * queue so that the smallest row key always appears at queue head, which helps to decide the
190    * "Next Cell Hint". As scanning going on, the number of candidate rows in the RowTracker will
191    * remain the size of fuzzy keys until some of the fuzzy keys won't possibly have matches any
192    * more.
193    */
194   private class RowTracker {
195     private final PriorityQueue<Pair<byte[], Pair<byte[], byte[]>>> nextRows;
196     private boolean initialized = false;
197 
198     RowTracker() {
199       nextRows =
200           new PriorityQueue<Pair<byte[], Pair<byte[], byte[]>>>(fuzzyKeysData.size(),
201               new Comparator<Pair<byte[], Pair<byte[], byte[]>>>() {
202                 @Override
203                 public int compare(Pair<byte[], Pair<byte[], byte[]>> o1,
204                     Pair<byte[], Pair<byte[], byte[]>> o2) {
205                   return isReversed()? Bytes.compareTo(o2.getFirst(), o1.getFirst()):
206                     Bytes.compareTo(o1.getFirst(), o2.getFirst());
207                 }
208               });
209     }
210 
211     byte[] nextRow() {
212       if (nextRows.isEmpty()) {
213         throw new IllegalStateException(
214             "NextRows should not be empty, make sure to call nextRow() after updateTracker() return true");
215       } else {
216         return nextRows.peek().getFirst();
217       }
218     }
219 
220     boolean updateTracker(Cell currentCell) {
221       if (!initialized) {
222         for (Pair<byte[], byte[]> fuzzyData : fuzzyKeysData) {
223           updateWith(currentCell, fuzzyData);
224         }
225         initialized = true;
226       } else {
227         while (!nextRows.isEmpty() && !lessThan(currentCell, nextRows.peek().getFirst())) {
228           Pair<byte[], Pair<byte[], byte[]>> head = nextRows.poll();
229           Pair<byte[], byte[]> fuzzyData = head.getSecond();
230           updateWith(currentCell, fuzzyData);
231         }
232       }
233       return !nextRows.isEmpty();
234     }
235 
236     boolean lessThan(Cell currentCell, byte[] nextRowKey) {
237       int compareResult =
238           Bytes.compareTo(currentCell.getRowArray(), currentCell.getRowOffset(),
239             currentCell.getRowLength(), nextRowKey, 0, nextRowKey.length);
240       return (!isReversed() && compareResult < 0) || (isReversed() && compareResult > 0);
241     }
242 
243     void updateWith(Cell currentCell, Pair<byte[], byte[]> fuzzyData) {
244       byte[] nextRowKeyCandidate =
245           getNextForFuzzyRule(isReversed(), currentCell.getRowArray(), currentCell.getRowOffset(),
246             currentCell.getRowLength(), fuzzyData.getFirst(), fuzzyData.getSecond());
247       if (nextRowKeyCandidate != null) {
248         nextRows.add(new Pair<byte[], Pair<byte[], byte[]>>(nextRowKeyCandidate, fuzzyData));
249       }
250     }
251 
252   }
253 
254   @Override
255   public boolean filterAllRemaining() {
256     return done;
257   }
258 
259   /**
260    * @return The filter serialized using pb
261    */
262   @Override
263   public byte[] toByteArray() {
264     FilterProtos.FuzzyRowFilter.Builder builder = FilterProtos.FuzzyRowFilter.newBuilder();
265     for (Pair<byte[], byte[]> fuzzyData : fuzzyKeysData) {
266       BytesBytesPair.Builder bbpBuilder = BytesBytesPair.newBuilder();
267       bbpBuilder.setFirst(ByteStringer.wrap(fuzzyData.getFirst()));
268       bbpBuilder.setSecond(ByteStringer.wrap(fuzzyData.getSecond()));
269       builder.addFuzzyKeysData(bbpBuilder);
270     }
271     return builder.build().toByteArray();
272   }
273 
274   /**
275    * @param pbBytes A pb serialized {@link FuzzyRowFilter} instance
276    * @return An instance of {@link FuzzyRowFilter} made from <code>bytes</code>
277    * @throws DeserializationException
278    * @see #toByteArray
279    */
280   public static FuzzyRowFilter parseFrom(final byte[] pbBytes) throws DeserializationException {
281     FilterProtos.FuzzyRowFilter proto;
282     try {
283       proto = FilterProtos.FuzzyRowFilter.parseFrom(pbBytes);
284     } catch (InvalidProtocolBufferException e) {
285       throw new DeserializationException(e);
286     }
287     int count = proto.getFuzzyKeysDataCount();
288     ArrayList<Pair<byte[], byte[]>> fuzzyKeysData = new ArrayList<Pair<byte[], byte[]>>(count);
289     for (int i = 0; i < count; ++i) {
290       BytesBytesPair current = proto.getFuzzyKeysData(i);
291       byte[] keyBytes = current.getFirst().toByteArray();
292       byte[] keyMeta = current.getSecond().toByteArray();
293       fuzzyKeysData.add(new Pair<byte[], byte[]>(keyBytes, keyMeta));
294     }
295     return new FuzzyRowFilter(fuzzyKeysData);
296   }
297 
298   @Override
299   public String toString() {
300     final StringBuilder sb = new StringBuilder();
301     sb.append("FuzzyRowFilter");
302     sb.append("{fuzzyKeysData=");
303     for (Pair<byte[], byte[]> fuzzyData : fuzzyKeysData) {
304       sb.append('{').append(Bytes.toStringBinary(fuzzyData.getFirst())).append(":");
305       sb.append(Bytes.toStringBinary(fuzzyData.getSecond())).append('}');
306     }
307     sb.append("}, ");
308     return sb.toString();
309   }
310 
311   // Utility methods
312 
313   static enum SatisfiesCode {
314     /** row satisfies fuzzy rule */
315     YES,
316     /** row doesn't satisfy fuzzy rule, but there's possible greater row that does */
317     NEXT_EXISTS,
318     /** row doesn't satisfy fuzzy rule and there's no greater row that does */
319     NO_NEXT
320   }
321 
322   @VisibleForTesting
323   static SatisfiesCode satisfies(byte[] row, byte[] fuzzyKeyBytes, byte[] fuzzyKeyMeta) {
324     return satisfies(false, row, 0, row.length, fuzzyKeyBytes, fuzzyKeyMeta);
325   }
326 
327   @VisibleForTesting
328   static SatisfiesCode satisfies(boolean reverse, byte[] row, byte[] fuzzyKeyBytes,
329       byte[] fuzzyKeyMeta) {
330     return satisfies(reverse, row, 0, row.length, fuzzyKeyBytes, fuzzyKeyMeta);
331   }
332 
333   static SatisfiesCode satisfies(boolean reverse, byte[] row, int offset, int length,
334       byte[] fuzzyKeyBytes, byte[] fuzzyKeyMeta) {
335 
336     if (!UNSAFE_UNALIGNED) {
337       return satisfiesNoUnsafe(reverse, row, offset, length, fuzzyKeyBytes, fuzzyKeyMeta);
338     }
339 
340     if (row == null) {
341       // do nothing, let scan to proceed
342       return SatisfiesCode.YES;
343     }
344     length = Math.min(length, fuzzyKeyBytes.length);
345     int numWords = length / Bytes.SIZEOF_LONG;
346     int offsetAdj = offset + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET;
347 
348     int j = numWords << 3; // numWords * SIZEOF_LONG;
349 
350     for (int i = 0; i < j; i += Bytes.SIZEOF_LONG) {
351 
352       long fuzzyBytes =
353           UnsafeAccess.theUnsafe.getLong(fuzzyKeyBytes, UnsafeAccess.BYTE_ARRAY_BASE_OFFSET
354               + (long) i);
355       long fuzzyMeta =
356           UnsafeAccess.theUnsafe.getLong(fuzzyKeyMeta, UnsafeAccess.BYTE_ARRAY_BASE_OFFSET
357               + (long) i);
358       long rowValue = UnsafeAccess.theUnsafe.getLong(row, offsetAdj + (long) i);
359       if ((rowValue & fuzzyMeta) != (fuzzyBytes)) {
360         // We always return NEXT_EXISTS
361         return SatisfiesCode.NEXT_EXISTS;
362       }
363     }
364 
365     int off = j;
366 
367     if (length - off >= Bytes.SIZEOF_INT) {
368       int fuzzyBytes =
369           UnsafeAccess.theUnsafe.getInt(fuzzyKeyBytes, UnsafeAccess.BYTE_ARRAY_BASE_OFFSET
370               + (long) off);
371       int fuzzyMeta =
372           UnsafeAccess.theUnsafe.getInt(fuzzyKeyMeta, UnsafeAccess.BYTE_ARRAY_BASE_OFFSET
373               + (long) off);
374       int rowValue = UnsafeAccess.theUnsafe.getInt(row, offsetAdj + (long) off);
375       if ((rowValue & fuzzyMeta) != (fuzzyBytes)) {
376         // We always return NEXT_EXISTS
377         return SatisfiesCode.NEXT_EXISTS;
378       }
379       off += Bytes.SIZEOF_INT;
380     }
381 
382     if (length - off >= Bytes.SIZEOF_SHORT) {
383       short fuzzyBytes =
384           UnsafeAccess.theUnsafe.getShort(fuzzyKeyBytes, UnsafeAccess.BYTE_ARRAY_BASE_OFFSET
385               + (long) off);
386       short fuzzyMeta =
387           UnsafeAccess.theUnsafe.getShort(fuzzyKeyMeta, UnsafeAccess.BYTE_ARRAY_BASE_OFFSET
388               + (long) off);
389       short rowValue = UnsafeAccess.theUnsafe.getShort(row, offsetAdj + (long) off);
390       if ((rowValue & fuzzyMeta) != (fuzzyBytes)) {
391         // We always return NEXT_EXISTS
392         // even if it does not (in this case getNextForFuzzyRule
393         // will return null)
394         return SatisfiesCode.NEXT_EXISTS;
395       }
396       off += Bytes.SIZEOF_SHORT;
397     }
398 
399     if (length - off >= Bytes.SIZEOF_BYTE) {
400       int fuzzyBytes = fuzzyKeyBytes[off] & 0xff;
401       int fuzzyMeta = fuzzyKeyMeta[off] & 0xff;
402       int rowValue = row[offset + off] & 0xff;
403       if ((rowValue & fuzzyMeta) != (fuzzyBytes)) {
404         // We always return NEXT_EXISTS
405         return SatisfiesCode.NEXT_EXISTS;
406       }
407     }
408     return SatisfiesCode.YES;
409   }
410 
411   static SatisfiesCode satisfiesNoUnsafe(boolean reverse, byte[] row, int offset, int length,
412       byte[] fuzzyKeyBytes, byte[] fuzzyKeyMeta) {
413     if (row == null) {
414       // do nothing, let scan to proceed
415       return SatisfiesCode.YES;
416     }
417 
418     Order order = Order.orderFor(reverse);
419     boolean nextRowKeyCandidateExists = false;
420 
421     for (int i = 0; i < fuzzyKeyMeta.length && i < length; i++) {
422       // First, checking if this position is fixed and not equals the given one
423       boolean byteAtPositionFixed = fuzzyKeyMeta[i] == 0;
424       boolean fixedByteIncorrect = byteAtPositionFixed && fuzzyKeyBytes[i] != row[i + offset];
425       if (fixedByteIncorrect) {
426         // in this case there's another row that satisfies fuzzy rule and bigger than this row
427         if (nextRowKeyCandidateExists) {
428           return SatisfiesCode.NEXT_EXISTS;
429         }
430 
431         // If this row byte is less than fixed then there's a byte array bigger than
432         // this row and which satisfies the fuzzy rule. Otherwise there's no such byte array:
433         // this row is simply bigger than any byte array that satisfies the fuzzy rule
434         boolean rowByteLessThanFixed = (row[i + offset] & 0xFF) < (fuzzyKeyBytes[i] & 0xFF);
435         if (rowByteLessThanFixed && !reverse) {
436           return SatisfiesCode.NEXT_EXISTS;
437         } else if (!rowByteLessThanFixed && reverse) {
438           return SatisfiesCode.NEXT_EXISTS;
439         } else {
440           return SatisfiesCode.NO_NEXT;
441         }
442       }
443 
444       // Second, checking if this position is not fixed and byte value is not the biggest. In this
445       // case there's a byte array bigger than this row and which satisfies the fuzzy rule. To get
446       // bigger byte array that satisfies the rule we need to just increase this byte
447       // (see the code of getNextForFuzzyRule below) by one.
448       // Note: if non-fixed byte is already at biggest value, this doesn't allow us to say there's
449       // bigger one that satisfies the rule as it can't be increased.
450       if (fuzzyKeyMeta[i] == 1 && !order.isMax(fuzzyKeyBytes[i])) {
451         nextRowKeyCandidateExists = true;
452       }
453     }
454     return SatisfiesCode.YES;
455   }
456 
457   @VisibleForTesting
458   static byte[] getNextForFuzzyRule(byte[] row, byte[] fuzzyKeyBytes, byte[] fuzzyKeyMeta) {
459     return getNextForFuzzyRule(false, row, 0, row.length, fuzzyKeyBytes, fuzzyKeyMeta);
460   }
461 
462   @VisibleForTesting
463   static byte[] getNextForFuzzyRule(boolean reverse, byte[] row, byte[] fuzzyKeyBytes,
464       byte[] fuzzyKeyMeta) {
465     return getNextForFuzzyRule(reverse, row, 0, row.length, fuzzyKeyBytes, fuzzyKeyMeta);
466   }
467 
468   /** Abstracts directional comparisons based on scan direction. */
469   private enum Order {
470     ASC {
471       @Override
472       public boolean lt(int lhs, int rhs) {
473         return lhs < rhs;
474       }
475 
476       @Override
477       public boolean gt(int lhs, int rhs) {
478         return lhs > rhs;
479       }
480 
481       @Override
482       public byte inc(byte val) {
483         // TODO: what about over/underflow?
484         return (byte) (val + 1);
485       }
486 
487       @Override
488       public boolean isMax(byte val) {
489         return val == (byte) 0xff;
490       }
491 
492       @Override
493       public byte min() {
494         return 0;
495       }
496     },
497     DESC {
498       @Override
499       public boolean lt(int lhs, int rhs) {
500         return lhs > rhs;
501       }
502 
503       @Override
504       public boolean gt(int lhs, int rhs) {
505         return lhs < rhs;
506       }
507 
508       @Override
509       public byte inc(byte val) {
510         // TODO: what about over/underflow?
511         return (byte) (val - 1);
512       }
513 
514       @Override
515       public boolean isMax(byte val) {
516         return val == 0;
517       }
518 
519       @Override
520       public byte min() {
521         return (byte) 0xFF;
522       }
523     };
524 
525     public static Order orderFor(boolean reverse) {
526       return reverse ? DESC : ASC;
527     }
528 
529     /** Returns true when {@code lhs < rhs}. */
530     public abstract boolean lt(int lhs, int rhs);
531 
532     /** Returns true when {@code lhs > rhs}. */
533     public abstract boolean gt(int lhs, int rhs);
534 
535     /** Returns {@code val} incremented by 1. */
536     public abstract byte inc(byte val);
537 
538     /** Return true when {@code val} is the maximum value */
539     public abstract boolean isMax(byte val);
540 
541     /** Return the minimum value according to this ordering scheme. */
542     public abstract byte min();
543   }
544 
545   /**
546    * @return greater byte array than given (row) which satisfies the fuzzy rule if it exists, null
547    *         otherwise
548    */
549   @VisibleForTesting
550   static byte[] getNextForFuzzyRule(boolean reverse, byte[] row, int offset, int length,
551       byte[] fuzzyKeyBytes, byte[] fuzzyKeyMeta) {
552     // To find out the next "smallest" byte array that satisfies fuzzy rule and "greater" than
553     // the given one we do the following:
554     // 1. setting values on all "fixed" positions to the values from fuzzyKeyBytes
555     // 2. if during the first step given row did not increase, then we increase the value at
556     // the first "non-fixed" position (where it is not maximum already)
557 
558     // It is easier to perform this by using fuzzyKeyBytes copy and setting "non-fixed" position
559     // values than otherwise.
560     byte[] result =
561         Arrays.copyOf(fuzzyKeyBytes, length > fuzzyKeyBytes.length ? length : fuzzyKeyBytes.length);
562     if (reverse && length > fuzzyKeyBytes.length) {
563       // we need trailing 0xff's instead of trailing 0x00's
564       for (int i = fuzzyKeyBytes.length; i < result.length; i++) {
565         result[i] = (byte) 0xFF;
566       }
567     }
568     int toInc = -1;
569     final Order order = Order.orderFor(reverse);
570 
571     boolean increased = false;
572     for (int i = 0; i < result.length; i++) {
573       if (i >= fuzzyKeyMeta.length || fuzzyKeyMeta[i] == 0 /* non-fixed */) {
574         result[i] = row[offset + i];
575         if (!order.isMax(row[offset + i])) {
576           // this is "non-fixed" position and is not at max value, hence we can increase it
577           toInc = i;
578         }
579       } else if (i < fuzzyKeyMeta.length && fuzzyKeyMeta[i] == -1 /* fixed */) {
580         if (order.lt((row[i + offset] & 0xFF), (fuzzyKeyBytes[i] & 0xFF))) {
581           // if setting value for any fixed position increased the original array,
582           // we are OK
583           increased = true;
584           break;
585         }
586 
587         if (order.gt((row[i + offset] & 0xFF), (fuzzyKeyBytes[i] & 0xFF))) {
588           // if setting value for any fixed position makes array "smaller", then just stop:
589           // in case we found some non-fixed position to increase we will do it, otherwise
590           // there's no "next" row key that satisfies fuzzy rule and "greater" than given row
591           break;
592         }
593       }
594     }
595 
596     if (!increased) {
597       if (toInc < 0) {
598         return null;
599       }
600       result[toInc] = order.inc(result[toInc]);
601 
602       // Setting all "non-fixed" positions to zeroes to the right of the one we increased so
603       // that found "next" row key is the smallest possible
604       for (int i = toInc + 1; i < result.length; i++) {
605         if (i >= fuzzyKeyMeta.length || fuzzyKeyMeta[i] == 0 /* non-fixed */) {
606           result[i] = order.min();
607         }
608       }
609     }
610 
611     return reverse? result: trimTrailingZeroes(result, fuzzyKeyMeta, toInc);
612   }
613 
614   /**
615    * For forward scanner, next cell hint should  not contain any trailing zeroes
616    * unless they are part of fuzzyKeyMeta
617    * hint = '\x01\x01\x01\x00\x00'
618    * will skip valid row '\x01\x01\x01'
619    * 
620    * @param result
621    * @param fuzzyKeyMeta
622    * @param toInc - position of incremented byte
623    * @return trimmed version of result
624    */
625   
626   private static byte[] trimTrailingZeroes(byte[] result, byte[] fuzzyKeyMeta, int toInc) {
627     int off = fuzzyKeyMeta.length >= result.length? result.length -1:
628            fuzzyKeyMeta.length -1;  
629     for( ; off >= 0; off--){
630       if(fuzzyKeyMeta[off] != 0) break;
631     }
632     if (off < toInc)  off = toInc;
633     byte[] retValue = new byte[off+1];
634     System.arraycopy(result, 0, retValue, 0, retValue.length);
635     return retValue;
636   }
637 
638   /**
639    * @return true if and only if the fields of the filter that are serialized are equal to the
640    *         corresponding fields in other. Used for testing.
641    */
642   @Override
643   boolean areSerializedFieldsEqual(Filter o) {
644     if (o == this) return true;
645     if (!(o instanceof FuzzyRowFilter)) return false;
646 
647     FuzzyRowFilter other = (FuzzyRowFilter) o;
648     if (this.fuzzyKeysData.size() != other.fuzzyKeysData.size()) return false;
649     for (int i = 0; i < fuzzyKeysData.size(); ++i) {
650       Pair<byte[], byte[]> thisData = this.fuzzyKeysData.get(i);
651       Pair<byte[], byte[]> otherData = other.fuzzyKeysData.get(i);
652       if (!(Bytes.equals(thisData.getFirst(), otherData.getFirst()) && Bytes.equals(
653         thisData.getSecond(), otherData.getSecond()))) {
654         return false;
655       }
656     }
657     return true;
658   }
659 
660   @Override
661   public boolean equals(Object obj) {
662     return obj instanceof Filter && areSerializedFieldsEqual((Filter) obj);
663   }
664 
665   @Override
666   public int hashCode() {
667     return Objects.hash(this.fuzzyKeysData);
668   }
669 }