[erlang-questions] Bit syntax matching gotchas
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
> 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.
2> B = <<A>>.
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:
I suppose something like this would provide enough information:
-spec f(<<_:32>>) -> <<_:16>>.
Or to be absolutely explicit:
chop(In, Size) when is_binary(In) ->
Mask = bit_size(In) - Size,
<<_:Mask, Out:Size>> = In,
Is there a better way of doing that? I still expect to see things like
`<<Chopped:Size>> = SomeBin` all over the place.
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.
More information about the erlang-questions