[erlang-questions] Validating binaries

Roger Lipscombe roger@REDACTED
Tue Aug 11 16:39:22 CEST 2015


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.



More information about the erlang-questions mailing list