[erlang-questions] Bit syntax matching gotchas

zxq9 zxq9@REDACTED
Wed Feb 3 18:20:21 CET 2016


On 2016年2月3日 水曜日 16:06:49 Björn Gustavsson wrote:
> However, the following examples should produce
> warnings:
> 
> <<-55555:8>>
> <<100000:8>>
> 
> The two values above cannot be represented in
> 8 bits, which points to a real bug.

I have to admit that I've abused the bejesus out of this "bug" quite a bit
without ever considering it to be peculiar. I do remember being surprised
when I was first exploring Erlang and saw this happen, though:

  1> A = 10000.
  10000
  2> B = <<A>>.
  <<16>>

It made sense after a moment, especially once I played some more, but I
don't recall the peculiar properties of this ever being explained anywhere
in practical terms.

>How could the compiler warn you that you depend on masking?
>
>Consider this code:
>
>f(A) ->
>  <<A:16>>.

I suppose something like this would provide enough information:

  -spec f(<<_:32>>) -> <<_:16>>.
  f(A) ->
      <<A:16>>.

Or to be absolutely explicit:

  chop(In, Size) when is_binary(In) ->
      Mask = bit_size(In) - Size,
      <<_:Mask, Out:Size>> = In,
      <<Out:Size>>.

Is there a better way of doing that? I still expect to see things like
`<<Chopped:Size>> = SomeBin` all over the place.

Meh.

I do a fair amount of value assertion here and there in code, just not
usually with binary syntax involved (that is, I do `A = B`, but never
`<<A>> = <<B>>`). Some of the examples you presented have bizarre outcomes,
though. When `A /= A`, syntax aside, something is wrong with the world.

-Craig



More information about the erlang-questions mailing list