1 // Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
2 //  This source code is licensed under both the GPLv2 (found in the
3 //  COPYING file in the root directory) and Apache 2.0 License
4 //  (found in the LICENSE.Apache file in the root directory).
5 
6 package org.rocksdb.util;
7 
8 import org.rocksdb.AbstractComparator;
9 import org.rocksdb.ComparatorOptions;
10 
11 import java.nio.ByteBuffer;
12 
13 /**
14  * This is a Java implementation of a Comparator for Java int
15  * keys.
16  *
17  * This comparator assumes keys are (at least) four bytes, so
18  * the caller must guarantee that in accessing other APIs in
19  * combination with this comparator.
20  *
21  * The performance of Comparators implemented in Java is always
22  * less than their C++ counterparts due to the bridging overhead,
23  * as such you likely don't want to use this apart from benchmarking
24  * or testing.
25  */
26 public final class IntComparator extends AbstractComparator {
27 
IntComparator(final ComparatorOptions copt)28   public IntComparator(final ComparatorOptions copt) {
29     super(copt);
30   }
31 
32   @Override
name()33   public String name() {
34     return "rocksdb.java.IntComparator";
35   }
36 
37   @Override
compare(final ByteBuffer a, final ByteBuffer b)38   public int compare(final ByteBuffer a, final ByteBuffer b) {
39     return compareIntKeys(a, b);
40   }
41 
42   /**
43    * Compares integer keys
44    * so that they are in ascending order
45    *
46    * @param a 4-bytes representing an integer key
47    * @param b 4-bytes representing an integer key
48    *
49    * @return negative if a < b, 0 if a == b, positive otherwise
50    */
compareIntKeys(final ByteBuffer a, final ByteBuffer b)51   private final int compareIntKeys(final ByteBuffer a, final ByteBuffer b) {
52     final int iA = a.getInt();
53     final int iB = b.getInt();
54 
55     // protect against int key calculation overflow
56     final long diff = (long)iA - iB;
57     final int result;
58     if (diff < Integer.MIN_VALUE) {
59       result = Integer.MIN_VALUE;
60     } else if(diff > Integer.MAX_VALUE) {
61       result = Integer.MAX_VALUE;
62     } else {
63       result = (int)diff;
64     }
65     return result;
66   }
67 }
68