bschmeck

bschmeck

Dynamic pattern matching of binaries in function heads?

Do binary patterns declared in function heads have to have static sizes? It appears to be the case, but I can’t find documentation one way or the other.

More concretely, it is possible to match a binary with a “#” as the third byte like this:

def foo(<<header::binary-size(2), "#", rest::binary>>), do: something()

But this attempt to make the size of the header dynamic results in an error:

def foo(<<header::binary-size(n), "#", rest::binary>>, n), do: something()

** (CompileError) iex:46: undefined variable "n"

Interestingly, flipping the order of the arguments to the function results in a slightly different error:

def foo(n, <<header::binary-size(n), "#", rest::binary>>), do: something()

** (CompileError) iex:46: undefined variable "n" in bitstring segment. If the size of the binary is a variable, the variable must be defined prior to its use in the binary/bitstring match itself, or outside the pattern match

That error message makes it seem like what I’m trying to do is not possible, but maybe I’m just missing something?

Marked As Solved

g-andrade

g-andrade

If the size itself precedes the binary data and can be decoded using bitsyntax, this can be done (assuming size is a one-byte unsigned integer):

def foo(<<n::integer, header::binary-size(n), "#", rest::binary>>), do: something()

But not much else beyond leveraging other encodings (bitsize, endianness) of the size prefix, unfortunately.

Also Liked

g-andrade

g-andrade

E.g. in a shell:

# <<n::integer, data::binary-size(n), "#", rest::binary>> = <<5, "hello#rest">>
<<5, 104, 101, 108, 108, 111, 35, 114, 101, 115, 116>>

# n
5

# data
"hello"

# rest
"rest"
g-andrade

g-andrade

So you can just prepend the value to the binary and then it would work?

I definitely would not recommend this, since it will require a new binary to be allocated, as you rightly suggest.

Even if the binaries involved are expected to be small, it seems hard to justify the performance hit for such a tiny spoon of syntactic sugar.

Where Next?

Popular in Questions Top

pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

Other popular topics Top

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

We're in Beta

About us Mission Statement