001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.filter;
019
020import java.util.ArrayList;
021import java.util.Arrays;
022import java.util.Comparator;
023import java.util.List;
024import java.util.Objects;
025import java.util.PriorityQueue;
026
027import org.apache.hadoop.hbase.Cell;
028import org.apache.hadoop.hbase.CellComparator;
029import org.apache.hadoop.hbase.PrivateCellUtil;
030import org.apache.yetus.audience.InterfaceAudience;
031import org.apache.hadoop.hbase.exceptions.DeserializationException;
032import org.apache.hbase.thirdparty.com.google.protobuf.InvalidProtocolBufferException;
033import org.apache.hbase.thirdparty.com.google.protobuf.UnsafeByteOperations;
034import org.apache.hadoop.hbase.shaded.protobuf.generated.FilterProtos;
035import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.BytesBytesPair;
036import org.apache.hadoop.hbase.util.Bytes;
037import org.apache.hadoop.hbase.util.Pair;
038import org.apache.hadoop.hbase.util.UnsafeAvailChecker;
039
040import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
041
042/**
043 * This is optimized version of a standard FuzzyRowFilter Filters data based on fuzzy row key.
044 * Performs fast-forwards during scanning. It takes pairs (row key, fuzzy info) to match row keys.
045 * Where fuzzy info is a byte array with 0 or 1 as its values:
046 * <ul>
047 * <li>0 - means that this byte in provided row key is fixed, i.e. row key's byte at same position
048 * must match</li>
049 * <li>1 - means that this byte in provided row key is NOT fixed, i.e. row key's byte at this
050 * position can be different from the one in provided row key</li>
051 * </ul>
052 * Example: Let's assume row key format is userId_actionId_year_month. Length of userId is fixed and
053 * is 4, length of actionId is 2 and year and month are 4 and 2 bytes long respectively. Let's
054 * assume that we need to fetch all users that performed certain action (encoded as "99") in Jan of
055 * any year. Then the pair (row key, fuzzy info) would be the following: row key = "????_99_????_01"
056 * (one can use any value instead of "?") fuzzy info =
057 * "\x01\x01\x01\x01\x00\x00\x00\x00\x01\x01\x01\x01\x00\x00\x00" I.e. fuzzy info tells the matching
058 * mask is "????_99_????_01", where at ? can be any value.
059 */
060@InterfaceAudience.Public
061public class FuzzyRowFilter extends FilterBase {
062  private static final boolean UNSAFE_UNALIGNED = UnsafeAvailChecker.unaligned();
063  private List<Pair<byte[], byte[]>> fuzzyKeysData;
064  private boolean done = false;
065
066  /**
067   * The index of a last successfully found matching fuzzy string (in fuzzyKeysData). We will start
068   * matching next KV with this one. If they do not match then we will return back to the one-by-one
069   * iteration over fuzzyKeysData.
070   */
071  private int lastFoundIndex = -1;
072
073  /**
074   * Row tracker (keeps all next rows after SEEK_NEXT_USING_HINT was returned)
075   */
076  private RowTracker tracker;
077
078  public FuzzyRowFilter(List<Pair<byte[], byte[]>> fuzzyKeysData) {
079    List<Pair<byte[], byte[]>> fuzzyKeyDataCopy = new ArrayList<>(fuzzyKeysData.size());
080
081    for (Pair<byte[], byte[]> aFuzzyKeysData : fuzzyKeysData) {
082      if (aFuzzyKeysData.getFirst().length != aFuzzyKeysData.getSecond().length) {
083        Pair<String, String> readable =
084          new Pair<>(Bytes.toStringBinary(aFuzzyKeysData.getFirst()), Bytes.toStringBinary(aFuzzyKeysData.getSecond()));
085        throw new IllegalArgumentException("Fuzzy pair lengths do not match: " + readable);
086      }
087
088      Pair<byte[], byte[]> p = new Pair<>();
089      // create a copy of pair bytes so that they are not modified by the filter.
090      p.setFirst(Arrays.copyOf(aFuzzyKeysData.getFirst(), aFuzzyKeysData.getFirst().length));
091      p.setSecond(Arrays.copyOf(aFuzzyKeysData.getSecond(), aFuzzyKeysData.getSecond().length));
092
093      // update mask ( 0 -> -1 (0xff), 1 -> 2)
094      p.setSecond(preprocessMask(p.getSecond()));
095      preprocessSearchKey(p);
096
097      fuzzyKeyDataCopy.add(p);
098    }
099    this.fuzzyKeysData = fuzzyKeyDataCopy;
100    this.tracker = new RowTracker();
101  }
102
103
104  private void preprocessSearchKey(Pair<byte[], byte[]> p) {
105    if (!UNSAFE_UNALIGNED) {
106      // do nothing
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      // do nothing
128      return mask;
129    }
130    if (isPreprocessedMask(mask)) return mask;
131    for (int i = 0; i < mask.length; i++) {
132      if (mask[i] == 0) {
133        mask[i] = -1; // 0 -> -1
134      } else if (mask[i] == 1) {
135        mask[i] = 2;// 1 -> 2
136      }
137    }
138    return mask;
139  }
140
141  private boolean isPreprocessedMask(byte[] mask) {
142    for (int i = 0; i < mask.length; i++) {
143      if (mask[i] != -1 && mask[i] != 2) {
144        return false;
145      }
146    }
147    return true;
148  }
149
150  @Override
151  public ReturnCode filterCell(final Cell c) {
152    final int startIndex = lastFoundIndex >= 0 ? lastFoundIndex : 0;
153    final int size = fuzzyKeysData.size();
154    for (int i = startIndex; i < size + startIndex; i++) {
155      final int index = i % size;
156      Pair<byte[], byte[]> fuzzyData = fuzzyKeysData.get(index);
157      // This shift is idempotent - always end up with 0 and -1 as mask values.
158      for (int j = 0; j < fuzzyData.getSecond().length; j++) {
159        fuzzyData.getSecond()[j] >>= 2;
160      }
161      SatisfiesCode satisfiesCode =
162          satisfies(isReversed(), c.getRowArray(), c.getRowOffset(), c.getRowLength(),
163            fuzzyData.getFirst(), fuzzyData.getSecond());
164      if (satisfiesCode == SatisfiesCode.YES) {
165        lastFoundIndex = index;
166        return ReturnCode.INCLUDE;
167      }
168    }
169    // NOT FOUND -> seek next using hint
170    lastFoundIndex = -1;
171
172    return ReturnCode.SEEK_NEXT_USING_HINT;
173
174  }
175
176  @Override
177  public Cell getNextCellHint(Cell currentCell) {
178    boolean result = tracker.updateTracker(currentCell);
179    if (result == false) {
180      done = true;
181      return null;
182    }
183    byte[] nextRowKey = tracker.nextRow();
184    return PrivateCellUtil.createFirstOnRow(nextRowKey, 0, (short) nextRowKey.length);
185  }
186
187  /**
188   * If we have multiple fuzzy keys, row tracker should improve overall performance. It calculates
189   * all next rows (one per every fuzzy key) and put them (the fuzzy key is bundled) into a priority
190   * queue so that the smallest row key always appears at queue head, which helps to decide the
191   * "Next Cell Hint". As scanning going on, the number of candidate rows in the RowTracker will
192   * remain the size of fuzzy keys until some of the fuzzy keys won't possibly have matches any
193   * more.
194   */
195  private class RowTracker {
196    private final PriorityQueue<Pair<byte[], Pair<byte[], byte[]>>> nextRows;
197    private boolean initialized = false;
198
199    RowTracker() {
200      nextRows = new PriorityQueue<>(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 = CellComparator.getInstance().compareRows(currentCell, nextRowKey, 0, nextRowKey.length);
238      return (!isReversed() && compareResult < 0) || (isReversed() && compareResult > 0);
239    }
240
241    void updateWith(Cell currentCell, Pair<byte[], byte[]> fuzzyData) {
242      byte[] nextRowKeyCandidate =
243          getNextForFuzzyRule(isReversed(), currentCell.getRowArray(), currentCell.getRowOffset(),
244            currentCell.getRowLength(), fuzzyData.getFirst(), fuzzyData.getSecond());
245      if (nextRowKeyCandidate != null) {
246        nextRows.add(new Pair<>(nextRowKeyCandidate, fuzzyData));
247      }
248    }
249
250  }
251
252  @Override
253  public boolean filterAllRemaining() {
254    return done;
255  }
256
257  /**
258   * @return The filter serialized using pb
259   */
260  @Override
261  public byte[] toByteArray() {
262    FilterProtos.FuzzyRowFilter.Builder builder = FilterProtos.FuzzyRowFilter.newBuilder();
263    for (Pair<byte[], byte[]> fuzzyData : fuzzyKeysData) {
264      BytesBytesPair.Builder bbpBuilder = BytesBytesPair.newBuilder();
265      bbpBuilder.setFirst(UnsafeByteOperations.unsafeWrap(fuzzyData.getFirst()));
266      bbpBuilder.setSecond(UnsafeByteOperations.unsafeWrap(fuzzyData.getSecond()));
267      builder.addFuzzyKeysData(bbpBuilder);
268    }
269    return builder.build().toByteArray();
270  }
271
272  /**
273   * @param pbBytes A pb serialized {@link FuzzyRowFilter} instance
274   * @return An instance of {@link FuzzyRowFilter} made from <code>bytes</code>
275   * @throws DeserializationException
276   * @see #toByteArray
277   */
278  public static FuzzyRowFilter parseFrom(final byte[] pbBytes) throws DeserializationException {
279    FilterProtos.FuzzyRowFilter proto;
280    try {
281      proto = FilterProtos.FuzzyRowFilter.parseFrom(pbBytes);
282    } catch (InvalidProtocolBufferException e) {
283      throw new DeserializationException(e);
284    }
285    int count = proto.getFuzzyKeysDataCount();
286    ArrayList<Pair<byte[], byte[]>> fuzzyKeysData = new ArrayList<>(count);
287    for (int i = 0; i < count; ++i) {
288      BytesBytesPair current = proto.getFuzzyKeysData(i);
289      byte[] keyBytes = current.getFirst().toByteArray();
290      byte[] keyMeta = current.getSecond().toByteArray();
291      fuzzyKeysData.add(new Pair<>(keyBytes, keyMeta));
292    }
293    return new FuzzyRowFilter(fuzzyKeysData);
294  }
295
296  @Override
297  public String toString() {
298    final StringBuilder sb = new StringBuilder();
299    sb.append("FuzzyRowFilter");
300    sb.append("{fuzzyKeysData=");
301    for (Pair<byte[], byte[]> fuzzyData : fuzzyKeysData) {
302      sb.append('{').append(Bytes.toStringBinary(fuzzyData.getFirst())).append(":");
303      sb.append(Bytes.toStringBinary(fuzzyData.getSecond())).append('}');
304    }
305    sb.append("}, ");
306    return sb.toString();
307  }
308
309  // Utility methods
310
311  static enum SatisfiesCode {
312    /** row satisfies fuzzy rule */
313    YES,
314    /** row doesn't satisfy fuzzy rule, but there's possible greater row that does */
315    NEXT_EXISTS,
316    /** row doesn't satisfy fuzzy rule and there's no greater row that does */
317    NO_NEXT
318  }
319
320  @VisibleForTesting
321  static SatisfiesCode satisfies(byte[] row, byte[] fuzzyKeyBytes, byte[] fuzzyKeyMeta) {
322    return satisfies(false, row, 0, row.length, fuzzyKeyBytes, fuzzyKeyMeta);
323  }
324
325  @VisibleForTesting
326  static SatisfiesCode satisfies(boolean reverse, byte[] row, byte[] fuzzyKeyBytes,
327      byte[] fuzzyKeyMeta) {
328    return satisfies(reverse, row, 0, row.length, fuzzyKeyBytes, fuzzyKeyMeta);
329  }
330
331  static SatisfiesCode satisfies(boolean reverse, byte[] row, int offset, int length,
332      byte[] fuzzyKeyBytes, byte[] fuzzyKeyMeta) {
333
334    if (!UNSAFE_UNALIGNED) {
335      return satisfiesNoUnsafe(reverse, row, offset, length, fuzzyKeyBytes, fuzzyKeyMeta);
336    }
337
338    if (row == null) {
339      // do nothing, let scan to proceed
340      return SatisfiesCode.YES;
341    }
342    length = Math.min(length, fuzzyKeyBytes.length);
343    int numWords = length / Bytes.SIZEOF_LONG;
344
345    int j = numWords << 3; // numWords * SIZEOF_LONG;
346
347    for (int i = 0; i < j; i += Bytes.SIZEOF_LONG) {
348      long fuzzyBytes = Bytes.toLong(fuzzyKeyBytes, i);
349      long fuzzyMeta = Bytes.toLong(fuzzyKeyMeta, i);
350      long rowValue = Bytes.toLong(row, offset + i);
351      if ((rowValue & fuzzyMeta) != (fuzzyBytes)) {
352        // We always return NEXT_EXISTS
353        return SatisfiesCode.NEXT_EXISTS;
354      }
355    }
356
357    int off = j;
358
359    if (length - off >= Bytes.SIZEOF_INT) {
360      int fuzzyBytes = Bytes.toInt(fuzzyKeyBytes, off);
361      int fuzzyMeta = Bytes.toInt(fuzzyKeyMeta, off);
362      int rowValue = Bytes.toInt(row, offset + off);
363      if ((rowValue & fuzzyMeta) != (fuzzyBytes)) {
364        // We always return NEXT_EXISTS
365        return SatisfiesCode.NEXT_EXISTS;
366      }
367      off += Bytes.SIZEOF_INT;
368    }
369
370    if (length - off >= Bytes.SIZEOF_SHORT) {
371      short fuzzyBytes = Bytes.toShort(fuzzyKeyBytes, off);
372      short fuzzyMeta = Bytes.toShort(fuzzyKeyMeta, off);
373      short rowValue = Bytes.toShort(row, offset + off);
374      if ((rowValue & fuzzyMeta) != (fuzzyBytes)) {
375        // We always return NEXT_EXISTS
376        // even if it does not (in this case getNextForFuzzyRule
377        // will return null)
378        return SatisfiesCode.NEXT_EXISTS;
379      }
380      off += Bytes.SIZEOF_SHORT;
381    }
382
383    if (length - off >= Bytes.SIZEOF_BYTE) {
384      int fuzzyBytes = fuzzyKeyBytes[off] & 0xff;
385      int fuzzyMeta = fuzzyKeyMeta[off] & 0xff;
386      int rowValue = row[offset + off] & 0xff;
387      if ((rowValue & fuzzyMeta) != (fuzzyBytes)) {
388        // We always return NEXT_EXISTS
389        return SatisfiesCode.NEXT_EXISTS;
390      }
391    }
392    return SatisfiesCode.YES;
393  }
394
395  static SatisfiesCode satisfiesNoUnsafe(boolean reverse, byte[] row, int offset, int length,
396      byte[] fuzzyKeyBytes, byte[] fuzzyKeyMeta) {
397    if (row == null) {
398      // do nothing, let scan to proceed
399      return SatisfiesCode.YES;
400    }
401
402    Order order = Order.orderFor(reverse);
403    boolean nextRowKeyCandidateExists = false;
404
405    for (int i = 0; i < fuzzyKeyMeta.length && i < length; i++) {
406      // First, checking if this position is fixed and not equals the given one
407      boolean byteAtPositionFixed = fuzzyKeyMeta[i] == 0;
408      boolean fixedByteIncorrect = byteAtPositionFixed && fuzzyKeyBytes[i] != row[i + offset];
409      if (fixedByteIncorrect) {
410        // in this case there's another row that satisfies fuzzy rule and bigger than this row
411        if (nextRowKeyCandidateExists) {
412          return SatisfiesCode.NEXT_EXISTS;
413        }
414
415        // If this row byte is less than fixed then there's a byte array bigger than
416        // this row and which satisfies the fuzzy rule. Otherwise there's no such byte array:
417        // this row is simply bigger than any byte array that satisfies the fuzzy rule
418        boolean rowByteLessThanFixed = (row[i + offset] & 0xFF) < (fuzzyKeyBytes[i] & 0xFF);
419        if (rowByteLessThanFixed && !reverse) {
420          return SatisfiesCode.NEXT_EXISTS;
421        } else if (!rowByteLessThanFixed && reverse) {
422          return SatisfiesCode.NEXT_EXISTS;
423        } else {
424          return SatisfiesCode.NO_NEXT;
425        }
426      }
427
428      // Second, checking if this position is not fixed and byte value is not the biggest. In this
429      // case there's a byte array bigger than this row and which satisfies the fuzzy rule. To get
430      // bigger byte array that satisfies the rule we need to just increase this byte
431      // (see the code of getNextForFuzzyRule below) by one.
432      // Note: if non-fixed byte is already at biggest value, this doesn't allow us to say there's
433      // bigger one that satisfies the rule as it can't be increased.
434      if (fuzzyKeyMeta[i] == 1 && !order.isMax(fuzzyKeyBytes[i])) {
435        nextRowKeyCandidateExists = true;
436      }
437    }
438    return SatisfiesCode.YES;
439  }
440
441  @VisibleForTesting
442  static byte[] getNextForFuzzyRule(byte[] row, byte[] fuzzyKeyBytes, byte[] fuzzyKeyMeta) {
443    return getNextForFuzzyRule(false, row, 0, row.length, fuzzyKeyBytes, fuzzyKeyMeta);
444  }
445
446  @VisibleForTesting
447  static byte[] getNextForFuzzyRule(boolean reverse, byte[] row, byte[] fuzzyKeyBytes,
448      byte[] fuzzyKeyMeta) {
449    return getNextForFuzzyRule(reverse, row, 0, row.length, fuzzyKeyBytes, fuzzyKeyMeta);
450  }
451
452  /** Abstracts directional comparisons based on scan direction. */
453  private enum Order {
454    ASC {
455      @Override
456      public boolean lt(int lhs, int rhs) {
457        return lhs < rhs;
458      }
459
460      @Override
461      public boolean gt(int lhs, int rhs) {
462        return lhs > rhs;
463      }
464
465      @Override
466      public byte inc(byte val) {
467        // TODO: what about over/underflow?
468        return (byte) (val + 1);
469      }
470
471      @Override
472      public boolean isMax(byte val) {
473        return val == (byte) 0xff;
474      }
475
476      @Override
477      public byte min() {
478        return 0;
479      }
480    },
481    DESC {
482      @Override
483      public boolean lt(int lhs, int rhs) {
484        return lhs > rhs;
485      }
486
487      @Override
488      public boolean gt(int lhs, int rhs) {
489        return lhs < rhs;
490      }
491
492      @Override
493      public byte inc(byte val) {
494        // TODO: what about over/underflow?
495        return (byte) (val - 1);
496      }
497
498      @Override
499      public boolean isMax(byte val) {
500        return val == 0;
501      }
502
503      @Override
504      public byte min() {
505        return (byte) 0xFF;
506      }
507    };
508
509    public static Order orderFor(boolean reverse) {
510      return reverse ? DESC : ASC;
511    }
512
513    /** Returns true when {@code lhs < rhs}. */
514    public abstract boolean lt(int lhs, int rhs);
515
516    /** Returns true when {@code lhs > rhs}. */
517    public abstract boolean gt(int lhs, int rhs);
518
519    /** Returns {@code val} incremented by 1. */
520    public abstract byte inc(byte val);
521
522    /** Return true when {@code val} is the maximum value */
523    public abstract boolean isMax(byte val);
524
525    /** Return the minimum value according to this ordering scheme. */
526    public abstract byte min();
527  }
528
529  /**
530   * @return greater byte array than given (row) which satisfies the fuzzy rule if it exists, null
531   *         otherwise
532   */
533  @VisibleForTesting
534  static byte[] getNextForFuzzyRule(boolean reverse, byte[] row, int offset, int length,
535      byte[] fuzzyKeyBytes, byte[] fuzzyKeyMeta) {
536    // To find out the next "smallest" byte array that satisfies fuzzy rule and "greater" than
537    // the given one we do the following:
538    // 1. setting values on all "fixed" positions to the values from fuzzyKeyBytes
539    // 2. if during the first step given row did not increase, then we increase the value at
540    // the first "non-fixed" position (where it is not maximum already)
541
542    // It is easier to perform this by using fuzzyKeyBytes copy and setting "non-fixed" position
543    // values than otherwise.
544    byte[] result =
545        Arrays.copyOf(fuzzyKeyBytes, length > fuzzyKeyBytes.length ? length : fuzzyKeyBytes.length);
546    if (reverse && length > fuzzyKeyBytes.length) {
547      // we need trailing 0xff's instead of trailing 0x00's
548      for (int i = fuzzyKeyBytes.length; i < result.length; i++) {
549        result[i] = (byte) 0xFF;
550      }
551    }
552    int toInc = -1;
553    final Order order = Order.orderFor(reverse);
554
555    boolean increased = false;
556    for (int i = 0; i < result.length; i++) {
557      if (i >= fuzzyKeyMeta.length || fuzzyKeyMeta[i] == 0 /* non-fixed */) {
558        result[i] = row[offset + i];
559        if (!order.isMax(row[offset + i])) {
560          // this is "non-fixed" position and is not at max value, hence we can increase it
561          toInc = i;
562        }
563      } else if (i < fuzzyKeyMeta.length && fuzzyKeyMeta[i] == -1 /* fixed */) {
564        if (order.lt((row[i + offset] & 0xFF), (fuzzyKeyBytes[i] & 0xFF))) {
565          // if setting value for any fixed position increased the original array,
566          // we are OK
567          increased = true;
568          break;
569        }
570
571        if (order.gt((row[i + offset] & 0xFF), (fuzzyKeyBytes[i] & 0xFF))) {
572          // if setting value for any fixed position makes array "smaller", then just stop:
573          // in case we found some non-fixed position to increase we will do it, otherwise
574          // there's no "next" row key that satisfies fuzzy rule and "greater" than given row
575          break;
576        }
577      }
578    }
579
580    if (!increased) {
581      if (toInc < 0) {
582        return null;
583      }
584      result[toInc] = order.inc(result[toInc]);
585
586      // Setting all "non-fixed" positions to zeroes to the right of the one we increased so
587      // that found "next" row key is the smallest possible
588      for (int i = toInc + 1; i < result.length; i++) {
589        if (i >= fuzzyKeyMeta.length || fuzzyKeyMeta[i] == 0 /* non-fixed */) {
590          result[i] = order.min();
591        }
592      }
593    }
594
595    return reverse? result: trimTrailingZeroes(result, fuzzyKeyMeta, toInc);
596  }
597
598  /**
599   * For forward scanner, next cell hint should  not contain any trailing zeroes
600   * unless they are part of fuzzyKeyMeta
601   * hint = '\x01\x01\x01\x00\x00'
602   * will skip valid row '\x01\x01\x01'
603   * 
604   * @param result
605   * @param fuzzyKeyMeta
606   * @param toInc - position of incremented byte
607   * @return trimmed version of result
608   */
609  
610  private static byte[] trimTrailingZeroes(byte[] result, byte[] fuzzyKeyMeta, int toInc) {
611    int off = fuzzyKeyMeta.length >= result.length? result.length -1:
612           fuzzyKeyMeta.length -1;  
613    for( ; off >= 0; off--){
614      if(fuzzyKeyMeta[off] != 0) break;
615    }
616    if (off < toInc)  off = toInc;
617    byte[] retValue = new byte[off+1];
618    System.arraycopy(result, 0, retValue, 0, retValue.length);
619    return retValue;
620  }
621
622  /**
623   * @return true if and only if the fields of the filter that are serialized are equal to the
624   *         corresponding fields in other. Used for testing.
625   */
626  @Override
627  boolean areSerializedFieldsEqual(Filter o) {
628    if (o == this) return true;
629    if (!(o instanceof FuzzyRowFilter)) return false;
630
631    FuzzyRowFilter other = (FuzzyRowFilter) o;
632    if (this.fuzzyKeysData.size() != other.fuzzyKeysData.size()) return false;
633    for (int i = 0; i < fuzzyKeysData.size(); ++i) {
634      Pair<byte[], byte[]> thisData = this.fuzzyKeysData.get(i);
635      Pair<byte[], byte[]> otherData = other.fuzzyKeysData.get(i);
636      if (!(Bytes.equals(thisData.getFirst(), otherData.getFirst()) && Bytes.equals(
637        thisData.getSecond(), otherData.getSecond()))) {
638        return false;
639      }
640    }
641    return true;
642  }
643
644  @Override
645  public boolean equals(Object obj) {
646    return obj instanceof Filter && areSerializedFieldsEqual((Filter) obj);
647  }
648
649  @Override
650  public int hashCode() {
651    return Objects.hash(this.fuzzyKeysData);
652  }
653}