Try to understand hexdocs Plug.Parsers custom body reader example

Hi,
I am confused with below line in custom body reader

conn = update_in(conn.assigns[:raw_body], &[body | (&1 || [])])

my naive understand is that it update :raw_body to [body | []] as &1 is empty at the moment

my question is :raw_body is bitstring originally, why change to list?

Thanks.

In many places in elixir and erlang, you can use iodata, which is a String or a list of Strings, or a list of characters, or a list of any of the above. Building a list of strings is just creating a bunch of pointers; rebuilding a string via concatenation Is allocating, and copying. So the easy answer is “performance”.

Try putting a list of strings (or a list of list of strings, or a list of mix and match) into IO.puts, for example. There is alsi function IO.iodata_to_binary/0 which normalizes it if you need it.

2 Likes

Thanks

You could also use the builtin to_string function on iolists because IO.iodata_to_binary is Unicode-unsafe while to_string is actually Unicode-safe.

2 Likes