Error with default bitstring value + size in struct

Given this struct:

defmodule Struct do
    defstruct bit: <<0::size(4)>>
end

I get this error:

iex> %Struct{}
** (FunctionClauseError) no function clause matching in :elixir_bitstring.extract_bit_type/2

When I don’t specify a size (bit: <<0>>), a struct is returned as expected. Is this behavior on purpose?

1 Like
iex> defmodule SomeStruct do
...>     defstruct bit: <<0::size(4)>>
...> end
...> 
{:module, SomeStruct,
 <<70, 79, 82, 49, 0, 0, 9, 24, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 186,
   131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115,
   95, 118, 49, 108, 0, 0, 0, 4, 104, 2, ...>>,
 %SomeStruct{bit: <<0::size(4)>>}}
iex> %SomeStruct{}
** (FunctionClauseError) no function clause matching in :elixir_bitstring.extract_bit_type/2
    (elixir) src/elixir_bitstring.erl:226: :elixir_bitstring.extract_bit_type(4, [])
    (elixir) src/elixir_bitstring.erl:220: :elixir_bitstring.extract_bit_info/2
    (elixir) src/elixir_bitstring.erl:156: :elixir_bitstring.build_bitstr_each/5
    (elixir) src/elixir_bitstring.erl:149: :elixir_bitstring.build_bitstr/4
    (stdlib) lists.erl:1354: :lists.mapfoldl/3
    (stdlib) lists.erl:1355: :lists.mapfoldl/3

Huh, well this is interesting, I’ve tried a few various things, but it seems in all cases regardless of the keys or values it seems that constructing a struct with a default value of a non-multiple-of-8-bits bitstring causes the struct to die on creation… Is this a bug @josevalim or something?

It seems that the issue is with any bit size < 8. I tried with 8 and more, and it works as expected. I haven’t found anything in the docs suggesting that this is expected behavior, and updating a struct with <<0::4>> works as expected. I opened an issue in case this is a bug. :slight_smile:

1 Like

It is a bug, thanks for filing a report.

2 Likes