How binary size works in Elixir

I am currently trying to understand how it binary-size(number)works in Elixir. In the example from the Little Elixir and OTP tutorials, there is a section where they break the 128-byte ID3 tag. The tag has the following properties:

  • 3 byte header
  • 30 byte tag header
  • 30 byte artist tag
  • 30 byte album tag
  • 4-byte tag of the year
  • Vacation Packed

The way they extract it in a book,

<< "TAG", title :: binary-size(30), artist :: binary-size(30), album :: binary-size(30), year:: binary-size(4), _ :: binary >>

I am having trouble understanding how each value gets the correct value from binary-size(#num). Maybe this is the order in which pattern matching occurs, and it’s hard for me to figure it out. I am currently approaching it since the first pattern matches the header, which is three bytes, since it is hardcoded as "TAG", at this point I am not sure how we can get the value of 30 bytes from binary-size(30). Is this operation divided into two separate parts? We say that first from 128, the total byte size, we subtract 30, and then assign a size value (30) to the header, and then transfer this updated size to each value in the match of the binary patterns, propagating any changes along the way?

+4
source share
1

, , Elixir , .

-, , , binary-size(30) binary - size(30).

, , , 30 (, 30 ), , 30 .

, :

iex(1)> string = "binary matching string"
"binary matching string"
iex(2)> <<head::binary-size(1), _rest::binary>> = string
"binary matching string"
iex(3)> head
"b"

, , head " " , b.

_rest .

. << >> ​​elixir, binary size, , , , val::binary-size(1) val::size(8) ( ).

iex(4)> <<head::size(8), _rest::binary>> = string
"binary matching string"
iex(5)> head
98
iex(6)> <<head>>
"b"

, IEX h <<>> .

+9

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


All Articles