Sha256: 960557452f40095430fd473b451a82d2740afbe666bf9a5d45a4e50567233773

Contents?: true

Size: 1.71 KB

Versions: 14

Compression:

Stored size: 1.71 KB

Contents

%%% See http://github.com/mojombo/bert.erl for documentation.
%%% MIT License - Copyright (c) 2009 Tom Preston-Werner <tom@mojombo.com>

-module(bert).
-version('1.1.0').
-author("Tom Preston-Werner").

-export([encode/1, decode/1]).

-ifdef(TEST).
-include("test/bert_test.erl").
-endif.

%%---------------------------------------------------------------------------
%% Public API

-spec encode(term()) -> binary().

encode(Term) ->
  term_to_binary(encode_term(Term)).

-spec decode(binary()) -> term().

decode(Bin) ->
  decode_term(binary_to_term(Bin)).

%%---------------------------------------------------------------------------
%% Encode

-spec encode_term(term()) -> term().

encode_term(Term) ->
  case Term of
    [] -> {bert, nil};
    true -> {bert, true};
    false -> {bert, false};
    Dict when is_record(Term, dict, 9) ->
      {bert, dict, encode_term(dict:to_list(Dict))};
    List when is_list(Term) ->
      lists:map((fun encode_term/1), List);
    Tuple when is_tuple(Term) ->
      TList = tuple_to_list(Tuple),
      TList2 = lists:map((fun encode_term/1), TList),
      list_to_tuple(TList2);
    _Else -> Term
  end.

%%---------------------------------------------------------------------------
%% Decode

-spec decode_term(term()) -> term().

decode_term(Term) ->
  case Term of
    {bert, nil} -> [];
    {bert, true} -> true;
    {bert, false} -> false;
    {bert, dict, Dict} ->
      dict:from_list(decode_term(Dict));
    {bert, Other} ->
      {bert, Other};
    List when is_list(Term) ->
      lists:map((fun decode_term/1), List);
    Tuple when is_tuple(Term) ->
      TList = tuple_to_list(Tuple),
      TList2 = lists:map((fun decode_term/1), TList),
      list_to_tuple(TList2);
    _Else -> Term
  end.  

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
capricorn-2.0.11 erlang/lib/bert/src/bert.erl
capricorn-2.0.10 erlang/lib/bert/src/bert.erl
capricorn-2.0.9 erlang/lib/bert/src/bert.erl
capricorn-2.0.8 erlang/lib/bert/src/bert.erl
capricorn-2.0.7 erlang/lib/bert/src/bert.erl
capricorn-2.0.6 erlang/lib/bert/src/bert.erl
capricorn-2.0.5 erlang/lib/bert/src/bert.erl
capricorn-2.0.4 erlang/lib/bert/src/bert.erl
capricorn-2.0.3 erlang/lib/bert/src/bert.erl
capricorn-2.0.3.pre2 erlang/lib/bert/src/bert.erl
capricorn-2.0.3.pre erlang/lib/bert/src/bert.erl
capricorn-2.0.2 erlang/lib/bert/src/bert.erl
capricorn-2.0.1 erlang/lib/bert/src/bert.erl
capricorn-2.0.0 erlang/lib/bert/src/bert.erl