Skip to content

Commit 8230623

Browse files
authored
Fix AbstractByteBufferProxy.compareBuff and Improve ComparatorTest (PR #170) (fixes #169)
1 parent 18fbd77 commit 8230623

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

src/main/java/org/lmdbjava/ByteBufferProxy.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ public static int compareBuff(final ByteBuffer o1, final ByteBuffer o2) {
152152
}
153153
}
154154

155-
return o1.capacity() - o2.capacity();
155+
return o1.remaining() - o2.remaining();
156156
}
157157

158158
static Field findField(final Class<?> c, final String name) {

src/test/java/org/lmdbjava/ComparatorTest.java

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
import static org.lmdbjava.DirectBufferProxy.PROXY_DB;
3434

3535
import java.nio.ByteBuffer;
36+
import java.util.Arrays;
3637
import java.util.Comparator;
3738

3839
import com.google.common.primitives.SignedBytes;
@@ -156,9 +157,38 @@ private static class ByteBufferRunner implements ComparatorRunner {
156157

157158
@Override
158159
public 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

0 commit comments

Comments
 (0)