{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__ >= 701
{-# LANGUAGE Trustworthy #-}
#endif
module System.IO.UTF8 (
print
, putStr
, putStrLn
, getLine
, readLn
, openBinaryFile
, withBinaryFile
, readFile
, writeFile
, appendFile
, interact
, getContents
, hGetLine
, hGetContents
, hPutStr
, hPutStrLn
) where
import Control.Monad (liftM)
import Data.Word (Word8)
import Prelude (String, (=<<), (.), map, Enum(toEnum, fromEnum), Read,
Show(..))
import System.IO (Handle, IO, FilePath, IOMode(AppendMode, ReadMode, WriteMode))
import qualified System.IO as IO
import Control.Exception (bracket)
import Codec.Binary.UTF8.String (encode, decode)
encodeString :: String -> String
encodeString xs = bytesToString (encode xs)
decodeString :: String -> String
decodeString xs = decode (stringToBytes xs)
bytesToString :: [Word8] -> String
bytesToString xs = map (toEnum . fromEnum) xs
stringToBytes :: String -> [Word8]
stringToBytes xs = map (toEnum . fromEnum) xs
print :: Show a => a -> IO ()
print x = putStrLn (show x)
putStr :: String -> IO ()
putStr x = IO.putStr (encodeString x)
putStrLn :: String -> IO ()
putStrLn x = IO.putStrLn (encodeString x)
getLine :: IO String
getLine = liftM decodeString IO.getLine
readLn :: Read a => IO a
readLn = IO.readIO =<< getLine
openBinaryFile :: FilePath -> IOMode -> IO Handle
openBinaryFile n m = IO.openBinaryFile (encodeString n) m
withBinaryFile :: FilePath -> IOMode -> (Handle -> IO a) -> IO a
withBinaryFile n m f = bracket (openBinaryFile n m) IO.hClose f
readFile :: FilePath -> IO String
readFile n = hGetContents =<< openBinaryFile n ReadMode
writeFile :: FilePath -> String -> IO ()
writeFile n s = withBinaryFile n WriteMode (\ h -> hPutStr h s)
appendFile :: FilePath -> String -> IO ()
appendFile n s = withBinaryFile n AppendMode (\ h -> hPutStr h s)
hGetLine :: Handle -> IO String
hGetLine h = liftM decodeString (IO.hGetLine h)
hGetContents :: Handle -> IO String
hGetContents h = liftM decodeString (IO.hGetContents h)
hPutStr :: Handle -> String -> IO ()
hPutStr h s = IO.hPutStr h (encodeString s)
hPutStrLn :: Handle -> String -> IO ()
hPutStrLn h s = IO.hPutStrLn h (encodeString s)
getContents :: IO String
getContents = liftM decodeString IO.getContents
interact :: (String -> String) -> IO ()
interact f = IO.interact (encodeString . f . decodeString)