[erlang-questions] encoding packets a style+efficiency question

Jachym Holecek freza@REDACTED
Tue Jul 26 20:18:49 CEST 2011


# Anupam Kapoor 2011-07-26:
> yes i know. but my question was more towards a better approach towards
> writing packet encoders/decoders. may you please let me know your
> thoughts on that ?

It's hard to answer such a broad question more precisely, so just some
random considerations really.

The usual general approach is that you design native Erlang representation
of the PDUs involved and then provide functions with about this signature:

  decode(binary()) -> PDU
  encode(PDU) -> iolist()

Popular choices of native representations ('PDU' above) include[*]:

  * TVLs, that is [{Key, Val}, ...] where Key tends to be atom.
  * Plain tuples if PDUs are simple enough.
  * Records, usually one record type per PDU type.

Or various combinations of these (ie. use record to represent anything
in packet header and then have 'body' element which is a TVL holding
decoded packet body).

And sometimes it makes sense to separate packet header processing from
payload processing altogether (pass payload around as a binary and
decode it later on -- or never).

The API of your protocol stack would usually operate on the native 'PDU'
type, so that the user doesn't have to encode/decode things him/herself,
but this again depends.

HTH,
	-- Jachym

[*] I'm intentionally not listing dict in there although I've seen it
    used a few times. It looks horribly ugly in logs, the performance
    gain is questionable and often irrelevant, it's hard to iterate
    over, impossible to pattern-match on...



More information about the erlang-questions mailing list