File.hs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. module System.IO.Uniform.File (
  2. FileIO,
  3. openFile
  4. ) where
  5. import System.IO.Uniform
  6. import System.IO.Uniform.External
  7. import Foreign
  8. import Foreign.C.String
  9. import Foreign.C.Error
  10. import qualified Data.ByteString as BS
  11. import Control.Monad
  12. import System.Posix.Types (Fd(..))
  13. -- | UniformIO type for file IO.
  14. instance UniformIO FileIO where
  15. uRead s n = allocaArray n (
  16. \b -> do
  17. count <- c_recv (fd s) b $ fromIntegral n
  18. if count < 0
  19. then throwErrno "could not read"
  20. else BS.packCStringLen (b, fromIntegral count)
  21. )
  22. uPut s t = BS.useAsCStringLen t (
  23. \(str, n) -> do
  24. count <- c_send (fd s) str $ fromIntegral n
  25. when (count < 0) $ throwErrno "could not write"
  26. )
  27. uClose s = do
  28. f <- Fd <$> c_prepareToClose (fd s)
  29. closeFd f
  30. startTls _ = return
  31. isSecure _ = True
  32. -- | Open a file for bidirectional IO.
  33. openFile :: String -> IO FileIO
  34. openFile fileName = do
  35. r <- withCString fileName (
  36. fmap FileIO . c_createFile
  37. )
  38. if fd r == nullPtr
  39. then throwErrno "could not open file"
  40. else return r