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