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