mirror of
https://github.com/google/flatbuffers.git
synced 2026-06-02 04:04:19 +00:00
[Java][FlexBuffers] Abstract buffer access from ByteBuffer (#5743)
To read and build flexbuffers on Java, one needs to wrap the data using ByteBuffer. But for the common case of having ByteBuffers backed by arrays, accessing from a ByteBuffer might be inefficient. So this change introduces two interfaces: ReadBuf and ReadWriteBuf. It allows one to read and writes data directly on an array. It also allow other buffer implementations to be used with flexbuffers. Another change is that FlexBuffersBuilder backed by array allows the buffer to grow with the increase of the message size. Something that could not be done with ByteBuffer.
This commit is contained in:
@@ -15,6 +15,7 @@ import com.google.flatbuffers.UnionVector;
|
||||
import com.google.flatbuffers.FlexBuffers.FlexBufferException;
|
||||
import com.google.flatbuffers.FlexBuffers.Reference;
|
||||
import com.google.flatbuffers.FlexBuffers.Vector;
|
||||
import com.google.flatbuffers.ArrayReadWriteBuf;
|
||||
|
||||
import java.io.*;
|
||||
import java.math.BigInteger;
|
||||
@@ -1007,6 +1008,23 @@ class JavaTest {
|
||||
TestEq(source, result);
|
||||
}
|
||||
|
||||
public static void testBuilderGrowth() {
|
||||
FlexBuffersBuilder builder = new FlexBuffersBuilder();
|
||||
builder.putString("This is a small string");
|
||||
ByteBuffer b = builder.finish();
|
||||
TestEq("This is a small string", FlexBuffers.getRoot(b).asString());
|
||||
|
||||
FlexBuffersBuilder failBuilder = new FlexBuffersBuilder(ByteBuffer.allocate(1));
|
||||
try {
|
||||
failBuilder.putString("This is a small string");
|
||||
// This should never be reached, it should throw an exception
|
||||
// since ByteBuffers do not grow
|
||||
assert(false);
|
||||
} catch (java.lang.ArrayIndexOutOfBoundsException exception) {
|
||||
// It should throw exception
|
||||
}
|
||||
}
|
||||
|
||||
public static void TestFlexBuffers() {
|
||||
testSingleElementByte();
|
||||
testSingleElementShort();
|
||||
@@ -1028,6 +1046,7 @@ class JavaTest {
|
||||
testFlexBuferEmpty();
|
||||
testFlexBufferVectorStrings();
|
||||
testDeprecatedTypedVectorString();
|
||||
testBuilderGrowth();
|
||||
}
|
||||
|
||||
static void TestVectorOfBytes() {
|
||||
|
||||
Reference in New Issue
Block a user