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());
```