Search code examples
haskellbytestring

How to get a String from a Lazy.Builder?


I need to manipulate the binary encoding as '0' and '1' of simple strings given as input, using ascii 7-bits.

For the encoding I have used the function Data.ByteString.Lazy.Builder.string7 :: String -> Builder

However, I have not found a way to convert back the resulting Builder object into a string of '0' and '1'. Is it possible ? Is there another way ?

Subsidiary question: And if I wanted it in hexadecimal form as text ?


Solution

  • There's an unpackChars function in Data.ByteString.Lazy.Internal. There's also a non-lazy counterpart in Data.ByteString.Internal.

    import qualified Data.ByteString.Lazy.Builder as Build
    import qualified Data.ByteString.Lazy as BS
    import qualified Data.ByteString.Lazy.Internal as BSI
    
    --> BSI.unpackChars $ Build.toLazyByteString $ Build.string7 "010101"
    --"010101"
    

    You can also use map (chr . fromIntegral) . BS.unpack instead of unpackChars, but unpackChars is probably faster.

    Alternatively, as Michael Snoyman commented below, you could use Data.ByteString.Char8 or its lazy version and you'll get the right conversions to begin with.