Skip to content

Commit

Permalink
Optimise text_format:escape_label_value (#160)
Browse files Browse the repository at this point in the history
Don't create a new binary if there is no special character to escape.
  • Loading branch information
gomoripeti authored Nov 20, 2023
1 parent 297a6e6 commit 9186c8c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
28 changes: 23 additions & 5 deletions src/formats/prometheus_text_format.erl
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,21 @@ format(Registry) ->
ok = file:close(Fd),
Str.

-spec escape_label_value(binary() | iolist()) -> binary()
; (undefined) -> no_return().
-spec escape_label_value(binary() | iolist()) -> binary().
%% @doc
%% Escapes the backslash (\), double-quote ("), and line feed (\n) characters
%% @end
escape_label_value(LValue) when is_list(LValue); is_binary(LValue) ->
escape_string(fun escape_label_char/1, LValue);
escape_label_value(LValue) when is_binary(LValue) ->
case has_special_char(LValue) of
true ->
escape_string(fun escape_label_char/1, LValue);
false ->
LValue
end;
escape_label_value(LValue) when is_list(LValue) ->
escape_label_value(iolist_to_binary(LValue));
escape_label_value(Value) ->
erlang:error({wtf, Value}).
erlang:error({invalid_value, Value}).

%%====================================================================
%% Private Parts
Expand Down Expand Up @@ -248,6 +254,18 @@ escape_label_char($" = X) ->
escape_label_char(X) ->
<<X>>.

%% @perivate
-spec has_special_char(binary()) -> boolean().
has_special_char(<<C:8, _/bitstring>>)
when C =:= $\\;
C =:= $\n;
C =:= $" ->
true;
has_special_char(<<_:8, Rest/bitstring>>) ->
has_special_char(Rest);
has_special_char(<<>>) ->
false.

%% @private
escape_string(Fun, Str) when is_binary(Str) ->
<< <<(Fun(X))/binary>> || <<X:8>> <= Str >>;
Expand Down
4 changes: 4 additions & 0 deletions test/eunit/format/prometheus_text_format_tests.erl
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ escape_label_value_test()->
?assertEqual(<<"qwe\\\\qwe\\nq\\\"we\\\"qwe">>,
prometheus_text_format:escape_label_value("qwe\\qwe\nq\"we\"qwe")).

escape_label_value_no_special_char_test() ->
LabelBin = <<"qweqweqwe">>,
?assert(erts_debug:same(LabelBin, prometheus_text_format:escape_label_value(LabelBin))).

prometheus_format_test_() ->
{foreach,
fun prometheus_eunit_common:start/0,
Expand Down

0 comments on commit 9186c8c

Please sign in to comment.