./ct_report/coverage/mongoose_bin.COVER.html

1 %%%----------------------------------------------------------------------
2 %%% File : mongoose_bin.erl
3 %%% Author : Piotr Nosek <piotr.nosek@erlang-solutions.com>
4 %%% Purpose : Binaries manipulation and generation
5 %%% Created : 24 Jul 2018 by Piotr Nosek <piotr.nosek@erlang-solutions.com>
6 %%%----------------------------------------------------------------------
7
8 -module(mongoose_bin).
9 -author('piotr.nosek@erlang-solutions.com').
10
11 -export([tokens/2,
12 join/2,
13 encode_crypto/1,
14 gen_from_crypto/0,
15 gen_from_timestamp/0,
16 string_to_binary/1]).
17
18 %% ---------------------------------------------------
19 %% API
20 %% ---------------------------------------------------
21
22 %% tokens/2 and join/2 functions from original str.erl module
23 %% (C) Evgeniy Khramtsov <ekhramtsov@process-one.net>
24
25 %% Each byte in second argument is treated as distinct, one-character separator
26 -spec tokens(Subject :: binary(), BinaryWithSeparators :: binary()) -> [binary()].
27 tokens(B1, B2) ->
28 138 [list_to_binary(T) ||
29 138 T <- string:tokens(binary_to_list(B1), binary_to_list(B2))].
30
31 -spec join(BinsToJoin :: [binary()], Separator :: binary() | char()) -> binary().
32 join(L, Sep) ->
33
:-(
iolist_to_binary(join_s(L, Sep)).
34
35 -spec gen_from_crypto() -> binary().
36 gen_from_crypto() ->
37 1100 base16:encode(crypto:strong_rand_bytes(8)).
38
39 -spec gen_from_timestamp() -> binary().
40 gen_from_timestamp() ->
41 99 {Mega, Secs, Micro} = os:timestamp(),
42 99 MegaB = integer_to_binary(Mega),
43 99 SecsB = integer_to_binary(Secs),
44 99 MicroB = integer_to_binary(Micro),
45 99 <<MegaB/binary, $-, SecsB/binary, $-, MicroB/binary>>.
46
47 -spec encode_crypto(iodata()) -> binary().
48
:-(
encode_crypto(Text) -> base16:encode(crypto:hash(sha, Text)).
49
50 -spec string_to_binary(binary() | list()) -> binary().
51 string_to_binary(S) when is_list(S) ->
52 % If list is in Erlang representation of Unicode, we must use `unicode` module
53 % If it's not or is already converted, we must use list_to_binary
54 % since input can be from `file:consult/1` and prior to 17.0
55 % this function returned bytes in a list instead of proper unicode string
56 % so it is already like after a call to `unicode`.
57
:-(
case lists:any(fun(C) -> C > 255 end, S) of
58
:-(
true -> unicode:characters_to_binary(S);
59
:-(
false -> list_to_binary(S)
60 end;
61 string_to_binary(B) when is_binary(B) ->
62
:-(
B.
63
64 %% ---------------------------------------------------
65 %% Internal functions
66 %% ---------------------------------------------------
67 join_s([], _Sep) ->
68
:-(
[];
69 join_s([H|T], Sep) ->
70
:-(
[H, [[Sep, X] || X <- T]].
Line Hits Source