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