An immutable byte string type, with mutable ST buffers and String codecs.
spago install bytestrings
Data.ByteString— the immutableByteStringtype and its pure operationsData.ByteString.ST— mutableSTByteString hbuffersData.ByteString.Encoding—Stringconversions:UTF8,UTF16LE,Latin1,Hex,Base64
import Data.ByteString (bytes, take)
import Data.ByteString.Encoding (Encoding(..), fromString, fromStringLossy, toString, toStringLossy)
main = do
-- encode a string to bytes: `fromString` returns `Nothing` if it can't convert
assertEqual { actual: fromString UTF8 "hi!", expected: Just (bytes [ 0x68, 0x69, 0x21 ]) }
-- `fromStringLossy` is the total variant, doesn't return a `Maybe` and substitutes things it can't represent
let bs = fromStringLossy UTF8 "hi!"
-- render the bytes as hex
assertEqual { actual: toString Hex bs, expected: Just "686921" }
-- slice, then decode back to a string
assertEqual { actual: toString UTF8 (take 2 bs), expected: Just "hi" }
-- strict decoding is `Nothing` on invalid input; the `Lossy` variants are
-- total and substitute instead
assertEqual { actual: toString UTF8 (bytes [ 0x80 ]), expected: Nothing }
assertEqual { actual: toStringLossy UTF8 (bytes [ 0x80 ]), expected: "\xFFFD" }See the tests to see usages.
Sources are formatted with purs-tidy:
purs-tidy format-in-place src test
Module documentation is published on Pursuit.