[erlang-questions] Validating binaries

Sean Cribbs seancribbs@REDACTED
Tue Aug 11 17:01:12 CEST 2015


This looks like a case where you could use a binary comprehension.

validate_lower_case_hex(Value, Length) when is_binary(Value),
                                            byte_size(Value) == Length ->
    Value == << <<C>> ||  <<C:8>> <= Value,
                          (C >= $0 andalso C =< $9) orelse
                          (C >= $a andalso C =< $f) >>;

validate_lower_case_hex(Value, _) when is_binary(Value) ->
    false.

On Tue, Aug 11, 2015 at 9:39 AM, Roger Lipscombe <roger@REDACTED>
wrote:

> Simple question: what's the most efficient way to validate that a
> binary value is of a certain length, and contains only certain
> characters?
>
> I've got the following:
>
> %% @doc Check that 'Value' is a binary, exactly length 'Length',
> %% containing only ASCII characters [0-9af].
> %% If the check succeeds, return the value; otherwise throw.
> validate_lower_case_hex(Value, Length) ->
>     validate_lower_case_hex(Value, Length, Value).
>
> validate_lower_case_hex(<<>>, 0, Value) ->
>     Value;
> validate_lower_case_hex(<<>>, N, _Value) when N > 0 ->
>     % binary is too short.
>     erlang:error(validation_failed);
> validate_lower_case_hex(<<_,_>>, 0, _Value) ->
>     % binary is too long.
>     erlang:error(validation_failed);
> validate_lower_case_hex(<<C:8, Rest/binary>>, N, Value)
>   when C >= $0, C =< $9; C >= $a, C =< $f ->
>     validate_lower_case_hex(Rest, N - 1, Value);
> validate_lower_case_hex(<<_C:8, _Rest/binary>>, _N, _Value) ->
>     % unexpected character.
>     erlang:error(validation_failed).
>
> Is there a better (faster) way to do it?
>
> Thanks,
> Roger.
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20150811/043eb9ad/attachment.htm>


More information about the erlang-questions mailing list