Guest User

Untitled

a guest
Apr 26th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. module StringIO where
  2.  
  3. import Prelude hiding (read)
  4.  
  5. import Foreign
  6. import Foreign.ForeignPtr
  7. import Foreign.C.Types
  8.  
  9. import GHC.IO.Handle
  10. import GHC.IO.Buffer
  11. import GHC.IO.BufferedIO
  12. import GHC.IO.Device
  13.  
  14. import Control.Applicative
  15. import Data.Typeable
  16. import Data.Word
  17. import Data.IORef
  18. import System.IO
  19.  
  20. data StringIOBuffer = StringIOBuffer (IORef [Word8])
  21. deriving (Typeable)
  22.  
  23. instance RawIO StringIOBuffer where
  24. read (StringIOBuffer ref) ptr len = do
  25. (w,rest) <- fmap (splitAt len) $ readIORef ref
  26. pokeArray ptr w
  27. writeIORef ref rest
  28. return $ length w
  29.  
  30. readNonBlocking buf ptr len = -- TODO
  31. fmap Just $ read buf ptr len
  32.  
  33. write (StringIOBuffer ref) ptr len = do
  34. r <- peekArray len ptr
  35. modifyIORef ref (++r)
  36.  
  37. writeNonBlocking buf ptr len =
  38. write buf ptr len >> return len -- TODO
  39.  
  40. instance BufferedIO StringIOBuffer where
  41. newBuffer (StringIOBuffer ref) state = do
  42. let buf_len = 1024
  43. buf_ptr <- mallocForeignPtrBytes buf_len
  44. return (emptyBuffer buf_ptr buf_len state)
  45. fillReadBuffer = readBuf
  46. fillReadBuffer0 = readBufNonBlocking
  47. flushWriteBuffer = writeBuf
  48. flushWriteBuffer0 = writeBufNonBlocking
  49.  
  50. instance IODevice StringIOBuffer where
  51. ready _ _ _ = return True
  52. close _ = return ()
  53. devType _ = return RawDevice
  54.  
  55. makeStringIO :: IO Handle
  56. makeStringIO = do
  57. buffer <- StringIOBuffer <$> newIORef []
  58. mkFileHandle buffer "string io" ReadWriteMode (Just localeEncoding) nativeNewlineMode
Add Comment
Please, Sign In to add comment