### Install QuickBuffers plugin via command line (Debian/Ubuntu) Source: https://github.com/hebirobotics/quickbuffers/blob/main/docs/download.html Downloads and installs the QuickBuffers protoc plugin .deb package for the current CPU architecture using dpkg-architecture and wget. Requires sudo privileges for apt install. ```bash $ CPU=$(dpkg-architecture -q DEB_HOST_ARCH_CPU) $ wget https://github.com/HebiRobotics/QuickBuffers/releases/latest/download/protoc-gen-quickbuf_1.4_${CPU}.deb $ sudo apt install ./protoc-gen-quickbuf_1.4_${CPU}.deb ``` -------------------------------- ### Example JSON output Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md The prettified JSON output produced by the previous example's toString call. ```text { "text": "👍 QuickBuffers 👍", "peopleList": [{ "id": 0, "name": "First Name" }, { "id": 1, "name": "Last Name" }] } ``` -------------------------------- ### Execute conformance_test_runner with ConformanceQuickbuf.exe Source: https://github.com/hebirobotics/quickbuffers/blob/main/conformance/README.md Copies the QuickBuffers conformance executable into the protobuf directory, makes it executable, and runs the conformance test runner with --enforce_recommended. The output should list 0 failures; unsupported features like text format and some Google internal formats are skipped. ```shell cd ${protobufDir} cp ${quickbufDir}/conformance/target/ConformanceQuickbuf.exe ${protobufDir}/ chmod +x ConformanceQuickbuf.exe ./conformance_test_runner --enforce_recommended ConformanceQuickbuf.exe ``` -------------------------------- ### Compile native C++ conformance_test_runner on Linux Source: https://github.com/hebirobotics/quickbuffers/blob/main/conformance/README.md Clones the protobuf repository, initializes submodules, and builds the conformance test runner using CMake. This can take tens of minutes depending on CPU. Must be run on Linux due to pipe limitations in Windows and macOS. ```shell git clone https://github.com/protocolbuffers/protobuf.git cd protobuf git submodule update --init --recursive cmake . -Dprotobuf_BUILD_CONFORMANCE=ON && cmake --build . ``` -------------------------------- ### Compile QuickBuffers test executable with Maven and GraalVM native image Source: https://github.com/hebirobotics/quickbuffers/blob/main/conformance/README.md Builds a native image of the protoc-gen-quickbuf generator and then compiles the conformance executable. The second command tests the native generator and builds the conformance executable. The note shows native compilation without prior packaging. The generated executable is in ${quickbufDir}/conformance/target/ConformanceQuickbuf.exe. ```shell # 1) build a native image of the generator mvn clean package --projects "protoc-gen-quickbuf" -am -P"makeNative,useNative" # 2) test the native generator and build the conformance executable mvn clean package --projects quickbuf-runtime,conformance -am -P"makeNative,useNative" # (note) native compilation without any prior packaging mvn native:compile-no-fork -pl conformance -PmakeNative ``` -------------------------------- ### Expected conformance test runner output Source: https://github.com/hebirobotics/quickbuffers/blob/main/conformance/README.md Shows the expected output from running the conformance test runner. It reports 653 successes, 1376 skipped, 0 expected failures, and 0 unexpected failures for the first suite, and 0 successes, 120 skipped for the second suite. The final lines indicate EOF received after 120 and 2030 tests. ```text user:~/protobuf$ ./conformance_test_runner --enforce_recommended ConformanceQuickbuf.exe WARNING: All log messages before absl::InitializeLog() is called are written to STDERR I0000 00:00:1675465291.622071 18024 conformance_test_runner.cc:315] ConformanceQuickbuf.exe CONFORMANCE TEST BEGIN ==================================== CONFORMANCE SUITE PASSED: 653 successes, 1376 skipped, 0 expected failures, 0 unexpected failures. WARNING: All log messages before absl::InitializeLog() is called are written to STDERR I0000 00:00:1675465292.115120 22087 conformance_test_runner.cc:315] ConformanceQuickbuf.exe CONFORMANCE TEST BEGIN ==================================== CONFORMANCE SUITE PASSED: 0 successes, 120 skipped, 0 expected failures, 0 unexpected failures. ConformanceQuickbuf: received EOF from test runner after 120 tests. Bytes read: 12581, Bytes written: 1216 ConformanceQuickbuf: received EOF from test runner after 2030 tests. Bytes read: 166171, Bytes written: 55441 ``` -------------------------------- ### Message field accessors and usage in .proto and Java Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Shows .proto definitions for nested message types and simplified generated Java accessors. Includes two usage examples: setting via 'set' (copies data) and modifying the internal store directly with getMutableNestedMessage() (recommended). ```proto // .proto message NestedMessage { optional int32 primitive_value = 1; } message RootMessage { optional NestedMessage nested_message = 1; } ``` ```Java // simplified generated code public final class RootMessage { public RootMessage setNestedMessage(NestedMessage value); // copies contents to internal message public RootMessage clearNestedMessage(); // clears has bit as well as the backing object public boolean hasNestedMessage(); public NestedMessage getNestedMessage(); // internal message -> treat as read-only public NestedMessage getMutableNestedMessage(); // internal message -> may be modified until has state is cleared private final NestedMessage nestedMessage = NestedMessage.newInstance(); } ``` ```Java // (1) setting nested values via 'set' (does a data copy!) msg.setNestedMessage(NestedMessage().newInstance().setPrimitiveValue(0)); // (2) modify the internal store directly (recommended) RootMessage msg = RootMessage.newInstance(); msg.getMutableNestedMessage().setPrimitiveValue(0); ``` -------------------------------- ### Protobuf message definitions Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Defines the message structure used in the examples: RootMessage, NestedMessage, and Person. ```protobuf // .proto definition message RootMessage { optional string text = 1; optional NestedMessage nested_message = 2; repeated Person people_list = 3; } message NestedMessage { optional double value = 1; } message Person { optional uint32 id = 1; optional string name = 2; } ``` -------------------------------- ### String field accessors in .proto and Java Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Shows .proto definition and simplified generated Java accessors for a string field. String types are internally stored as Utf8String, lazily parsed, and can be set with CharSequence. Includes a usage example for decoding characters into a StringBuilder. ```proto // .proto message SimpleMessage { optional string optional_string = 2; } ``` ```Java // simplified generated code public final class SimpleMessage { public SimpleMessage setOptionalString(Utf8String value); public SimpleMessage setOptionalString(CharSequence value); public SimpleMessage clearOptionalString(); // sets length = 0 public boolean hasOptionalString(); public String getOptionalString(); // lazily converted string public Utf8String getOptionalStringBytes(); // internal representation -> treat as read-only public Utf8String getMutableOptionalStringBytes(); // internal representation -> may be modified until has state is cleared private final Utf8String optionalString = Utf8String.newEmptyInstance(); } ``` ```Java // Get characters SimpleMessage msg = SimpleMessage.newInstance().setOptionalString("my-text"); StringBuilder chars = new StringBuilder(); msg.getOptionalStringBytes().getChars(chars); // chars now contains "my-text" ``` -------------------------------- ### Message Field Accessors Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Generated accessors for nested message fields, including get, getMutable, set, clear, and has methods. ```APIDOC ## Message Field Accessors ### Description Generated accessors for nested message fields, including get, getMutable, set, clear, and has methods. ### Methods - `setNestedMessage(NestedMessage value)` - Copies contents to internal message. - `clearNestedMessage()` - Clears has bit and backing object. - `hasNestedMessage()` - Returns whether the field is set. - `getNestedMessage()` - Returns internal message (read-only). - `getMutableNestedMessage()` - Returns internal message (modifiable until has state is cleared). ### Example (Generated Code) ```java public final class RootMessage { public RootMessage setNestedMessage(NestedMessage value); public RootMessage clearNestedMessage(); public boolean hasNestedMessage(); public NestedMessage getNestedMessage(); public NestedMessage getMutableNestedMessage(); private final NestedMessage nestedMessage = NestedMessage.newInstance(); } ``` ### Usage Example ```java // (1) setting nested values via 'set' (does a data copy!) msg.setNestedMessage(NestedMessage().newInstance().setPrimitiveValue(0)); // (2) modify the internal store directly (recommended) RootMessage msg = RootMessage.newInstance(); msg.getMutableNestedMessage().setPrimitiveValue(0); ``` ``` -------------------------------- ### Repeated Field Accessors Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Generated accessors for repeated scalar fields, including add, addAll, clear, has, get, and getMutable methods. ```APIDOC ## Repeated Field Accessors ### Description Generated accessors for repeated scalar fields, including add, addAll, clear, has, get, and getMutable methods. ### Methods - `addRepeatedDouble(double value)` - Adds one value. - `addAllRepeatedDouble(double... values)` - Adds N values. - `clearRepeatedDouble()` - Sets length to 0. - `hasRepeatedDouble()` - Returns whether the field is set. - `getRepeatedDouble()` - Returns internal store (read-only). - `getMutableRepeatedDouble()` - Returns internal store (modifiable). ### Example (Generated Code) ```java public final class SimpleMessage { public SimpleMessage addRepeatedDouble(double value); public SimpleMessage addAllRepeatedDouble(double... values); public SimpleMessage clearRepeatedDouble(); public boolean hasRepeatedDouble(); public RepeatedDouble getRepeatedDouble(); public RepeatedDouble getMutableRepeatedDouble(); private final RepeatedDouble repeatedDouble = RepeatedDouble.newEmptyInstance(); } ``` ``` -------------------------------- ### String Field Accessors Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Generated accessors for string fields, including set with Utf8String or CharSequence, get, getBytes, getMutableBytes, clear, and has methods. ```APIDOC ## String Field Accessors ### Description Generated accessors for string fields, including set with Utf8String or CharSequence, get, getBytes, getMutableBytes, clear, and has methods. ### Methods - `setOptionalString(Utf8String value)` - Sets the string from a Utf8String. - `setOptionalString(CharSequence value)` - Sets the string from a CharSequence. - `clearOptionalString()` - Sets length to 0. - `hasOptionalString()` - Returns whether the field is set. - `getOptionalString()` - Returns the lazily converted string. - `getOptionalStringBytes()` - Returns internal Utf8String (read-only). - `getMutableOptionalStringBytes()` - Returns internal Utf8String (modifiable until has state is cleared). ### Example (Generated Code) ```java public final class SimpleMessage { public SimpleMessage setOptionalString(Utf8String value); public SimpleMessage setOptionalString(CharSequence value); public SimpleMessage clearOptionalString(); public boolean hasOptionalString(); public String getOptionalString(); public Utf8String getOptionalStringBytes(); public Utf8String getMutableOptionalStringBytes(); private final Utf8String optionalString = Utf8String.newEmptyInstance(); } ``` ### Usage Example ```java SimpleMessage msg = SimpleMessage.newInstance().setOptionalString("my-text"); StringBuilder chars = new StringBuilder(); msg.getOptionalStringBytes().getChars(chars); // chars now contains "my-text" ``` ``` -------------------------------- ### Test native images with Maven Source: https://github.com/hebirobotics/quickbuffers/blob/main/protoc-gen-quickbuf/Readme.md Tests the native images using the quickbuf-compat module with the useNative profile. Requires the native images to be built first. ```bash mvn clean package --projects quickbuf-compat -am -PuseNative ``` -------------------------------- ### Run protoc with protoc-gen-quickbuf plugin Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Uses the protoc compiler with the protoc-gen-quickbuf plugin binary. The ${exePath} must be an absolute path to the plugin executable. ```sh protoc --plugin-protoc-gen-quickbuf=${exePath} --quickbuf_out=${options>: ``` -------------------------------- ### Build native images with Maven Source: https://github.com/hebirobotics/quickbuffers/blob/main/protoc-gen-quickbuf/Readme.md Builds native executables for the protoc-gen-quickbuf module using the makeNative and useNative profiles. Requires a GraalVM environment with GRAALVM_HOME set. ```bash mvn clean package --projects protoc-gen-quickbuf -am -P"makeNative,useNative" ``` -------------------------------- ### Run protoc-quickbuf directly Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Invokes the QuickBuffers message generator directly using the protoc-quickbuf executable. The ${options} and ${outputDir} placeholders must be replaced with actual values. ```sh protoc-quickbuf --quickbuf_out=${options>: ``` -------------------------------- ### Build with Maven package Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Builds the project with Maven. The package goal is required; mvn clean test is not sufficient. The second command omits building benchmarks. ```Shell mvn package ``` ```Shell mvn clean package --projects protoc-gen-quickbuf,quickbuf-runtime -am ``` -------------------------------- ### Detect platform and architecture using User-Agent Client Hints Source: https://github.com/hebirobotics/quickbuffers/blob/main/docs/download.html Uses navigator.userAgentData.getHighEntropyValues to obtain platform and architecture, mapping to os and arch values. Falls back to older navigator.appVersion if the API is unavailable. Calls afterProbe with mobile status, os, and arch. ```javascript navigator.userAgentData.getHighEntropyValues(["architecture", "bitness", "platform"]).then(uaData => { const platform = uaData.platform; var arch = "amd64"; if (uaData.architecture == "arm") arch = "aarch64" // Valid values are: "Android", "Chrome OS", "iOS", "Linux", "macOS", "Windows", or "Unknown". var os; if (platform == "Windows") { os = "win"; } else if (platform == "macOS") { os = "mac" } else if (platform == "Linux") { os = "linux" } else os = "other"; // Not available on mobile platforms currently. let isUnavailable = navigator.userAgentData.mobile; afterProbe(isUnavailable, os, arch); }); ``` ```javascript // Older way. let appVersion = navigator.appVersion; var os; if (appVersion.indexOf("Win") !== -1) os = "win"; else if (appVersion.indexOf("Mac") !== -1) os = "mac"; else if (appVersion.indexOf("X11") !== -1 || appVersion.indexOf("Linux") !== -1) os = "linux" else os = "other"; // CPU architecture in older API is useless. Safari lies and says Intel even on ARM. afterProbe(false, os); ``` -------------------------------- ### Maven plugin configuration for protoc-jar-maven-plugin Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Configures the protoc-jar-maven-plugin to download protoc and the QuickBuffers plugin, then generate messages from .proto files in src/main/protobuf. The plugin version is 3.11.4 and protoc version is 3.21.12. ```xml com.github.os72 protoc-jar-maven-plugin 3.11.4 generate-sources run 3.21.12 quickbuf us.hebi.quickbuf:protoc-gen-quickbuf:${quickbuf.version} ${quickbuf.options} ``` -------------------------------- ### Convenience wrappers for streams Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Creates ProtoSink and ProtoSource instances for ByteArrayOutputStream and ByteArrayInputStream. ```Java ProtoSink.newInstance(new ByteArrayOutputStream()); ProtoSource.newInstance(new ByteArrayInputStream(bytes)); ``` -------------------------------- ### Reusable objects with ProtoSink and ProtoSource Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Shows how to reuse ProtoSink and ProtoSource for streaming multiple messages, using setInput and setOutput. ```Java // Reusable objects byte[] buffer = new byte[512]; ProtoSink sink = ProtoSink.newArraySink(); ProtoSource source = ProtoSource.newArraySource(); // Stream messages for (int i = 0; i < 100; i++) { int length = msg.getSerializedSize(); msg.writeTo(sink.setOutput(buffer, 0, length)); result.clearQuick().mergeFrom(source.setInput(buffer, 0, length)); } ``` -------------------------------- ### Primitive field accessors in .proto and generated Java Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Shows the .proto definition and simplified generated Java accessors for a primitive field. All primitive values generate the same accessors and behavior as Protobuf-Java's Builder classes. ```proto // .proto message SimpleMessage { optional int32 primitive_value = 1; } ``` ```Java // simplified generated code public final class SimpleMessage { public SimpleMessage setPrimitiveValue(int value); public SimpleMessage clearPrimitiveValue(); public boolean hasPrimitiveValue(); public int getPrimitiveValue(); private int primitiveValue; } ``` -------------------------------- ### Maven dependency for quickbuf-runtime Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Adds the QuickBuffers runtime dependency to a Maven project. The version is referenced from the quickbuf.version property. ```xml us.hebi.quickbuf quickbuf-runtime ${quickbuf.version} ``` -------------------------------- ### Direct Source/Sink for off-heap memory Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Shows writing to and reading from a direct ByteBuffer using DirectSink and DirectSource. ```Java // Write to direct buffer ByteBuffer directBuffer = ByteBuffer.allocateDirect(msg.getSerializedSize()); ProtoSink directSink = ProtoSink.newDirectSink(); msg.writeTo(directSink.setOutput(directBuffer)); directBuffer.limit(directSink.getTotalBytesWritten()); // Read from direct buffer ProtoSource directSource = ProtoSource.newDirectSource(); RootMessage result = RootMessage.parseFrom(directSource.setInput(directBuffer)); assertEquals(msg, result); ``` -------------------------------- ### Maven properties for QuickBuffers Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Defines the QuickBuffers version and generator options as Maven properties. The options are used by the protoc-jar-maven-plugin configuration. ```xml 1.4 indent=4,allocation=lazy,extensions=embedded ``` -------------------------------- ### Serialize and parse JSON with JsonSink and JsonSource Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Shows how to configure a JsonSink for serialization and a JsonSource for parsing. The sink options control pretty printing, enum encoding, and field name preservation. The source can ignore unknown fields. Use ProtoMessage::writeTo or JsonSink::writeMessage to serialize, and ProtoMessage::parseFrom or JsonSource::parseMessage to parse. ```Java // json options JsonSink sink = JsonSink.newInstance() .setPrettyPrinting(false) .setWriteEnumsAsInts(false) .setPreserveProtoFieldNames(false); // use ProtoMessage::writeTo or JsonSink::writeMessage to serialize the contents msg.writeTo(sink.clear()); RepeatedByte bytes = sink.getBytes(); // use ProtoMessage::parseFrom or JsonSource::parseMessage to parse the contents JsonMessage result = JsonSource.newInstance(bytes) .setIgnoreUnknownFields(true) .parseMessage(JsonMessage.getFactory()); ``` -------------------------------- ### Set version with Maven versions plugin Source: https://github.com/hebirobotics/quickbuffers/blob/main/protoc-gen-quickbuf/Readme.md Updates the project version across all modules to the specified new version. Replace ${NEW_VERSION} with the desired version number. ```bash mvn versions:set -DprocessAllModules -DnewVersion=${NEW_VERSION} ``` -------------------------------- ### Generated Protobuf-Java writeTo method Source: https://github.com/hebirobotics/quickbuffers/blob/main/order.md Shows the generated Java class for the proto definition. The writeTo method accesses fields in a semi-random memory pattern due to JVM field reordering, which can degrade performance. ```java // Generated Protobuf-Java Message (simplified) class ExampleMessage extends GeneratedMessageV3 { private int field1_; private int field2_; private String field3_; private double field4_; private long field5_; @Override public void writeTo(CodedOutputStream output) throws IOException { // removed bitfield checks // offset 40 output.writeInt32(1, field1_); // offset 44 output.writeDouble(2, field4_); // offset 24 output.writeInt32(3, field2_); // offset 48 GeneratedMessageV3.writeString(output, 4, field3_); // offset 56 & ref jump output.writeInt64(5, field5_); // offset 32 } } ``` -------------------------------- ### Proguard: Disable warning for JdkMethods Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Add this line to the proguard.conf file to suppress warnings about missing methods when obfuscating against an older runtime. The warning is related to an intentional workaround, and R8 should automatically pick up the bundled config file. ```text -dontwarn us.hebi.quickbuf.JdkMethods ``` -------------------------------- ### Setting message values with fluent-style and getMutable() Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Shows how to set scalar fields, nested messages, and repeated fields using the mutable API. ```Java // Use fluent-style to set values RootMessage msg = RootMessage.newInstance() .setText("Hello World"); // Use getMutable() to set nested messages msg.getMutableNestedMessage() .setValue(1.0); // Write repeated values into the internally allocated list RepeatedMessage people = msg.getMutablePeopleList().reserve(4); for (int i = 0; i < 4; i++) { Person person = people.next() .setId(i) .setName("person " + i); } ``` -------------------------------- ### Convert protobuf stream to JSON and vice-versa Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Combines ProtoMessage methods to convert an incoming protobuf stream to outgoing JSON and vice-versa. Uses clearQuick, mergeFrom, and writeTo with a proto source and a JSON sink. ```Java msg.clearQuick() .mergeFrom(protoSource.setInput(input)) .writeTo(jsonSink.clear()); ``` -------------------------------- ### Primitive Field Accessors Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Generated accessors for primitive fields in QuickBuffers messages, mirroring Protobuf-Java Builder behavior. ```APIDOC ## Primitive Field Accessors ### Description Generated accessors for primitive fields in QuickBuffers messages, mirroring Protobuf-Java Builder behavior. ### Methods - `setPrimitiveValue(int value)` - Sets the primitive value. - `clearPrimitiveValue()` - Clears the field and its has bit. - `hasPrimitiveValue()` - Returns whether the field is set. - `getPrimitiveValue()` - Returns the current value. ### Example (Generated Code) ```java public final class SimpleMessage { public SimpleMessage setPrimitiveValue(int value); public SimpleMessage clearPrimitiveValue(); public boolean hasPrimitiveValue(); public int getPrimitiveValue(); private int primitiveValue; } ``` ``` -------------------------------- ### Serializing and parsing with toByteArray and parseFrom Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Convenience wrappers for serializing a message to a byte array and parsing it back. ```Java // Convenience wrappers byte[] buffer = msg.toByteArray(); RootMessage result = RootMessage.parseFrom(buffer); assertEquals(result, msg); ``` -------------------------------- ### Make code copyable by clicking the button Source: https://github.com/hebirobotics/quickbuffers/blob/main/docs/download.html Adds click event listeners to all elements with class 'copy-button'. Copies the code text from the parent element, stripping prompt prefixes, using the Clipboard API with fallback for Firefox. Shows a tooltip for 5 seconds after copying. ```javascript Array.from(document.getElementsByClassName("copy-button")).forEach((el) => { el.addEventListener("click", (event) => { const mimeType = 'text/plain'; const data = el.parentElement.parentElement.parentElement.children[0].textContent.split("\n").map(str => str.replace("$\xa0", "").replace("PS>\xa0", "").trim()).join("\n"); try { const promise = Promise.resolve(new Blob([data], { type: mimeType })); const clipboardItem = new ClipboardItem({ [mimeType]: promise }, { presentationStyle: "unspecified" }); navigator.clipboard.write([clipboardItem]) } catch (e) { // Try again with the older API. This is for Firefox. navigator.clipboard.writeText(data); } // Make the tooltip appear to confirm to the user. var index = document.styleSheets[0].insertRule(".tooltip:before, .tooltip:after { opacity:1; }", document.styleSheets[0].cssRules.length); setTimeout(function() { document.styleSheets[0].removeRule(index) }, 5000); }) }) ``` -------------------------------- ### JSON output via toString Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Sets message contents and prints the message as prettified JSON using the default toString method. ```Java // Set some contents RootMessage msg = RootMessage.newInstance(); msg.setText("👍 QuickBuffers \uD83D\uDC4D"); msg.getMutablePeopleList().next() .setId(0) .setName("First Name"); msg.getMutablePeopleList().next() .setId(1) .setName("Last Name"); // Print as prettified json System.out.println(msg); ``` -------------------------------- ### JDK8 memory layout of Protobuf-Java message Source: https://github.com/hebirobotics/quickbuffers/blob/main/order.md Output of a JOL (Java Object Layout) tool showing the actual memory layout on JDK8. Fields are reordered to [4,5,1,2,3] instead of declaration order, causing non-sequential access. ```text UnittestFieldOrder$ExampleMessage object internals: OFFSET SIZE TYPE DESCRIPTION VALUE 0 12 (object header) N/A 12 4 int AbstractMessageLite.memoizedHashCode N/A 16 4 int AbstractMessage.memoizedSize N/A 20 4 UnknownFieldSet GeneratedMessageV3.unknownFields N/A 24 8 double ExampleMessage.field4_ N/A 32 8 long ExampleMessage.field5_ N/A 40 4 int ExampleMessage.bitField0_ N/A 44 4 int ExampleMessage.field1_ N/A 48 4 int ExampleMessage.field2_ N/A 52 1 byte ExampleMessage.memoizedIsInitialized N/A 53 3 (alignment/padding gap) 56 4 Object ExampleMessage.field3_ N/A 60 4 (loss due to the next object alignment) Instance size: 64 bytes Space losses: 3 bytes internal + 4 bytes external = 7 bytes total ``` -------------------------------- ### Generated QuickBuffers (RoboBuffers) message Source: https://github.com/hebirobotics/quickbuffers/blob/main/order.md QuickBuffers declares and serializes fields sorted by type and ascending number, resulting in a predictable memory layout and sequential access pattern during serialization. ```java // Generated RoboBuffers Message (simplified) class ExampleMessage extends ProtoMessage { private double field4; private long field5; private int field1; private int field2; private final StringBuilder field3 = new StringBuilder(0); @Override public void writeTo(ProtoSink output) throws IOException { // removed bitfield checks // offset 16 output.writeRawByte((byte) 17); // tag output.writeDoubleNoTag(field4); // offset 24 output.writeRawByte((byte) 40); // tag output.writeInt64NoTag(field5); // offset 32 output.writeRawByte((byte) 8); // tag output.writeInt32NoTag(field1); // offset 40 output.writeRawByte((byte) 24); // tag output.writeInt32NoTag(field2); // offset 44 output.writeRawByte((byte) 34); // tag output.writeStringNoTag(field3); // offset 48 & ref jump } } ``` -------------------------------- ### Proto definition with non-sequential field numbers Source: https://github.com/hebirobotics/quickbuffers/blob/main/order.md Defines a message with fields numbered 1,3,4,2,5. Protobuf-Java serializes fields in ascending field number order, resulting in field[1,4,2,3,5]. ```proto // Proto definition message ExampleMessage { optional int32 field1 = 1; optional int32 field2 = 3; optional string field3 = 4; optional double field4 = 2; optional int64 field5 = 5; } ``` -------------------------------- ### Repeated field accessors in .proto and Java Source: https://github.com/hebirobotics/quickbuffers/blob/main/README.md Shows .proto definition and simplified generated Java accessors for a repeated scalar field. Repeated scalar fields work mostly the same as String fields, but the internal array() can be accessed directly if needed. ```proto // .proto message SimpleMessage { repeated double repeated_double = 42; } ``` ```Java // simplified generated code public final class SimpleMessage { public SimpleMessage addRepeatedDouble(double value); // adds one value public SimpleMessage addAllRepeatedDouble(double... values); // adds N values public SimpleMessage clearRepeatedDouble(); // sets length = 0 public boolean hasRepeatedDouble(); public RepeatedDouble getRepeatedDouble(); // internal store -> treat as read-only public RepeatedDouble getMutableRepeatedDouble(); // internal store -> may be modified private final RepeatedDouble repeatedDouble = RepeatedDouble.newEmptyInstance(); } ``` -------------------------------- ### RepeatedByte writeTo(ProtoSink) method Source: https://github.com/hebirobotics/quickbuffers/blob/main/quickbuf-runtime/src/test/resources/concat/RepeatedByte.txt Writes the byte array to a ProtoSink using writeRawBytes. Returns this for chaining. ```java public RepeatedByte writeTo(ProtoSink sink) throws java.io.IOException { sink.writeRawBytes(array, 0, length); return this; } ``` -------------------------------- ### RepeatedByte writeTo(ByteBuffer) method Source: https://github.com/hebirobotics/quickbuffers/blob/main/quickbuf-runtime/src/test/resources/concat/RepeatedByte.txt Writes the byte array to a ByteBuffer. Returns this for chaining. ```java public RepeatedByte writeTo(java.nio.ByteBuffer buffer) { buffer.put(array, 0, length); return this; } ``` -------------------------------- ### RepeatedByte writeTo(OutputStream) method Source: https://github.com/hebirobotics/quickbuffers/blob/main/quickbuf-runtime/src/test/resources/concat/RepeatedByte.txt Writes the byte array to an OutputStream. Returns this for chaining. ```java public RepeatedByte writeTo(java.io.OutputStream outputStream) throws java.io.IOException { outputStream.write(array, 0, length); return this; } ```