Monday, August 17, 2009

erlang: Extracting values from binary streams with macros

Writing a lot of binary matching strings, I now use simple macros to synchronise erlang code with others language...
Let me explain a bit, there were many lines who look like theses:

parse(<< Id:32/little-unsigned, Oid:32/little-unsigned, Soid:16/little-unsigned >>, State) ->

Now I really prefer to see lines looking like this:

parse(<< ?UINT32( Id ),
?UINT32( Oid ),
?UINT16( Soid ) >>, State) ->

The magic trick was to define macros at the beginning of the erl module like this:

-define( UINT32(X), X:32/little-unsigned).
-define( UINT16(X), X:16/little-unsigned).

Now everyone can read those parse lines easily...

No comments: