1 -----------------------------------------------------------------------------
3 -- Fast write-buffered Handles
5 -- (c) The University of Glasgow 2005-2006
7 -- This is a simple abstraction over Handles that offers very fast write
8 -- buffering, but without the thread safety that Handles provide. It's used
9 -- to save time in Pretty.printDoc.
11 -----------------------------------------------------------------------------
23 #include "HsVersions.h"
28 import Control.Monad ( when )
29 import Data.Char ( ord )
33 import GHC.IOBase ( IO(..) )
34 import GHC.Ptr ( Ptr(..) )
36 import GHC.Exts ( Int(..), Int#, Addr# )
38 -- -----------------------------------------------------------------------------
40 data BufHandle = BufHandle {-#UNPACK#-}!(Ptr Word8)
41 {-#UNPACK#-}!FastMutInt
44 newBufHandle :: Handle -> IO BufHandle
46 ptr <- mallocBytes buf_size
49 return (BufHandle ptr r hdl)
54 #define STRICT2(f) f a b | a `seq` b `seq` False = undefined
55 #define STRICT3(f) f a b c | a `seq` b `seq` c `seq` False = undefined
57 bPutChar :: BufHandle -> Char -> IO ()
59 bPutChar b@(BufHandle buf r hdl) c = do
62 then do hPutBuf hdl buf buf_size
65 else do pokeElemOff buf i (fromIntegral (ord c) :: Word8)
66 writeFastMutInt r (i+1)
68 bPutStr :: BufHandle -> String -> IO ()
70 bPutStr (BufHandle buf r hdl) str = do
73 where loop _ i | i `seq` False = undefined
74 loop "" i = do writeFastMutInt r i; return ()
77 hPutBuf hdl buf buf_size
80 pokeElemOff buf i (fromIntegral (ord c))
83 bPutFS :: BufHandle -> FastString -> IO ()
84 bPutFS b@(BufHandle buf r hdl) fs@(FastString _ len _ fp _) =
85 withForeignPtr fp $ \ptr -> do
87 if (i + len) >= buf_size
88 then do hPutBuf hdl buf i
91 then hPutBuf hdl ptr len
94 copyBytes (buf `plusPtr` i) ptr len
95 writeFastMutInt r (i+len)
97 bPutLitString :: BufHandle -> Addr# -> Int# -> IO ()
98 bPutLitString b@(BufHandle buf r hdl) a# len# = do
100 i <- readFastMutInt r
101 if (i+len) >= buf_size
102 then do hPutBuf hdl buf i
105 then hPutBuf hdl (Ptr a#) len
106 else bPutLitString b a# len#
108 copyBytes (buf `plusPtr` i) (Ptr a#) len
109 writeFastMutInt r (i+len)
111 bFlush :: BufHandle -> IO ()
112 bFlush (BufHandle buf r hdl) = do
113 i <- readFastMutInt r
114 when (i > 0) $ hPutBuf hdl buf i
119 myPutBuf s hdl buf i =
120 modifyIOError (\e -> ioeSetErrorString e (ioeGetErrorString e ++ ':':s ++ " (" ++ show buf ++ "," ++ show i ++ ")")) $