What is the syntax for byte_size versus pattern?

How to combine and what syntax to check byte_size equal 12 long pattern in handle_info() ? Can I use both templates in handle_info() , for example. first check the line for a new line, the second with byte_size ?

Sample code without a byte_size template:

 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 
+5
source share
1 answer

Yes, you can use both templates, this is the purpose of several functions. From top to bottom, the first sentence of the matching function will be executed.

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

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

These templates can, of course, be used in your feature suggestions:

 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 information on the types and modifiers available, you can find documentation on bit string syntax online or in iex by typing h <<>> .

You can also use the guard clause with byte_size :

 def handle_info({:elixir_serial, serial, data}, state) when byte_size(data) == 12 do # ... end 
+4
source

Source: https://habr.com/ru/post/1234547/


All Articles