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 |
|
|
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 |
651 |
[list_to_binary(T) || |
28 |
651 |
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 |
16 |
iolist_to_binary(join_s(L, Sep)). |
33 |
|
|
34 |
|
-spec gen_from_crypto() -> binary(). |
35 |
|
gen_from_crypto() -> |
36 |
16095 |
base16:encode(crypto:strong_rand_bytes(8)). |
37 |
|
|
38 |
|
-spec gen_from_timestamp() -> binary(). |
39 |
|
gen_from_timestamp() -> |
40 |
3940 |
{Mega, Secs, Micro} = os:timestamp(), |
41 |
3940 |
MegaB = integer_to_binary(Mega), |
42 |
3940 |
SecsB = integer_to_binary(Secs), |
43 |
3940 |
MicroB = integer_to_binary(Micro), |
44 |
3940 |
<<MegaB/binary, $-, SecsB/binary, $-, MicroB/binary>>. |
45 |
|
|
46 |
|
-spec encode_crypto(iodata()) -> binary(). |
47 |
38 |
encode_crypto(Text) -> base16:encode(crypto:hash(sha, Text)). |
48 |
|
|
49 |
|
%% --------------------------------------------------- |
50 |
|
%% Internal functions |
51 |
|
%% --------------------------------------------------- |
52 |
|
join_s([], _Sep) -> |
53 |
:-( |
[]; |
54 |
|
join_s([H|T], Sep) -> |
55 |
16 |
[H, [[Sep, X] || X <- T]]. |