<div dir="ltr">This looks like a case where you could use a binary comprehension.<div><br></div><div><div>validate_lower_case_hex(Value, Length) when is_binary(Value),</div><div> byte_size(Value) == Length -></div><div> Value == << <<C>> || <<C:8>> <= Value,</div><div> (C >= $0 andalso C =< $9) orelse</div><div> (C >= $a andalso C =< $f) >>;</div></div><div><br></div><div>validate_lower_case_hex(Value, _) when is_binary(Value) -></div><div> false.</div></div><div class="gmail_extra"><br><div class="gmail_quote">On Tue, Aug 11, 2015 at 9:39 AM, Roger Lipscombe <span dir="ltr"><<a href="mailto:roger@differentpla.net" target="_blank">roger@differentpla.net</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">Simple question: what's the most efficient way to validate that a<br>
binary value is of a certain length, and contains only certain<br>
characters?<br>
<br>
I've got the following:<br>
<br>
%% @doc Check that 'Value' is a binary, exactly length 'Length',<br>
%% containing only ASCII characters [0-9af].<br>
%% If the check succeeds, return the value; otherwise throw.<br>
validate_lower_case_hex(Value, Length) -><br>
validate_lower_case_hex(Value, Length, Value).<br>
<br>
validate_lower_case_hex(<<>>, 0, Value) -><br>
Value;<br>
validate_lower_case_hex(<<>>, N, _Value) when N > 0 -><br>
% binary is too short.<br>
erlang:error(validation_failed);<br>
validate_lower_case_hex(<<_,_>>, 0, _Value) -><br>
% binary is too long.<br>
erlang:error(validation_failed);<br>
validate_lower_case_hex(<<C:8, Rest/binary>>, N, Value)<br>
when C >= $0, C =< $9; C >= $a, C =< $f -><br>
validate_lower_case_hex(Rest, N - 1, Value);<br>
validate_lower_case_hex(<<_C:8, _Rest/binary>>, _N, _Value) -><br>
% unexpected character.<br>
erlang:error(validation_failed).<br>
<br>
Is there a better (faster) way to do it?<br>
<br>
Thanks,<br>
Roger.<br>
_______________________________________________<br>
erlang-questions mailing list<br>
<a href="mailto:erlang-questions@erlang.org">erlang-questions@erlang.org</a><br>
<a href="http://erlang.org/mailman/listinfo/erlang-questions" rel="noreferrer" target="_blank">http://erlang.org/mailman/listinfo/erlang-questions</a><br>
</blockquote></div><br></div>