THRIFT-894. java: Make default accessors for binary fields return byte[]; provide new accessors to get ByteBuffer version
This patch causes the underlying ByteBuffer that backs a binary field to be hidden behind a default accessor that provides a byte[] interface. This should allow users who skipped 0.4 to update their generated code without breaking any of their other code. A new accessor has been added that allows a way down to the underlying ByteBuffer for those experts who want to take advantage.
git-svn-id: https://svn.apache.org/repos/asf/incubator/thrift/trunk@996579 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/lib/java/src/org/apache/thrift/TBaseHelper.java b/lib/java/src/org/apache/thrift/TBaseHelper.java
index 9a7ee73..46075d3 100644
--- a/lib/java/src/org/apache/thrift/TBaseHelper.java
+++ b/lib/java/src/org/apache/thrift/TBaseHelper.java
@@ -240,4 +240,37 @@
int extended = (b | 0x100) & 0x1ff;
return Integer.toHexString(extended).toUpperCase().substring(1);
}
+
+ public static byte[] byteBufferToByteArray(ByteBuffer byteBuffer) {
+ if (wrapsFullArray(byteBuffer)) {
+ return byteBuffer.array();
+ }
+ byte[] target = new byte[byteBuffer.remaining()];
+ byteBufferToByteArray(byteBuffer, target, 0);
+ return target;
+ }
+
+ public static boolean wrapsFullArray(ByteBuffer byteBuffer) {
+ return byteBuffer.hasArray()
+ && byteBuffer.position() == 0
+ && byteBuffer.arrayOffset() == 0
+ && byteBuffer.remaining() == byteBuffer.capacity();
+ }
+
+ public static int byteBufferToByteArray(ByteBuffer byteBuffer, byte[] target, int offset) {
+ int remaining = byteBuffer.remaining();
+ System.arraycopy(byteBuffer.array(),
+ byteBuffer.arrayOffset() + byteBuffer.position(),
+ target,
+ offset,
+ remaining);
+ return remaining;
+ }
+
+ public static ByteBuffer rightSize(ByteBuffer in) {
+ if (wrapsFullArray(in)) {
+ return in;
+ }
+ return ByteBuffer.wrap(byteBufferToByteArray(in));
+ }
}