Packages

A simple bencode encoder and decoder writen in pure Erlang

Current section

Files

Jump to
erl_bencode src bencode.erl
Raw

src/bencode.erl

%% @author Robert Lasu
%% @copyright 2022 Robert Lasu
%% @doc A simple bencode decoder and encoder.
%% ----------------------------------
%% This is the API to use
%% ----------------------------------
-module(bencode).
-include_lib("eunit/include/eunit.hrl").
-ifdef(TEST).
-compile(export_all).
-endif.
-export([encode/1, decode/1]).
%% @doc Encodes `Value' to Bencode.
%% @end
-spec encode(Value) -> {ok, Encoded} | {error, Reason} | {warning, Reason, Encoded} when
Value :: map() | list() | string() | integer() | tuple() | atom(),
Encoded :: list(),
Reason :: atom().
%% @doc Encodes the `Value' provided to bencode
%% @param `Value' - can be either a map(), list(), string(), integer(), tuple() or atom()
%% @return Return - the bencode representation of `Value'
%% @throws Throws - {error, Reason} or {warning, Reason, Encoded}
encode(Value) -> encode:'_encode'(Value).
-spec decode(Value) -> {ok, Decoded} | {error, Reason} | {warning, Reason, Decoded} when
Value :: list() | atom(),
Decoded :: map() | list() | string() | integer() | atom(),
Reason :: atom().
%% @doc Takes a bencode string and convert it to a erlang term.
%% Even Erlang specific terms is supported such as atoms and tuples.
%% If `Value' is an atom() it's considerd to be a file path.
%% If `Value' is a list() it's considerd to be a bencode string
%% @param `Value' - a bencode string
%% @return Return - a Erlang term represented by `Value'. Can be
%% either a map(), list(), string(), integer(), tuple() or atom().
%% @throws Throws - {error, Reason} or {warning, Reason, Encoded}
decode(Value) -> decode:'_decode'(Value).