[erlang-questions] How erlang handle complicated data structure like C?

George Catalin Serbanut cgsmcmlxxv@REDACTED
Mon Sep 19 08:26:41 CEST 2011


Considering all variables integers, here is an example how to play with
records:

1. Record definition:
-record(tdm_leg,{a,b}).
-record(semper_packet_t,{tdm_leg = #tdm_leg{},ip_leg}).
-define(SEPARATOR,"--/--").

2. Inserting values:
insert_values(A,B,C) ->
     Semper_packet_t = #semper_packet_t{#tdm_leg{a=A,b=B},ip_leg=C}.

3. Read values:
read_values(Semper_packet_t = #semper{Tdm_leg =
tdm_leg#tdm_leg{a=A,b=B},ip_leg=C}) ->
     do_something_with(Semper_packet_t,Tdm_leg,A,B,C).

4. Encoder:
encode(#semper{#tdm_leg{a=A,b=B},ip_leg=C}) ->

list_to_binary(io_lib:format("~p~s~p~s~p",[A,?SEPARATOR,B,?SEPARATOR,C])).

5. Decoder:
decode(Binary) ->
    [A,B,C] = re:split(binary_to_list(Binary),?SEPARATOR,[{return,list}]),
    Semper_packet_t =
#semper_packet_t{#tdm_leg{a=list_to_integer(A),b=list_to_interger(B)},ip_leg=list_to_integer(C)}.

6. Binary tester:
is_my_record(Binary) ->
    L = re:split(binary_to_list(Binary),?SEPARATOR,[{return,list}]),
    if length(L) == 3 -> Result = lists:all(fun(E) -> TL =
string:join(string:tokens(E,"0123456789"),""), if length(TL) == 0 -> Result
= true; length(TL) /= 0 -> Result = false end, Result end,L),
       length(L) /= 3 -> Result = false,
    end,
    Result.

7. How to use the test:
receive_function(Packet) when is_my_record(Packet) == true ->
do_something_with_my_packet;
receive_function(Packet) when is_my_record(Packet) /= true -> I_do_not_care.

Take this an example only. There are other options more elegant. For the
moment I created something which is easily understandable for someone coming
from other programming languages.

Have fun with Erlang! ;)
CGS






On Mon, Sep 19, 2011 at 7:39 AM, Masklinn <masklinn@REDACTED> wrote:

> On 19 sept. 2011, at 07:09, Jovi Zhang <bookjovi@REDACTED> wrote:
> > But how to change record format to binary correctly? because the
> > binary need to transport in network.
> > When I try below, the output seems wrong.
> >
> > -record(semper_packet_t,
> >    {tdm_leg = <<1:8, 3:8>>,
> >     ip_leg = 2
> >     }).
> >
> > term_to_binary(#semper_packet_t.tdm_leg)
> >
> > result: <<131,97,2>>
> you need an encoder and a decoder, to and from your binary wire format. You
> don't generally put raw binary data in a record, and there is just about no
> way erlang's binary packing of its terms (which exists for e<->e exchanges)
> is going to match a struct defined by an arbitrary third party.
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20110919/6a4d66a4/attachment.htm>


More information about the erlang-questions mailing list