<div dir="ltr"><div dir="ltr"><div class="gmail_default" style="font-family:arial,helvetica,sans-serif"></div><div class="gmail_default" style="font-family:arial,helvetica,sans-serif"><span style="font-family:Arial,Helvetica,sans-serif">On Tue, Jul 14, 2020 at 10:57 PM Oliver Korpilla <<a href="mailto:Oliver.Korpilla@gmx.de">Oliver.Korpilla@gmx.de</a>> wrote:</span><br></div></div><div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><br>
extract(<< >>) -> [];<br>
extract(<< Header:8, X/binary>>) -><br>
Bits = Header * 8,<br>
<< Length:Bits, Y/binary >> = X,<br>
Payload = binary:part(Y, 0, Length),<br>
Rest = binary:part(Y, Length, byte_size(Y) - Length),<br>
Result = { Header, Length, Payload },<br>
[ Result | extract(Rest) ].<br>
</blockquote><div><br></div><div class="gmail_default" style="font-family:arial,helvetica,sans-serif">You can match directly on the length, which simplifies it a bit:</div><div class="gmail_default" style="font-family:arial,helvetica,sans-serif"><br></div>decode(<<Header:8, X/binary>>) -><br> L = Header*8,<br> <<Length:L/integer, Payload:Length/binary, Rest/binary>> = X,<br> [{Header, Length, Payload} | decode(Rest)];<br>decode(<<>>) -><br> [].<br><br><div class="gmail_default" style="font-family:arial,helvetica,sans-serif">You avoid having to mangle with binary:part/3. However, if there are only 4 headers, the following is also quite readable:</div><br>decode(<<1, L:8/integer, Payload:L/binary, Rest/binary>>) -> [{1, L, Payload} | decode(Rest)];<br>decode(<<2, L:16/integer, Payload:L/binary, Rest/binary>>) -> [{2, L, Payload} | decode(Rest)];<br>decode(<<3, L:24/integer, Payload:L/binary, Rest/binary>>) -> [{3, L, Payload} | decode(Rest)];<br>decode(<<4, L:32/integer, Payload:L/binary, Rest/binary>>) -> [{4, L, Payload} | decode(Rest)];<br>decode(<<>>) -> [].<br><div class="gmail_default" style="font-family:arial,helvetica,sans-serif"></div><div class="gmail_default" style="font-family:arial,helvetica,sans-serif">It repeats, but it is pretty clear what is going on I think. If you are not interested in the header type, you can possibly factor this out of the recursive loop, which makes it even nicer to look at.</div><div class="gmail_default" style="font-family:arial,helvetica,sans-serif"><br></div></div><div dir="ltr" class="gmail_signature">J.</div></div>