Closest implementation of C++ memcmp method in Java

RocksDB is a fast embedded key-value database designed by Facebook in C++. They have extended most functions in RocksDB to Java but somes are not there. For example, I came across the following problem:

In RocksDB, the key can be sorted in the following orderings in Java:

public enum BuiltinComparator {

private BuiltinComparator() {

in Java, if I have a set of keys:

set[startK, endK] 

and I want to iterate the range in RocksDB to get the values.

you can easily get the first value of the “startK” by

RocksIterator itr = rockDbInstance.newIterator();;

However, you need to have a comparator to sort the keys you have in the range, then compare with what the iterator returns so that you don’t need to iterate through the whole rocksDB again and again.

So in essence, the question is how we can implement a Comparator<byte[]> so that it the element ordered in the set is also the same as how RocksDB sorts the keys.

My Tentative Solution:

Based on the C++ source code snippet in:

Internally, RocksDb utilizes C++ memcmp method to compare byte arrays. This is very efficient however there’s no similar implementation for this function in Java. The perfect one I found after a couple of hours of researching is like the following :

After extensive testing, I’m confident this implementation so far functionally is equivalent to memcmp in C++. I haven’t tested its performance though so use with your caution on the potential performance impact.