Packages

Bencoding encoder/decoder for Erlang — implements the serialization format specified in BEP 3 (BitTorrent)

Current section

Files

Jump to
bencoding src bt_utils.erl
Raw

src/bt_utils.erl

%%%-------------------------------------------------------------------
%%% @author Ralf Thomas Pietsch <ratopi@abwesend.de>
%%% @copyright (C) 2018, Ralf Thomas Pietsch
%%% @doc
%%%
%%% @end
%%% Created : 27. Okt 2018 05:42
%%%-------------------------------------------------------------------
-module(bt_utils).
-author("Ralf Thomas Pietsch <ratopi@abwesend.de>").
%% API
-export([mapa/2, sha1/1, url_encode/1, gen_uid/0]).
mapa([], Value) ->
Value;
mapa([H | T], Map) ->
mapa(T, maps:get(H, Map)).
sha1(<<Bin/binary>>) ->
crypto:hash(sha, Bin).
url_encode(<<Bin/binary>>) ->
url_encode(Bin, []).
url_encode(<<>>, List) ->
list_to_binary(lists:reverse(List));
url_encode(<<V, Bin/binary>>, List) ->
url_encode(Bin, [to_hex(V rem 16), to_hex(V div 16), $% | List]).
to_hex(V) when V =< 9 ->
V + $0;
to_hex(V) ->
V + $A - 10.
gen_uid() ->
list_to_binary(
[
rand:uniform(256)
|| _ <- lists:seq(0, 19)
]
).