### Run Java Examples with Gradle Source: https://github.com/aeron-io/simple-binary-encoding/blob/master/README.md Use Gradle to run the Java examples included in the SBE project. ```bash ./gradlew runJavaExamples ``` -------------------------------- ### Build and Test Golang Code with Makefile Source: https://github.com/aeron-io/simple-binary-encoding/blob/master/README.md Navigate to the gocode directory and use the provided Makefile to test, run examples, and benchmarks for the Golang implementation. ```bash cd gocode # make # test, examples, bench ``` -------------------------------- ### Execute SBE Java Tool from Command Line Source: https://github.com/aeron-io/simple-binary-encoding/blob/master/README.md Example command to execute the SBE Java tool from the command line, generating C++ code. Ensure the SBE_TOOL_VERSION environment variable is set. ```bash java --add-opens java.base/jdk.internal.misc=ALL-UNNAMED -Dsbe.generate.ir=true -Dsbe.target.language=Cpp -Dsbe.target.namespace=sbe -Dsbe.output.dir=include/gen -Dsbe.errorLog=yes -jar sbe-all/build/libs/sbe-all-${SBE_TOOL_VERSION}.jar my-sbe-messages.xml ``` -------------------------------- ### Generate Rust Codecs with Gradle Source: https://github.com/aeron-io/simple-binary-encoding/blob/master/README.md Use this command to generate Rust codecs from your SBE schema. Ensure you have Gradle installed and configured. ```bash ./gradlew generateRustCodecs ``` -------------------------------- ### Type Element Examples Source: https://github.com/aeron-io/simple-binary-encoding/wiki/FIX-SBE-XML-Primer Defines custom types by specifying their name, primitive type, length, and semantic type. ```xml ``` ```xml ``` ```xml ``` -------------------------------- ### messageSchema Element Example Source: https://github.com/aeron-io/simple-binary-encoding/wiki/FIX-SBE-XML-Primer Defines the root element for an SBE schema, specifying package, ID, version, description, and byte order. ```xml ``` -------------------------------- ### Golang Usage of SBE Composite Types Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Golang-User-Guide Shows how composite types in SBE map directly to types in Golang and are referenced for setting or retrieving values. Example involves setting the capacity of a car's engine. ```go car.Engine.Capacity = 17 cylinders = car.Engine.NumCylinders ``` -------------------------------- ### Enum Element Examples Source: https://github.com/aeron-io/simple-binary-encoding/wiki/FIX-SBE-XML-Primer Defines enumerations with named valid values and their corresponding encoded types. ```xml 0 1 ``` ```xml A B C ``` -------------------------------- ### Golang Usage of SBE Repeating Groups Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Golang-User-Guide Illustrates how repeating groups in SBE are represented as slices in Golang. The length of the slice determines the number of items in the group. Example shows accessing the speed of the second fuel figure. ```go groupLength := len(car.FuelFigures) // Grab the second element's Speed speed := car.FuelFigures[1].Speed ``` -------------------------------- ### Build SBE Project with Gradle Source: https://github.com/aeron-io/simple-binary-encoding/blob/master/README.md Execute a full clean build of the SBE project using Gradle. ```bash ./gradlew ``` -------------------------------- ### Generate SBE Codec with JVM Options Source: https://github.com/aeron-io/simple-binary-encoding/blob/master/CHANGELOG.adoc Use this command to generate codecs or use generated Java classes. Ensure the `--add-opens` JVM option is specified for proper functionality. ```shell java --add-opens java.base/jdk.internal.misc=ALL-UNNAMED -Dsbe.generate.ir=true -Dsbe.target.language=Cpp -Dsbe.target.namespace=sbe -Dsbe.output.dir=include/gen -Dsbe.errorLog=yes -jar sbe-all/build/libs/sbe-all-${SBE_TOOL_VERSION}.jar my-sbe-messages.xml ``` -------------------------------- ### Generate Golang Codecs with Gradle Source: https://github.com/aeron-io/simple-binary-encoding/blob/master/README.md First build the SBE project using Gradle, then use it to generate the Golang codecs. ```bash ./gradlew ./gradlew generateGolangCodecs ``` -------------------------------- ### Run SBE Tool with System Property Options Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Sbe-Tool-Guide Execute the SBE tool with system property options to customize code generation and validation. Ensure the SBE_TOOL_VERSION environment variable is set. ```bash java [-Doption=value] --add-opens java.base/jdk.internal.misc=ALL-UNNAMED -jar sbe-all-${SBE_TOOL_VERSION}.jar ``` -------------------------------- ### Usage of SBE BitSet Choices in Golang Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Golang-User-Guide Demonstrates how to set a bit in the SBE bitset using the defined choice values. This is analogous to using enumerations. ```go car.Extras[OptionalExtrasChoice.CruiseControl] = true ``` -------------------------------- ### Initialize DirectBuffer in C# Source: https://github.com/aeron-io/simple-binary-encoding/wiki/CSharp-User-Guide Demonstrates how to initialize a byte array and wrap it with a DirectBuffer for efficient encoding and decoding in C#. This buffer is used for sending data over the wire or saving to disk. ```csharp // This byte array is used for encoding and decoding, // this is what you would send on the wire or save to disk var byteBuffer = new byte[4096]; // You then "wrap" the array with a DirectBuffer, this class is used by // the generated code to read and write efficiently to the underlying byte array var directBuffer = new DirectBuffer(byteBuffer); ``` -------------------------------- ### Run SBE Tool to Generate Codecs Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Sbe-Tool-Guide Execute the SBE tool as a JAR file to generate codecs from a message declarations file. Ensure the SBE_LIB_VERSION environment variable is set. ```bash java --add-opens java.base/jdk.internal.misc=ALL-UNNAMED -jar sbe-all-${SBE_LIB_VERSION}.jar ``` -------------------------------- ### Compile C Compliance With Version Test Executable Source: https://github.com/aeron-io/simple-binary-encoding/blob/master/sbe-tool/src/test/c/CMakeLists.txt Compiles a C source file 'CComplianceWithVersionTest.c' to verify C compliance with versioning in generated headers. It includes the generated code directory and depends on the 'c_codecs' target. ```cmake add_executable(CComplianceWithVersionTest CComplianceWithVersionTest.c) target_include_directories(CComplianceWithVersionTest PRIVATE ${C_CODEC_TARGET_DIR} ) add_dependencies(CComplianceWithVersionTest c_codecs) ``` -------------------------------- ### Clean, Build, and Test C++ with CMake Source: https://github.com/aeron-io/simple-binary-encoding/blob/master/README.md Perform a full clean, build, and test of all C++ targets using CMake. ```bash mkdir -p cppbuild/Debug cd cppbuild/Debug cmake ../.. cmake --build . --clean-first ctest ``` -------------------------------- ### Use Serialized IR as Input to SBE Tool Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Intermediate-Representation Provide the `.sbeir` file directly to the SBE Tool instead of the XML schema file for code generation. This allows using the pre-compiled IR as input. ```bash java -jar sbe-all-${SBE_LIB_VERSION}.jar ``` -------------------------------- ### Run Rust Tests with Gradle Source: https://github.com/aeron-io/simple-binary-encoding/blob/master/README.md Execute Rust tests through Gradle. This is a convenient way to run your generated code's tests. ```bash ./gradlew runRustTests ``` -------------------------------- ### Configure Maven for SBE Tool Code Generation Source: https://github.com/aeron-io/simple-binary-encoding/wiki/SBE-Tool-Maven This XML configuration sets up the exec-maven-plugin to run the SBE Tool and the build-helper-maven-plugin to add generated sources. Ensure the sbe.tool.version property is defined in your Maven project. ```xml org.codehaus.mojo exec-maven-plugin 1.6.0 generate-sources java false true uk.co.real_logic.sbe.SbeTool sbe.output.dir ${project.build.directory}/generated-sources/java ${project.build.resources[0].directory}/schema.xml ${project.build.directory}/generated-sources/java uk.co.real-logic sbe-tool ${sbe.tool.version} org.codehaus.mojo build-helper-maven-plugin 3.0.0 add-source generate-sources add-source ${project.build.directory}/generated-sources/java/ ``` -------------------------------- ### Create OTF Header Decoder Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Cpp-OTF-User-Guide Initializes an OtfHeaderDecoder after successfully decoding the SBE IR. Requires the header tokens obtained from the IrDecoder. ```cpp std::shared_ptr> headerTokens = irDecoder.header(); OtfHeaderDecoder headerDecoder(headerTokens); ``` -------------------------------- ### Compile C Compliance Test Executable Source: https://github.com/aeron-io/simple-binary-encoding/blob/master/sbe-tool/src/test/c/CMakeLists.txt Compiles a C source file 'CComplianceTest.c' to verify the C compliance of generated headers. It includes the generated code directory and depends on the 'c_codecs' target. ```cmake add_executable(CComplianceTest CComplianceTest.c) target_include_directories(CComplianceTest PRIVATE ${C_CODEC_TARGET_DIR} ) add_dependencies(CComplianceTest c_codecs) ``` -------------------------------- ### Handle Composite Begin/End in Java Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Java-OTF-User-Guide Callback methods for managing scope when decoding composite data structures. Push scope on begin and pop on end. ```java public void onBeginComposite(final Token fieldToken, final List tokens, final int fromIndex, final int toIndex) { namedScope.push(fieldToken.name() + "."); } public void onEndComposite(final Token fieldToken, final List tokens, final int fromIndex, final int toIndex) { namedScope.pop(); } ``` -------------------------------- ### Makefile Targets for SBE Golang Generation Source: https://github.com/aeron-io/simple-binary-encoding/blob/master/gocode/README.md The Makefile provides targets for generating Golang code from SBE schemas and running associated tests or benchmarks. Ensure your GOPATH is set correctly or use the Makefile to manage it. ```makefile example test bench ``` -------------------------------- ### Handle Repeating Group Begin/End in Java Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Java-OTF-User-Guide Callback methods for managing scope when decoding repeating groups. Push scope on begin and pop on end, supporting nested groups. ```java public void onBeginGroup(final Token token, final int groupIndex, final int numInGroup) { namedScope.push(token.name() + "."); } public void onEndGroup(final Token token, final int groupIndex, final int numInGroup) { namedScope.pop(); } ``` -------------------------------- ### SBE Flyweight Codec State Machine Diagram Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Safe-Flyweight-Usage Illustrates the state machine for SBE flyweight codecs, showing valid transitions between states based on field access order. This is crucial for understanding and preventing runtime errors. ```java /** * The states in which a encoder/decoder/codec can live. * *

The state machine diagram below, encoded in the dot language, describes * the valid state transitions according to the order in which fields may be * accessed safely. Tools such as PlantUML and Graphviz can render it. * *

{@code
     *   digraph G {
     *       NOT_WRAPPED -> V0_BLOCK [label="  wrap(version=0)  "];
     *       V0_BLOCK -> V0_BLOCK [label="  chatId(?)  "];
     *       V0_BLOCK -> V0_SUBJECT_DONE [label="  subject(?)  "];
     *       V0_SUBJECT_DONE -> V0_BODY_DONE [label="  body(?)  "];
     *   }
     * }
*/ private static class CodecStates { // ... } ``` -------------------------------- ### Run Rust Tests Directly with Cargo Source: https://github.com/aeron-io/simple-binary-encoding/blob/master/README.md Navigate to the Rust directory and use Cargo to run tests directly. This bypasses Gradle for testing. ```bash cd rust cargo test ``` -------------------------------- ### Accessing Single Fixed Fields in Go Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Golang-User-Guide Demonstrates direct access to single fixed fields within a Go struct generated by SBE. ```go car.SerialNumber = 1234 model := car.ModelYear ``` -------------------------------- ### Using SBE Enumerations in Go Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Golang-User-Guide Illustrates how SBE enumerations are represented in Go using custom types and a struct containing known values. Assigning an enumeration value to a field is shown. ```go type ModelEnum byte type ModelValues struct { A ModelEnum B ModelEnum C ModelEnum NullValue ModelEnum } var Model = ModelValues{65, 66, 67, 0} car.DiscountedModel = Model.C ``` -------------------------------- ### Generate Serialized IR with SBE Tool Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Intermediate-Representation Set the `sbe.generate.ir` Java system property to true when running the SBE Tool to generate a serialized IR file. The output file will have the same base name as the input XML file but with a `.sbeir` extension. ```bash java -Dsbe.generate.ir=true -jar sbe-all-${SBE_TOOL_VERSION}.jar ``` -------------------------------- ### New File Header for SBE Source: https://github.com/aeron-io/simple-binary-encoding/blob/master/CONTRIBUTING.md All new files added to the project must include this header, which specifies the Apache 2.0 license and copyright information. ```java /* * Copyright 2013-2025 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ``` -------------------------------- ### Decode SBE IR from File Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Cpp-OTF-User-Guide Loads the Simple Binary Encoding Intermediate Representation (IR) from a file using IrDecoder. Handles potential loading errors. ```cpp IrDecoder irDecoder; if (irDecoder.decode("generated/example-schema.sbeir") != 0) { std::cerr << "could not load SBE IR\n"; return -1; } ``` -------------------------------- ### Configure SBE C Code Generation Source: https://github.com/aeron-io/simple-binary-encoding/blob/master/sbe-tool/src/test/c/CMakeLists.txt Sets up a custom CMake command to generate C source and header files from SBE XML schemas using the SBE JAR. It specifies output directories, target language, and schema files. ```cmake set(CODE_GENERATION_SCHEMA ${CODEC_SCHEMA_DIR}/code-generation-schema.xml) set(CODE_GENERATION_SCHEMA_WITH_VERSION ${CODEC_SCHEMA_DIR}/code-generation-schema-with-version.xml) set(GROUP_WITH_DATA_SCHEMA ${CODEC_SCHEMA_DIR}/group-with-data-schema.xml) set(ISSUE889_SCHEMA ${CODEC_SCHEMA_DIR}/issue889.xml) set(GENERATED_CODECS ${C_CODEC_TARGET_DIR} ) add_custom_command( OUTPUT ${GENERATED_CODECS} DEPENDS sbe-jar ${SBE_JAR} ${CODE_GENERATION_SCHEMA} ${CODE_GENERATION_SCHEMA_WITH_VERSION} ${GROUP_WITH_DATA_SCHEMA} ${ISSUE889_SCHEMA} COMMAND ${Java_JAVA_EXECUTABLE} --add-opens java.base/jdk.internal.misc=ALL-UNNAMED -Dsbe.output.dir=${C_CODEC_TARGET_DIR} -Dsbe.target.language="C" -Dsbe.keyword.append.token="X" -jar ${SBE_JAR} ${CODE_GENERATION_SCHEMA} ${CODE_GENERATION_SCHEMA_WITH_VERSION} ${GROUP_WITH_DATA_SCHEMA} ${ISSUE889_SCHEMA} ) ``` -------------------------------- ### Encode BitSet Flags in C++ Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Cpp-User-Guide Initialize the bitset using `clear()`, then set individual flags to true or false. Ensure the bitset is cleared before encoding. ```cpp car.extras().clear() .cruiseControl(true) .sportsPack(true) .sunRoof(false); ``` -------------------------------- ### Decode BitSet Flags in C++ Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Cpp-User-Guide Access the bitset flyweight and use the getter methods to retrieve the state of each flag. Append the flag values to a string builder. ```cpp OptionalExtras &extras = car.extras(); sb.append("\ncar.extras.cruiseControl=").append(extras.cruiseControl()); sb.append("\ncar.extras.sportsPack=").append(extras.sportsPack()); sb.append("\ncar.extras.sunRoof=").append(extras.sunRoof()); ``` -------------------------------- ### Encode Message Header in C# Source: https://github.com/aeron-io/simple-binary-encoding/wiki/CSharp-User-Guide Shows how to encode a message header using the C# SBE implementation. The header includes block length, schema ID, template ID, and version, which are essential for decoding. ```csharp // First the message header messageHeader = new baseline.MessageHeader(); messageHeader.Wrap(directBuffer, bufferOffset, Car.Schemaversion); messageHeader.BlockLength = Car.BlockLength; messageHeader.SchemaId = Car.SchemaId; messageHeader.TemplateId = Car.TemplateId; messageHeader.Version = Car.Schemaversion; bufferOffset += MessageHeader.Size; // Then the message var car = new Car(); car.WrapForEncode(directBuffer, bufferOffset); // Populate the cars values (see below) ``` -------------------------------- ### Iterating Over Fixed Length Arrays in Go Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Golang-User-Guide Shows how to iterate over and modify elements of a fixed-length array field in a Go struct generated by SBE. ```go for i := 0; i < len(car.SomeNumbers); i++ { car.SomeNumbers[i] = i; } ``` -------------------------------- ### Handle Repeating Group Begin/End in C++ Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Cpp-OTF-User-Guide Manages scope for repeating groups by pushing and popping the group name onto a stack. Called at the beginning and end of each group iteration. ```cpp virtual void onBeginGroup( Token& token, std::uint64_t groupIndex, std::uint64_t numInGroup) { scope.push_back(token.name() + "."); } ``` ```cpp virtual void onEndGroup( Token& token, std::uint64_t groupIndex, std::uint64_t numInGroup) { scope.pop_back(); } ``` -------------------------------- ### Helper Function to Convert Encoded Data to String Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Cpp-OTF-User-Guide This helper function converts various primitive types (integers, characters, floats, doubles) from a buffer into a string representation. It handles both single values and fixed-length arrays, and differentiates between constant and non-constant encodings. ```C++ std::string asString(const Token& token, const char *buffer) { const Encoding& encoding = token.encoding(); const PrimitiveType type = encoding.primitiveType(); const std::uint64_t length = (token.isConstantEncoding()) ? encoding.constValue().size() : static_cast(token.encodedLength()); std::ostringstream result; std::uint64_t num = length / lengthOfType(type); switch (type) { case PrimitiveType::CHAR: { if (num > 1) { if (token.isConstantEncoding()) { buffer = encoding.constValue().getArray(); } result << std::string(buffer, length); } break; } case PrimitiveType::INT8: case PrimitiveType::INT16: case PrimitiveType::INT32: case PrimitiveType::INT64: { if (num > 1) { const char *separator = ""; for (size_t i = 0; i < num; i++) { result << separator << Encoding::getInt(type, encoding.byteOrder(), buffer + (i * lengthOfType(type))); separator = ", "; } } else { if (token.isConstantEncoding()) { result << encoding.constValue().getAsInt(); } else { result << encoding.getAsInt(buffer); } } break; } case PrimitiveType::UINT8: case PrimitiveType::UINT16: case PrimitiveType::UINT32: case PrimitiveType::UINT64: { if (num == 1) { if (token.isConstantEncoding()) { result << encoding.constValue().getAsUInt(); } else { result << encoding.getAsUInt(buffer); } } break; } case PrimitiveType::FLOAT: case PrimitiveType::DOUBLE: { if (num == 1) { result.setf(std::ios::fixed); result << std::setprecision(1) << encoding.getAsDouble(buffer); } break; } default: { break; } } return result.str(); } ``` -------------------------------- ### Decoding Variable Length Data in C++ Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Cpp-OTF-User-Guide Implement this callback to handle the decoding of variable-length strings or binary blobs. It receives the buffer and its length for processing. ```C++ virtual void onVarData( Token& fieldToken, const char *buffer, std::uint64_t length, Token& typeToken) { printScope(); std::cout << fieldToken.name() << "=" << std::string(buffer, length) << "\n"; } ``` -------------------------------- ### Define SBE C Test Executable Function Source: https://github.com/aeron-io/simple-binary-encoding/blob/master/sbe-tool/src/test/c/CMakeLists.txt Defines a reusable CMake function to create test executables for the SBE C codec. It handles adding the executable, dependencies, include directories, compile options, and test definitions. ```cmake function(sbe_test name) add_executable("C${name}" "${name}.cpp") add_dependencies(C${name} gmock) target_include_directories("C${name}" PRIVATE ${C_CODEC_TARGET_DIR} ) target_compile_options("C${name}" PRIVATE $<$:-Werror>) target_compile_options("C${name}" PRIVATE $<$:-Werror>) target_compile_options("C${name}" PRIVATE $<$:-Werror -Wno-maybe-uninitialized>) target_link_libraries("C${name}" gmock_main ${CMAKE_THREAD_LIBS_INIT}) add_test(NAME C${name} COMMAND C${name} WORKING_DIRECTORY ${C_CODEC_TARGET_DIR}) if (${ARGC} GREATER 1) add_dependencies(C${name} ${ARGV1}) endif () endfunction() ``` -------------------------------- ### Golang Representation of SBE Variable Length Data Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Golang-User-Guide Explains that variable-length data in SBE, used for binary data and strings, is represented as slices in Golang, behaving similarly to repeating groups. ```go variableLengthData := car.SomeVariableDataField ``` -------------------------------- ### Decode Primitive Fields as String in Java Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Java-OTF-User-Guide Override this method to decode primitive fields and print their values as strings. Handles constant and optional fields using metadata. ```Java public void onEncoding( final Token fieldToken, final DirectBuffer buffer, final int index, final Token typeToken, final int actingVersion) { final CharSequence value = readEncodingAsString(buffer, index, typeToken, actingVersion); printScope(); out.append(fieldToken.name()) .append('=') .append(value) .println(); } private static CharSequence readEncodingAsString( final DirectBuffer buffer, final int index, final Token typeToken, final int actingVersion) { final PrimitiveValue constOrNotPresentValue = constOrNotPresentValue(typeToken, actingVersion); if (null != constOrNotPresentValue) { return constOrNotPresentValue.toString(); } final StringBuilder sb = new StringBuilder(); final Encoding encoding = typeToken.encoding(); final int elementSize = encoding.primitiveType().size(); for (int i = 0, size = typeToken.arrayLength(); i < size; i++) { mapEncodingToString(sb, buffer, index + (i * elementSize), encoding); sb.append(", "); } sb.setLength(sb.length() - 2); return sb; } private long readEncodingAsLong( final DirectBuffer buffer, final int bufferIndex, final Token typeToken, final int actingVersion) { final PrimitiveValue constOrNotPresentValue = constOrNotPresentValue(typeToken, actingVersion); if (null != constOrNotPresentValue) { return constOrNotPresentValue.longValue(); } return getLong(buffer, bufferIndex, typeToken.encoding()); } ``` -------------------------------- ### Encode Variable Length Data in C++ Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Cpp-User-Guide Use `putManufacturer` and `putModel` to encode variable length strings. Ensure the length is correctly provided using `strlen`. ```cpp car.putManufacturer(MANUFACTURER, strlen(MANUFACTURER)); car.putModel(MODEL, strlen(MODEL)); ``` -------------------------------- ### Decode SBE Message Header in Go Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Golang-User-Guide Decodes the SBE message header from a reader. This is the first step in decoding an SBE message. ```go var header SbeGoMessageHeader m := NewSbeGoMarshaller() header.Decode(m, reader) ``` -------------------------------- ### Define C++ Test Executable Source: https://github.com/aeron-io/simple-binary-encoding/blob/master/sbe-tool/src/test/cpp/CMakeLists.txt Defines a CMake function to create a C++ executable for testing SBE generated code. It includes setting up include directories, compile options, and linking libraries. ```cmake function(sbe_test name) add_executable("${name}" "${name}.cpp") add_dependencies(${name} gmock) target_include_directories("${name}" PRIVATE ${CXX_CODEC_TARGET_DIR} ) target_compile_options("${name}" PRIVATE $<$:-Werror>) target_compile_options("${name}" PRIVATE $<$:-Werror>) target_compile_options("${name}" PRIVATE $<$:-Werror>) target_link_libraries("${name}" sbe gmock_main ${CMAKE_THREAD_LIBS_INIT}) add_test(NAME ${name} COMMAND ${name} WORKING_DIRECTORY ${CXX_CODEC_TARGET_DIR}) if (${ARGC} GREATER 1) add_dependencies(${name} ${ARGV1}) endif () endfunction() ``` -------------------------------- ### Handle Composite Begin/End in C++ Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Cpp-OTF-User-Guide Manages scope for composite fields by pushing and popping the composite name onto a stack. Called at the beginning and end of a composite structure. ```cpp virtual void onBeginComposite( Token& fieldToken, std::vector& tokens, std::size_t fromIndex, std::size_t toIndex) { scope.push_back(fieldToken.name() + "."); } ``` ```cpp virtual void onEndComposite( Token& fieldToken, std::vector& tokens, std::size_t fromIndex, std::size_t toIndex) { scope.pop_back(); } ``` -------------------------------- ### Configure SBE Code Generation Source: https://github.com/aeron-io/simple-binary-encoding/blob/master/sbe-tool/src/test/cpp/CMakeLists.txt Configures a custom CMake command to generate C++ codecs from various SBE XML schemas. It specifies output directories, target language, and various generation flags. ```cmake set(CODE_GENERATION_SCHEMA ${CODEC_SCHEMA_DIR}/code-generation-schema.xml) set(COMPOSITE_ELEMENTS_SCHEMA ${CODEC_SCHEMA_DIR}/composite-elements-schema.xml) set(COMPOSITE_OFFSETS_SCHEMA ${CODEC_SCHEMA_DIR}/composite-offsets-schema.xml) set(MESSAGE_BLOCK_LENGTH_TEST ${CODEC_SCHEMA_DIR}/message-block-length-test.xml) set(GROUP_WITH_DATA_SCHEMA ${CODEC_SCHEMA_DIR}/group-with-data-schema.xml) set(DTO_SCHEMA ${CODEC_SCHEMA_DIR}/dto-test-schema.xml) set(ISSUE835_SCHEMA ${CODEC_SCHEMA_DIR}/issue835.xml) set(ISSUE889_SCHEMA ${CODEC_SCHEMA_DIR}/issue889.xml) set(ACCESS_ORDER_SCHEMA ${CODEC_SCHEMA_DIR}/field-order-check-schema.xml) set(VERSIONED_MESSAGE_V1_SCHEMA ${CODEC_SCHEMA_DIR}/versioned-message-v1.xml) set(VERSIONED_MESSAGE_V2_SCHEMA ${CODEC_SCHEMA_DIR}/versioned-message-v2.xml) set(GENERATED_CODECS ${CXX_CODEC_TARGET_DIR} ) add_custom_command( OUTPUT ${GENERATED_CODECS} DEPENDS ${CODE_GENERATION_SCHEMA} ${COMPOSITE_ELEMENTS_SCHEMA} ${COMPOSITE_OFFSETS_SCHEMA} ${MESSAGE_BLOCK_LENGTH_TEST} ${GROUP_WITH_DATA_SCHEMA} ${DTO_SCHEMA} ${ISSUE835_SCHEMA} ${ISSUE889_SCHEMA} ${ACCESS_ORDER_SCHEMA} ${VERSIONED_MESSAGE_V1_SCHEMA} ${VERSIONED_MESSAGE_V2_SCHEMA} sbe-jar ${SBE_JAR} COMMAND ${Java_JAVA_EXECUTABLE} --add-opens java.base/jdk.internal.misc=ALL-UNNAMED -Dsbe.output.dir=${CXX_CODEC_TARGET_DIR} -Dsbe.generate.ir="true" -Dsbe.target.language="cpp" -Dsbe.generate.precedence.checks="true" -Dsbe.precedence.checks.flag.name="SBE_ENABLE_PRECEDENCE_CHECKS_IN_TESTS" -Dsbe.cpp.disable.implicit.copying="true" -Dsbe.keyword.append.token="X" -Dsbe.cpp.generate.dtos="true" -jar ${SBE_JAR} ${CODE_GENERATION_SCHEMA} ${COMPOSITE_OFFSETS_SCHEMA} ${MESSAGE_BLOCK_LENGTH_TEST} ${GROUP_WITH_DATA_SCHEMA} ${COMPOSITE_ELEMENTS_SCHEMA} ${DTO_SCHEMA} ${ISSUE835_SCHEMA} ${ISSUE889_SCHEMA} ${ACCESS_ORDER_SCHEMA} ${VERSIONED_MESSAGE_V1_SCHEMA} ${VERSIONED_MESSAGE_V2_SCHEMA} ) add_custom_target(codecs DEPENDS ${GENERATED_CODECS}) ``` -------------------------------- ### Define a Bit Set with Element Source: https://github.com/aeron-io/simple-binary-encoding/wiki/FIX-SBE-XML-Primer Use the element to define bit sets, specifying choices for each bit position. The encodingType must be a uint8, uint16, uint32, or uint64. ```xml 0 1 2 ``` -------------------------------- ### Encode Single Fixed Fields in C# Source: https://github.com/aeron-io/simple-binary-encoding/wiki/CSharp-User-Guide Demonstrates setting single fixed-length fields for a message in C#. This includes primitive types like integers and booleans. ```csharp car.SerialNumber = 1234; car.Available = BooleanType.T; ``` -------------------------------- ### Decode Fixed Length Array Fields in C# Source: https://github.com/aeron-io/simple-binary-encoding/wiki/CSharp-User-Guide Demonstrates decoding a fixed-length array of primitive values in C#. It iterates through the array and retrieves each element. ```csharp sb.Append("\ncar.someNumbers="); for (int i = 0, size = car.SomeNumbersLength; i < size; i++) { sb.Append(car.GetSomeNumbers(i)).Append(", "); } ``` -------------------------------- ### Encode Variable Length Data in Java Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Java-Users-Guide Encodes variable length string and binary data using the Simple Binary Encoding library in Java. Ensure data is put in order as defined in the schema. ```java car.manufacturer(new String(MANUFACTURER)); car.putModel(MODEL, srcOffset, MODEL.length); ``` -------------------------------- ### Create OTF Header Decoder Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Java-OTF-User-Guide Creates an OTFHeaderDecoder from the IR's header structure. This decoder is used to read message headers. ```Java // From the IR we can create OTF decoder for message headers. final OtfHeaderDecoder headerDecoder = new OtfHeaderDecoder(ir.headerStructure()); ``` -------------------------------- ### Handle Repeating Group Header in C++ Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Cpp-OTF-User-Guide Processes the header for repeating groups, printing the group name and the number of items within the group. ```cpp virtual void onGroupHeader( Token& token, std::uint64_t numInGroup) { printScope(); std::cout << token.name() << " Group Header: numInGroup=" << numInGroup << "\n"; } ``` -------------------------------- ### Decode Variable Length Data in Java Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Java-OTF-User-Guide Callback method for decoding variable-length strings or binary blobs. Handles character encoding and potential exceptions. ```java public void onVarData( final Token fieldToken, final DirectBuffer buffer, final int bufferIndex, final int length, final Token typeToken) { final String value; try { buffer.getBytes(bufferIndex, tempBuffer, 0, length); value = new String(tempBuffer, 0, length, typeToken.encoding().characterEncoding()); } catch (final UnsupportedEncodingException ex) { ex.printStackTrace(); return; } printScope(); out.append(fieldToken.name()) .append('=') .append(value) .println(); } ``` -------------------------------- ### Encode Fixed Length Array Fields in C# Source: https://github.com/aeron-io/simple-binary-encoding/wiki/CSharp-User-Guide Illustrates encoding a fixed-length array of primitive values in C#. It iterates through the array and sets each element. ```csharp for (int i = 0, size = car.SomeNumbersLength; i < size; i++) { car.SetSomeNumbers(i, (uint)i); } ``` -------------------------------- ### Decode BitSet Fields in Java Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Java-Users-Guide Decode bitset fields by accessing the `extras` flyweight and then querying the state of individual bits using methods like `cruiseControl()` and `sportsPack()`. ```java final OptionalExtrasDecoder extras = car.extras(); sb.append("\ncar.extras.cruiseControl=").append(extras.cruiseControl()); sb.append("\ncar.extras.sportsPack=").append(extras.sportsPack()); sb.append("\ncar.extras.sunRoof=").append(extras.sunRoof()); ``` -------------------------------- ### Encode Single Fixed Fields in C++ Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Cpp-User-Guide Encodes single fixed fields using a fluent interface after resetting the message flyweight for encoding. Ensure the buffer, offset, and length are correctly managed. ```cpp car.wrapForEncode(buffer, bufferOffset, bufferLength) .serialNumber(1234) .modelYear(2013); ``` -------------------------------- ### Decode Variable Length Data in C++ Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Cpp-User-Guide Use `getManufacturer` and `getModel` to decode variable length data into a temporary buffer. The `bytesCopied` return value is important for appending the correct number of characters. ```cpp char tmp[80]; bytesCopied = car.getManufacturer(tmp, sizeof(tmp)); sb.append("\ncar.manufacturer=").append(tmp, bytesCopied); sb.append("\ncar.manufacturerCharacterEncoding=").append(car.manufacturerCharacterEncoding()); bytesCopied = car.getModel(tmp, sizeof(tmp)); sb.append("\ncar.model=").append(tmp, bytesCopied); sb.append("\ncar.modelCharacterEncoding=").append(car.modelCharacterEncoding()); ``` -------------------------------- ### Encode SBE Message Header in Go Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Golang-User-Guide Encodes the SBE message header before encoding the message body. Requires a bytes.Buffer to write the encoded header. ```go var car Car var buf = new(bytes.Buffer) m := NewSbeGoMarshaller() header := SbeGoMessageHeader{car.SbeBLockLength(), car.SbeTemplateId(), car.SbeSchemaId(), car.SbeSchemaVersion()} header.Encode(m, buf) ``` -------------------------------- ### Decode Single Fixed Fields in C# Source: https://github.com/aeron-io/simple-binary-encoding/wiki/CSharp-User-Guide Shows how to decode and read single fixed-length fields from a message in C#. This is the reverse operation of encoding. ```csharp var sb = new StringBuilder(); sb.Append("\ncar.serialNumber=").Append(car.SerialNumber); sb.Append("\ncar.available=").Append(car.Available); ``` -------------------------------- ### Decode Message Header in C# Source: https://github.com/aeron-io/simple-binary-encoding/wiki/CSharp-User-Guide Illustrates how to decode a message header in C#. The decoded header information (block length, version) is used to determine the correct SBE decoder for the message body. ```csharp // first we decode the header (in a real world scenario you would need the header to decide which SBE decoder you are going to use bufferOffset = 0; // position the MessageHeader object at the beginning of the array MessageHeader.Wrap(directBuffer, bufferOffset, Car.SchemaVersion); // Extract info from the header which you would use to lookup the // applicable flyweight to decode this type of message based on templateId and version. int actingBlockLength = MessageHeader.BlockLength; int actingVersion = MessageHeader.Version; bufferOffset += MessageHeader.Size; // now we decode the message CarExample.Decode(Car, directBuffer, bufferOffset, actingBlockLength, actingVersion); // We can then directly read fields. (see below) ``` -------------------------------- ### Decode Fixed Array of Primitives in C++ Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Cpp-User-Guide Iterate through the array elements to decode them. Append each decoded element to a string builder for display. ```cpp sb.append("\ncar.someNumbers="); for (int i = 0, size = car.someNumbersLength(); i < size; i++) { sb.append(car.someNumbers(i)).append(", "); } ``` -------------------------------- ### Decode Enumeration Values in C++ Source: https://github.com/aeron-io/simple-binary-encoding/wiki/Cpp-User-Guide Decode enumeration values by calling the getter methods on the flyweight. Append the decoded values to a string builder. ```cpp sb.append("\ncar.available=").append(car.available()); sb.append("\ncar.code=").append(car.code()); ```