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