1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
%%% Copyright (c) 2015, NORDUnet A/S.
%%% See LICENSE for licensing information.
-module(tlv).
-export([encode/2, decode/1, encodelist/1, decodelist/1]).
-spec encode(binary(), binary()) -> binary().
encode(Type, Value) when byte_size(Type) == 4 ->
Len = byte_size(Value) + 8,
<<Len:32, Type:4/binary, Value/binary>>.
-spec decode(binary()) -> {binary(), binary(), binary()}.
decode(Data) ->
<<TotalLength:32, Rest1/binary>> = Data,
Length = TotalLength - 8,
<<Type:4/binary, Rest2/binary>> = Rest1,
<<Value:Length/binary, Rest3/binary>> = Rest2,
{Type, Value, Rest3}.
%% Convenience functions
-spec encodelist([{binary(), binary()}]) -> binary().
encodelist(List) ->
list_to_binary([encode(Type, Value) || {Type, Value} <- List]).
-spec decodelist(binary()) -> [{binary(), binary()}].
decodelist(Data) ->
decodelist(Data, []).
decodelist(<<>>, Acc) ->
lists:reverse(Acc);
decodelist(Data, Acc) ->
{Type, Value, Rest} = decode(Data),
decodelist(Rest, [{Type, Value} | Acc]).
%%%%%%%%%%%%%%%%%%%%
-include_lib("eunit/include/eunit.hrl").
-define(TESTDATA1, {<<"DATA">>, <<"some data">>}).
-define(TESTDATA2, {<<"DAT2">>, <<"some other data">>}).
the_test_() ->
{setup,
fun() -> [?TESTDATA1, ?TESTDATA2] end,
fun(_) -> ok end,
fun(TestVectors) ->
[?_assertEqual({T, V, <<>>}, decode(encode(T, V))) ||
{T, V} <- TestVectors] end}.
-define(LISTTESTDATA, [?TESTDATA1, ?TESTDATA2]).
list_test() ->
Encoded = encodelist(?LISTTESTDATA),
?assertEqual(decodelist(Encoded), ?LISTTESTDATA),
{T1, V1, Rest} = decode(Encoded),
?assertEqual({T1, V1}, ?TESTDATA1),
{T2, V2, <<>>} = decode(Rest),
?assertEqual({T2, V2}, ?TESTDATA2).
|