The following implements a simple codec using scodec
The result is a representation whose size depends on number of Data instances in the Container. Many use cases require a fixed size representation. The following code pads to 5 Data instances, i.e. 40 bits. This approach is only acceptable if the use case requires trailing padding with zero bits. Note also the unfortunate coupling to the size of Data representation.
This code pads the representation with Data(13,14). The two limitations of fixedSizeRepresentation no longer apply and the coupling to the size of the Data representation is eliminated. However, it does require that the pad value can be represented by Data. The pad values are often illegal within the domain and would be rejected by any validation attached to Data.
This code pads the representation with specific bytes. It allows the usage of any pad values, at the cost of even greater coupling to the Data representation.
This code resolves all of the above issues, by providing a separate codec to generate the pad representation.
There is some coupling between the tuples that represent the pad value and Data. That seems unavoidable and the compiler will help to catch many of the possible errors.
The above code is suboptimal if the cost of encoding the pad value is high. The following caches the result of the encoding.
Finally an example where the padding leads the actual data.
It might be reasonable to extend the standard scodec combinators to better handle these cases.