4 ms·
Validating UTF-8 binaries with Erlang
- rdtsc 12y agoErlang's pattern matching, especially binary pattern matching is very powerful and really unique. Once you use it, you start to miss it in other languages. Here is how to parse a TCP segment (from http://broadcast.oreilly.com/2009/03/the-power-of-erlang-bit-syntax.html http://broadcast.oreilly.com/2009/03/the-power-of-erlang-bit...): decode(Segment) -> case Segment of << SourcePort:16, DestinationPort:16, SequenceNumber:32, AckNumber:32, DataOffset:4, _Reserved:4, Flags:8, WindowSize:16, Checksum:16, UrgentPointer:16, Payload/binary>> when DataOffset>4 -> OptSize = (DataOffset - 5)*32, << Options:OptSize, Message/binary >> = Payload, <> = <>, %% Can now process the Message according to the %% Options (if any) and the flags CWR, ..., FIN. binary_to_list(Message) end. Here is a link of how to parse an RTP packet: https://forfunand.wordpress.com/2011/10/10/why-erlangs-binary-syntax-is-awesome/ https://forfunand.wordpress.com/2011/10/10/why-erlangs-binar...