[erlang-questions] Protocol Mapping

Attila Rajmund Nohl attila.r.nohl@REDACTED
Wed Dec 19 14:05:53 CET 2012


Hello!

You could try to generate the code that implements the first pattern.

2012/12/19 Steve Davis <steven.charles.davis@REDACTED>:
> Hi,
>
> I'm frequently facing situations with binary protocol
> translations/transforms where I need to map binary codes to e.g. atoms and
> back.
>
> This is of course "easy" in Erlang, but suffers some inconveniences. I've
> attached a code snippet distilled down to the simplest case to explain my
> issue.
>
> I'm sure the first codec pattern below is familiar, and for sure is
> efficient.
> However, there are multiple places where updating is required to add new
> message types.
>
> The second pattern is much less usual, but handy as one line achieves the
> addition of a new message type.
> It helps particularly when there is more than one pairing involved (e.g.
> {atom, code, status_message}).
>
> For sure this cannot be something nobody has seen/thought about. I'm
> wondering if anyone has comment on this, and maybe suggestions for
> approaches that I haven't thought of.
>
> /s
> -------
> -module(mapping).
>
> -compile(export_all).
>
> %% traditional
>
> -define(HELLO, 100).
> -define(HELP, 101).
> -define(DONE, 102).
>
> encode(hello) -> ?HELLO;
> encode(help) -> ?HELP;
> encode(done) -> ?DONE.
>
> decode(?HELLO) -> hello;
> decode(?HELP) -> help;
> decode(?DONE) -> done.
>
> %% alternative
>
> -define(MAP, [
> {hello, 100},
> {help, 101},
> {done, 102}
> ]).
>
> encode0(X) ->
> {X, Y} = lists:keyfind(X, 1, ?MAP),
> Y.
>
> decode0(X) ->
> {Y, X} = lists:keyfind(X, 2, ?MAP),
> Y.
>
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>



More information about the erlang-questions mailing list