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
|
%%% Copyright (c) 2015, NORDUnet A/S.
%%% See LICENSE for licensing information.
-module(tlv).
-export([encode/2, decode/1]).
-spec encode(binary(), binary()) -> binary().
encode(Type, Value) ->
4 = byte_size(Type), % FIXME: make Type a 4 octet binary
Len = byte_size(Value) + 8,
<<Len:32, Type/binary, Value/binary>>.
-spec decode(binary()) -> {binary(), binary(), binary()}.
decode(Data) ->
<<TotalLength:32, Rest1/binary>> = Data,
Length = TotalLength - 8,
<<Type:4/binary-unit:8, Rest2/binary>> = Rest1,
<<Value:Length/binary-unit:8, Rest3/binary>> = Rest2,
{Type, Value, Rest3}.
%%%%%%%%%%%%%%%%%%%%
-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}.
|