Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is syntax for byte_size in pattern matching?

How to match and what syntax is to check byte_size equal 12 length pattern in handle_info()? Can I use both patterns in handle_info(), eg. first that will check string for new line, second with byte_size?

Example code without byte_size pattern:

def init(_) do
  {:ok, []}
end

def handle_info({:elixir_serial, serial, "\n"}, state) do
  {:noreply, Enum.reverse(state)}
end

def handle_info({:elixir_serial, serial, data}, state) do
  Logger.debug "data: #{data}"
  {:noreply, [data | state]}
end
like image 987
luzny Avatar asked Oct 26 '15 17:10

luzny


1 Answers

Yes, you can use both patterns, this is the purpose of having multiple function clauses. From top to bottom, the first matching function clause will be executed.

You can use different binary patterns to match 12 bytes, depending on which output you need:

iex> <<data::bytes-size(12)>> = "abcdefghijkl"
"abcdefghijkl"
iex> data
"abcdefghijkl"

iex> <<data::size(96)>> = "abcdefghijkl"
"abcdefghijkl"
iex> data
30138990049255557934854335340

These patterns can of course be used in your function clauses:

def handle_info({:elixir_serial, serial, <<data::bytes-size(12)>>}, state) do
  # ...
end

def handle_info({:elixir_serial, serial, <<data::size(96)>>}, state) do
  # ...
end

For more info on available types and modifiers, you can look up the documentation of the bitstring syntax online or in iex by typing h <<>>.

You could also use a guard clause together with byte_size:

def handle_info({:elixir_serial, serial, data}, state) when byte_size(data) == 12 do
  # ...
end
like image 58
Patrick Oscity Avatar answered Oct 13 '22 12:10

Patrick Oscity