[erlang-questions] How to efficiently set the bit at position Index to 1 in a binary?

Zabrane Mickael zabrane3@REDACTED
Sat Dec 24 23:22:37 CET 2011


One last thing.

>  a(N, B) ->
>      fun (<<L:N/bits, _:1, R/bits>>) -> % THIS IS LINE 266
>          <<L/bits, 1:1, R/bits>> 
>      end(B).

How to disable the following warning only for this function:
src/foo.erl:266: Warning: NOT OPTIMIZED: sub binary is used or returned

is there a way to do it by using -compile(...) directive?


Regards,
Zabrane

On Dec 24, 2011, at 8:17 PM, Jachym Holecek wrote:

> # Zabrane Mickael 2011-12-24:
>> Hi folks,
>> 
>> Here's my code:
>> 
>> %%--------------------------------------------------------------------
>> %% @doc Set the bit at position Index to 1 in the binary Bin.
>> %% @end
>> %%--------------------------------------------------------------------
>> -spec set(Bin :: binary(), Index :: non_neg_integer()) -> binary().
>> set(<<1:1, _/bits>> = Bin, 0) ->
>>    Bin;
>> set(<<0:1, Rest/bits>>, 0) ->
>>    <<1:1, Rest/bits>>;
>> set(Bin, Index) when Index > 0 ->
>>    Before = Index - 1,
>>    <<Head:Before, _:1, Rest/bits>> = Bin,
>>    <<Head:Before, 1:1, Rest/bits>>.
>> 
>> 
>> After compiling, I'm getting the following warnings:
>> src/foo.erl:248: Warning: INFO: the '=' operator will prevent delayed sub binary optimization
>> src/foo.erl:248: Warning: INFO: the '=' operator will prevent delayed sub binary optimization
>> src/foo.erl:250: Warning: NOT OPTIMIZED: sub binary is used or returned
>> src/foo.erl:254: Warning: NOT OPTIMIZED: sub binary is used or returned
>> 
>> What's the best/optimized solution and how to get rid of these warnings?
> 
> Binary matching is *much* more powerful than what it looks like at first:
> 
>  -module(a).
>  -export([a/2]).
> 
>  a(N, B) ->
>      fun (<<L:N/bits, _:1, R/bits>>) ->
>          <<L/bits, 1:1, R/bits>> 
>      end(B).
> 
> The compiler refuses the saner form (doing the binary match in a/1's head
> directly) quoting the delusion that N isn't bound at that point... pity.
> 
> Have fun,
> 	-- Jachym



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20111224/bfc9b196/attachment.htm>


More information about the erlang-questions mailing list