title: Safely serialize Text to Bytestring
body: <p>The text package does not provide an instance of <code>Binary</code> to encode/decode text. I have read about and understand the reasoning behind this (namely, <code>Text</code> should be encoding-agnostic). However, I need a <code>Binary</code> instance of <code>Text</code>. I've found that there is a package called text-binary that does this. However, the instance is as follows:</p>
  
  <pre><code>instance Binary T.Text where
      put = put . T.encodeUtf8
      get = T.decodeUtf8 &lt;$&gt; get
  </code></pre>
  
  <p>Pretty good, except that <code>decodeUtf8</code> is a partial function, so I'd rather be using <code>decodeUtf8'</code> and passing the failure through the <code>Get</code> monad. I can't figure out how to fail correctly with the <code>Get</code> monad. Just from looking around in Data.Binary.Get, I see this:</p>
  
  <pre><code>data Decoder a = Fail !B.ByteString {-# UNPACK #-} !ByteOffset String
            | Partial (Maybe B.ByteString -&gt; Decoder a)
            | Done !B.ByteString {-# UNPACK #-} !ByteOffset a
  </code></pre>
  
  <p>Which seems to indicate that there is a way to do what I want. I just can't see how the library authors intend for it to be used. I appreciate any insights that a more learned mind than my own has to offer.</p>