title: Erlang pattern matching bitstrings
body: <p>I'm writing code to decode messages from a binary protocol. Each message type is assigned a 1 byte type identifier and each message carries this type id. Messages all start with a common header consisting of 5 fields. My API is simple:</p>
  
  <pre><code>decoder:decode(Bin :: binary()) -&gt; my_message_type() | {error, binary()}`
  </code></pre>
  
  <p>My first instinct is to lean heavily on pattern matching by writing one decode function for each message type and to decode that message type completely in the fun argument</p>
  
  <pre><code>decode(&lt;&lt;Hdr1:8, ?MESSAGE_TYPE_ID_X:8, Hdr3:8, Hdr4:8, Hdr5:32, 
           TypeXField1:32, TypeXFld2:32, TypeXFld3:32&gt;&gt;) -&gt;
      #message_x{hdr1=Hdr1, hdr3=Hdr3 ... fld4=TypeXFld3};
  
  decode(&lt;&lt;Hdr1:8, ?MESSAGE_TYPE_ID_Y:8, Hdr3:8, Hdr4:8, Hdr5:32, 
           TypeYField1:32, TypeYFld2:16, TypeYFld3:4, TypeYFld4:32
           TypeYFld5:64&gt;&gt;) -&gt;
      #message_y{hdr1=Hdr1, hdr3=Hdr3 ... fld5=TypeYFld5}.
  </code></pre>
  
  <p>Note that while the first 5 fields of the messages are structurally identical, the fields after that vary for each message type.</p>
  
  <p>I have roughly 20 message types and thus 20 functions similar to the above. Am I decoding the full message multiple times with this structure? Is it idiomatic? Would I be better off just decoding the message type field in the function header and then decode the full message in the body of the message?</p>