54 lines
1.5 KiB
Haskell
54 lines
1.5 KiB
Haskell
module Data.ByteString.Char8.Util (
|
|
decodeHex
|
|
, fromInt
|
|
, hexString
|
|
, parseBytes
|
|
, previous
|
|
, subBS
|
|
, toInt
|
|
, utf16BEToutf8
|
|
) where
|
|
|
|
import Data.ByteString (ByteString, snoc)
|
|
import qualified Data.ByteString as BS (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))
|
|
|
|
toInt :: ByteString -> Int
|
|
toInt = BS.foldl (\n w -> 0x100*n + fromEnum w) 0
|
|
|
|
{-
|
|
encodeHex :: ByteString -> ByteString
|
|
encodeHex =
|
|
-}
|
|
|
|
decodeHex :: ByteString -> ByteString
|
|
decodeHex = parseBytes . Char8.unpack
|
|
|
|
parseBytes :: String -> ByteString
|
|
parseBytes = BS.pack . fmap hexString . pairDigits
|
|
where
|
|
pairDigits "" = []
|
|
pairDigits [c] = [[c]]
|
|
pairDigits (firstChar:secondChar:end) = (firstChar:[secondChar]):pairDigits end
|
|
|
|
utf16BEToutf8 :: ByteString -> ByteString
|
|
utf16BEToutf8 = encodeUtf8 . decodeUtf16BE
|