Skip to content

Commit

Permalink
Merge pull request #292 from SergeTupchiy/support-byte-unit-for-bytesize
Browse files Browse the repository at this point in the history
Support byte unit for bytesize
  • Loading branch information
SergeTupchiy authored Mar 13, 2024
2 parents 59e471c + e1d128f commit d3345b6
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 4 deletions.
2 changes: 2 additions & 0 deletions etc/convert-sample.conf
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ min = 1m
hour = 1h
day = 1d

b = "256b"
B = "256B"
kb = 1kb
KB = 1KB
mb = 1mb
Expand Down
5 changes: 4 additions & 1 deletion src/hocon_postprocess.erl
Original file line number Diff line number Diff line change
Expand Up @@ -155,13 +155,16 @@ bytesize(Other) ->
Other.

do_bytesize(Str) ->
{ok, MP} = re:compile("^\s*([0-9]+)(kb|KB|mb|MB|gb|GB)$"),
{ok, MP} = re:compile("^\s*([0-9]+)(b|B|kb|KB|mb|MB|gb|GB)$"),
case re_run_first(Str, MP) of
{match, [Val, Unit]} ->
do_bytesize(list_to_integer(Val), Unit);
_ ->
Str
end.

do_bytesize(Val, "b") -> Val;
do_bytesize(Val, "B") -> Val;
do_bytesize(Val, "kb") -> Val * ?KILOBYTE;
do_bytesize(Val, "KB") -> Val * ?KILOBYTE;
do_bytesize(Val, "mb") -> Val * ?MEGABYTE;
Expand Down
6 changes: 3 additions & 3 deletions src/hocon_tconf.erl
Original file line number Diff line number Diff line change
Expand Up @@ -1108,7 +1108,7 @@ user_defined_validators(Schema) ->
validators(field_schema(Schema, validator)).

builtin_validators(?ENUM(Symbols)) ->
[fun(Value) -> check_enum_sybol(Value, Symbols) end];
[fun(Value) -> check_enum_symbol(Value, Symbols) end];
builtin_validators(Type) ->
TypeChecker = fun(Value) ->
case typerefl:typecheck(Type, Value) of
Expand All @@ -1122,12 +1122,12 @@ builtin_validators(Type) ->
end,
[TypeChecker].

check_enum_sybol(Value, Symbols) when is_atom(Value); is_integer(Value) ->
check_enum_symbol(Value, Symbols) when is_atom(Value); is_integer(Value) ->
case lists:member(Value, Symbols) of
true -> ok;
false -> {error, not_a_enum_symbol}
end;
check_enum_sybol(_Value, _Symbols) ->
check_enum_symbol(_Value, _Symbols) ->
{error, unable_to_convert_to_enum_symbol}.

validate(Opts, Schema, Value, Validators) ->
Expand Down
4 changes: 4 additions & 0 deletions test/hocon_tests.erl
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,8 @@ apply_opts_test_() ->
[
?_assertEqual(
{ok, #{
<<"b">> => 256,
<<"B">> => 256,
<<"GB">> => 1073741824,
<<"KB">> => 1024,
<<"MB">> => 1048576,
Expand Down Expand Up @@ -524,6 +526,8 @@ apply_opts_test_() ->
),
?_assertEqual(
{ok, #{
<<"b">> => ok,
<<"B">> => ok,
<<"GB">> => ok,
<<"KB">> => ok,
<<"MB">> => ok,
Expand Down

0 comments on commit d3345b6

Please sign in to comment.