I am reading a binary file, and inside it there is a structure in which the first byte of data indicates the type of data following it. I am trying to deal with this by matching with a pattern, and I am having problems.
I tried several ways that I thought might work, none of them work. You can see my weak attempts below:
defmodule Test do def build(<< 0x11, rest >>) do "11!" end def build(<< 0x12, rest :: size(4) >>) do "12!" end def build(<< type, rest >>) when type == 0x13 do "13!" end def build(bytes) do "Unknown!" end end [ << 0x11, 0x01, 0x02, 0x03, 0x04 >>, << 0x12, 0x01, 0x02, 0x03, 0x04 >>, << 0x13, 0x01, 0x02, 0x03, 0x04 >> ] |> Enum.map(&Test.build/1) |> IO.inspect
I would like to receive: ["11!", "12!", "13!"] .
The data matched with them is a fixed size (in this case, 5 total bytes). This SO question seems to suggest me to also indicate the total size? Not sure how to do this.
In the end, I'm not interested in the value of the first byte if the methods are sent by matching, so rest is the only thing I really need in every body of the method. What am I missing?
pattern-matching elixir
Nick veys
source share