Peter Saxton
Peter Saxton

Reputation: 4676

How to test if an Elixir (or erlang) value can be written as binary

I think this question is the same as asking how do I check if a value is an io_list. I want this to be as efficient as possible, therefore do not want to turn the value into a binary as part of the process of checking if it is an io_list.

Upvotes: 1

Views: 229

Answers (1)

Dogbert
Dogbert

Reputation: 222080

After browsing the stdlib of Erlang, I believe your best choice is to use :erlang.iolist_size and catch ArgumentError to detect invalid iolists.

iolist? = fn x ->
  try do
    :erlang.iolist_size(x)
    true
  rescue
    ArgumentError -> false
  end
end

IO.inspect iolist?("foo")
IO.inspect iolist?(["foo"])
IO.inspect iolist?(:foo)

Output:

true
true
false

In my highly unscientific benchmark, this is about thrice as fast as :erlang.iolist_to_binary/1.

iolist = List.duplicate([[[1, "2"], '3'], ?4], 1000000)
IO.inspect :timer.tc(:erlang, :iolist_to_binary, [iolist])
IO.inspect :timer.tc(:erlang, :iolist_size, [iolist])
{82291,
 <<1, 50, 51, 52, 1, 50, 51, 52, 1, 50, 51, 52, 1, 50, 51, 52, 1, 50, 51, 52, 1,
   50, 51, 52, 1, 50, 51, 52, 1, 50, 51, 52, 1, 50, 51, 52, 1, 50, 51, 52, 1,
   50, 51, 52, 1, 50, 51, 52, 1, ...>>}
{25577, 4000000}

Upvotes: 1

Related Questions