|
| 1 | +%% |
| 2 | +%% MessagePack for Erlang |
| 3 | +%% |
| 4 | +%% Copyright (C) 2009-2013 UENISHI Kota |
| 5 | +%% |
| 6 | +%% Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +%% you may not use this file except in compliance with the License. |
| 8 | +%% You may obtain a copy of the License at |
| 9 | +%% |
| 10 | +%% http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +%% |
| 12 | +%% Unless required by applicable law or agreed to in writing, software |
| 13 | +%% distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +%% See the License for the specific language governing permissions and |
| 16 | +%% limitations under the License. |
| 17 | +%% |
| 18 | +-module(msgpack_term). |
| 19 | + |
| 20 | +-export([to_binary/1, from_binary/1, |
| 21 | + pack_ext/2, unpack_ext/2]). |
| 22 | +-behabiour(msgpack_ext). |
| 23 | + |
| 24 | +-define(ERLANG_TERM, 131). |
| 25 | +-define(TERM_OPTION, [{enable_str,true},{ext,?MODULE},{allow_atom,none}]). |
| 26 | + |
| 27 | +to_binary(Term) -> |
| 28 | + msgpack:pack(Term, ?TERM_OPTION). |
| 29 | + |
| 30 | +from_binary(Bin) -> |
| 31 | + {ok, Term} = msgpack:unpack(Bin, ?TERM_OPTION), |
| 32 | + Term. |
| 33 | + |
| 34 | +-spec pack_ext(tuple(), msgpack:options()) -> |
| 35 | + {ok, {Type::byte(), Data::binary()}} | |
| 36 | + {error, any()}. |
| 37 | +pack_ext(Term, _Options) -> |
| 38 | + {ok, {?ERLANG_TERM, erlang:term_to_binary(Term)}}. |
| 39 | + |
| 40 | +-spec unpack_ext(Type::byte(), Data::binary()) -> |
| 41 | + {ok, any()} | {error, any()}. |
| 42 | +unpack_ext(?ERLANG_TERM, Bin) -> |
| 43 | + {ok, erlang:binary_to_term(Bin)}. |
| 44 | + |
| 45 | +-ifdef(TEST). |
| 46 | +-include_lib("eunit/include/eunit.hrl"). |
| 47 | + |
| 48 | +test_data() -> |
| 49 | + ['foobar atom', %% is_atom/1 |
| 50 | + fun() -> ok end, %% is_function/1 |
| 51 | + self(), %% is_pid/1 |
| 52 | + %% is_port/1 |
| 53 | + make_ref(), %% is_reference/1 |
| 54 | + {me, foo, bar}, %% is_tuple/1 |
| 55 | + {}]. |
| 56 | + |
| 57 | +t2b_b2t_test() -> |
| 58 | + Data = test_data(), |
| 59 | + ?assertEqual(Data, |
| 60 | + msgpack:binary_to_term(msgpack:term_to_binary(Data))). |
| 61 | + |
| 62 | +-endif. |
0 commit comments