haskellbytestring

How to get nth byte from ByteString?


How can I get nth byte of ByteString in Haskell?

I tried to find function like !! for ByteStrings, but found nothing.


Solution

  • ByteString.index is the function you're looking for.

    Most of the "containerish" types emulate the extended list interface; you also want to be careful because that index function will crash the program if you feed it a string that's too short (as will !! on ordinary lists). A better implementation might be

    import Data.ByteString as B
    nthByte :: Int -> B.ByteString -> Maybe Word8
    nthByte n bs = fst <$> B.uncons (B.drop n bs)
    

    which, reading inside out, drops the first n bytes (maybe producing an empty byte string), then attempts to split the first character from the remainder, and if successful, ignores the rest of the string.