Hufflepdf/src/Data/ByteString/Char8/Util.hs

50 lines
1.5 KiB
Haskell

module Data.ByteString.Char8.Util (
decodeHex
, fromInt
, hexString
, previous
, subBS
, toInt
, toBytes
, utf16BEToutf8
) where
import Data.ByteString (ByteString, snoc)
import qualified Data.ByteString as BS (empty, foldl, pack, singleton)
import qualified Data.ByteString.Char8 as Char8 (drop, index, take, unpack)
import Data.Text.Encoding (encodeUtf8, decodeUtf16BE)
import Prelude hiding (length)
previous :: Char -> Int -> ByteString -> Int
previous char position byteString
| Char8.index byteString position == char = position
| otherwise = previous char (position - 1) byteString
subBS :: Int -> Int -> ByteString -> ByteString
subBS offset length = Char8.take length . Char8.drop offset
hexString :: (Num a, Read a) => String -> a
hexString s = read $ "0x" ++ s
fromInt :: Int -> ByteString
fromInt n
| n < 0x100 = BS.singleton $ toEnum n
| otherwise = fromInt (n `div` 0x100) `snoc` (toEnum (n `mod` 0x100))
toBytes :: Int -> Int -> ByteString
toBytes 0 _ = BS.empty
toBytes size n = toBytes (size - 1) (n `div` 0x100) `snoc` (toEnum (n `mod` 0x100))
toInt :: ByteString -> Int
toInt = BS.foldl (\n w -> 0x100*n + fromEnum w) 0
decodeHex :: ByteString -> ByteString
decodeHex = BS.pack . fmap hexString . pairDigits . Char8.unpack
where
pairDigits "" = []
pairDigits [c] = [[c]]
pairDigits (firstChar:secondChar:end) = (firstChar:[secondChar]):pairDigits end
utf16BEToutf8 :: ByteString -> ByteString
utf16BEToutf8 = encodeUtf8 . decodeUtf16BE