Skip to content

Handling Nulls

Variable Length Strings

Null strings encoded using a variable length string encoder are returned as empty strings. The sample nullStringReturnsAsEmptyString shows the effect in action.

encoder.message2(null);
//decode
Assertions.assertEquals("", decoder.message2());

Numbers

Number fields do not support nulls, however a magic number can be assigned to represent null. If you do not provide one, SBE uses a default value. If null is required, the generated xxxxNullValue can be used. Then, when reading, convert the generated Null value back to null.

Here's an example defining a null magic number as 33; of course you would need to select a valid value for your particular usage:

<composite name="composite" description="Sample Composite type">
    <type name="field1" primitiveType="uint16" nullValue="33"/>
</composite>

You can retrieve the magic number for a field via the NullValue method, for example:

CompositeDecoder.field1NullValue()

Repeating Groups

Working with repeating groups is simple for both encoding and decoding data.

Encoding

  • First, declare the group size
  • For each item in the group:
  • Iterate to the next item
  • Apply values.
final SampleGroupEncoder encoder = new SampleGroupEncoder();
final MessageHeaderEncoder messageHeaderEncoder = new MessageHeaderEncoder();
final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);
final UnsafeBuffer directBuffer = new UnsafeBuffer(byteBuffer);

encoder.wrapAndApplyHeader(directBuffer, 0, messageHeaderEncoder);
encoder.timestamp(1000L);

SampleGroupEncoder.GroupEncoder groupEncoder = encoder.groupCount(2);
groupEncoder.next();
groupEncoder.groupField1(1);
groupEncoder.groupField2(2);
groupEncoder.groupField3(MESSAGE_2);

groupEncoder.next();
groupEncoder.groupField1(1);
groupEncoder.groupField2(2);
groupEncoder.groupField3(MESSAGE_2);

encoder.message(MESSAGE_1);

Decoding

The decoder generates an Iterable, which makes group processing simpler.

final SampleGroupDecoder decoder = new SampleGroupDecoder();
final MessageHeaderDecoder headerDecoder = new MessageHeaderDecoder();
int bufferOffset = 0;
headerDecoder.wrap(directBuffer, bufferOffset);

...

bufferOffset += headerDecoder.encodedLength();
decoder.wrap(directBuffer, bufferOffset, actingBlockLength, actingVersion);
assertEquals(1000L, decoder.timestamp());

for (final SampleGroupDecoder.GroupDecoder groupDecoder : decoder.group())
{
    assertEquals(1, groupDecoder.groupField1());
    assertEquals(2, groupDecoder.groupField2());
    assertEquals(MESSAGE_2, groupDecoder.groupField3());
}

assertEquals(MESSAGE_1, decoder.message());

See canWriteReadSampleRepeatGroups in the sample.

Back to top