-----------------------------------------------------------------------------
-- Implements only the functions necessary for Haskore!
--
-- Suitable for use with Hugs 98
-----------------------------------------------------------------------------

module Haskore.General.IO
          (openBinaryFile, readBinaryFile, writeBinaryFile,
           ByteString, stringCharFromByte, stringByteFromChar, )
   where

import System.IO
   (IOMode(ReadMode, WriteMode),
    openBinaryFile, hClose, hGetContents, hPutStr, )
import Control.Exception(bracket)
import Control.Monad(liftM)
import Data.Char (ord, chr)
import Data.Word (Word8)

type ByteString = [Word8]

{- |
Hugs makes trouble here because it performs UTF-8 conversions.
E.g. @[255]@ is output as @[195,191]@
It would be easy to replace these routines by FastPackedString(fps).ByteString.Lazy,
however this introduces a new package dependency.
-}
writeBinaryFile :: FilePath -> ByteString -> IO ()
writeBinaryFile path str =
   bracket (openBinaryFile path WriteMode) hClose
           (flip hPutStr (stringCharFromByte str))

stringCharFromByte :: ByteString -> String
stringCharFromByte = map (chr . fromIntegral)

readBinaryFile :: FilePath -> IO ByteString
readBinaryFile path =
   liftM stringByteFromChar .
      hGetContents =<< openBinaryFile path ReadMode

stringByteFromChar :: String -> ByteString
stringByteFromChar = map (fromIntegral . ord)
