Fix AbstractByteBufferProxy.compareBuff and Improve ComparatorTest (P… · lmdbjava/lmdbjava@8230623
@@ -33,6 +33,7 @@
3333import static org.lmdbjava.DirectBufferProxy.PROXY_DB;
34343535import java.nio.ByteBuffer;
36+import java.util.Arrays;
3637import java.util.Comparator;
37383839import com.google.common.primitives.SignedBytes;
@@ -156,9 +157,38 @@ private static class ByteBufferRunner implements ComparatorRunner {
156157157158@Override
158159public int compare(final byte[] o1, final byte[] o2) {
159-final ByteBuffer o1b = ByteBuffer.wrap(o1);
160-final ByteBuffer o2b = ByteBuffer.wrap(o2);
161-return PROXY_OPTIMAL.compare(o1b, o2b);
160+// Convert arrays to buffers that are larger than the array, with
161+// limit set at the array length. One buffer bigger than the other.
162+ByteBuffer o1b = arrayToBuffer(o1, o1.length * 3);
163+ByteBuffer o2b = arrayToBuffer(o2, o2.length * 2);
164+final int result = PROXY_OPTIMAL.compare(o1b, o2b);
165+166+// Now swap which buffer is bigger
167+o1b = arrayToBuffer(o1, o1.length * 2);
168+o2b = arrayToBuffer(o2, o2.length * 3);
169+final int result2 = PROXY_OPTIMAL.compare(o1b, o2b);
170+171+assertThat(result2, is(result));
172+173+// Now try with buffers sized to the array.
174+o1b = ByteBuffer.wrap(o1);
175+o2b = ByteBuffer.wrap(o2);
176+final int result3 = PROXY_OPTIMAL.compare(o1b, o2b);
177+178+assertThat(result3, is(result));
179+180+return result;
181+ }
182+183+private ByteBuffer arrayToBuffer(final byte[] arr, final int bufferCapacity) {
184+if (bufferCapacity < arr.length) {
185+throw new IllegalArgumentException("bufferCapacity < arr.length");
186+ }
187+final byte[] newArr = Arrays.copyOf(arr, bufferCapacity);
188+final ByteBuffer byteBuffer = ByteBuffer.wrap(newArr);
189+byteBuffer.limit(arr.length);
190+byteBuffer.position(0);
191+return byteBuffer;
162192 }
163193 }
164194