Allow setting custom field packer and unpacker #310
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Currently, all
Pack
andUnpack
methods of the fields (exceptComposite
) do the same steps. These steps were extracted into theDefaultPacker
.We also introduced
Packer
andUnpacker
interfaces, so you can create custom implementation to pack/unpack any field you have.Here is an example of when such a change can be helpful.
Problem
The default behavior of the field packer and unpacker may not meet your requirements. For instance, you might need the length prefix to represent the length of the encoded data, not the field value. This is often necessary when using BCD or HEX encoding, where the field value's length differs from the encoded field value's length.
Example Requirement:
Default Behavior
Let's explore the default behavior of a Numeric field:
Here, the length is expected to be 2 bytes since 123 encoded in BCD is 0x01, 0x23. By default, the length prefix will contain the field value's length, which is 3 digits, resulting in a length prefix of 0x03.
Custom Packer and Unpacker
Let's create a custom packer and unpacker for the Numeric field to pack the field value as BCD and set the length prefix to the length of the encoded field value.
In this case, the length is expected to be 2 bytes since 123 encoded in BCD is 0x01, 0x23. Thus, the length prefix is 0x02, indicating the length of the packed data is 2 bytes.