Open cmkarlsson opened 7 years ago
As far as I know, this is not possible in the BEAM.
Binary sizes for everything but the "tail" has to be known at compiletime.
This is definitely possible in the BEAM. Elixir:
iex(1)> s = 5
5
iex(2)> <<x::binary-size(s), rest::binary>> = "foobarbaz"
"foobarbaz"
iex(3)> x
"fooba"
iex(4)> rest
"rbaz"
Oh, either I missed a change in the BEAM or I am missremembering some details around this...
BEAM does not support having a variable length for any chunk except the last even if it can be easily calculated manually by subtracting the size of the binary and the size of the last chunk. You may be misremembering that.
iex(5)> <<x::binary, rest::binary-size(2)>> = "foobarbaz"
** (CompileError) iex:5: a binary field without size is only allowed at the end of a binary pattern and never allowed in binary generators
I often have the need to pattern match binaries on dynamic sizes. Currently this is not possible in alpaca (which gives
{invalid_bin_qualifier,<<"s">>}
)An example:
I think it would make sense to have the size being expressed as any expression returning an integer.
Tested with alpaca 620b9fa134cc68e7342b29bcdb4baf6e5482e1f3