Read/Write order matters¶
Since SBE does not hold any data about the layout of the buffer and also supports variable length fields, it has to rely on the developer to use it as specified. This means reading and writing the data in the exact field order specified in the XML. If you do not follow this order, you should expect strange read results.
Here's an example showing this in action. This SBE message has two sequence types followed by two string types:
<sbe:message name="SampleCorruption" id="2" description="Corruption sample">
<field name="sequence1" id="1" type="Sequence"/>
<field name="sequence2" id="2" type="Sequence"/>
<data name="message1" id="3" type="varStringEncoding"/>
<data name="message2" id="4" type="varStringEncoding"/>
</sbe:message>
If we write the message in the an incorrect order, we can see unexpected results. With message a
being written to message1
, we should expect message1
to be message a
when read.
encoder.wrapAndApplyHeader(directBuffer, 0, messageHeaderEncoder);
encoder.message2("a message");
encoder.message1("message a");
encoder.sequence1(123L);
encoder.sequence2(321L);
If we read it as follows, with an assertion that message1
has the value message a
:
Assertions.assertEquals(123, decoder.sequence1());
Assertions.assertEquals("message a", decoder.message1());
Assertions.assertEquals(321, decoder.sequence2());
Assertions.assertEquals("a message", decoder.message2());
We can see the assertion fail with message1
having the value for message2
, a message
.
com.aeroncookbook.sbe.SbeTests > dataCanBeCorrupted() FAILED
org.opentest4j.AssertionFailedError: expected: <message a> but was: <a message>
See dataCanBeCorrupted
and dataCanBeReadCorrectlyWhenWrittenCorrectly
in the test provided with the sample project.