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)
51 buf_size = 8192 :: Int
53 #define STRICT2(f) f a b | a `seq` b `seq` False = undefined
54 #define STRICT3(f) f a b c | a `seq` b `seq` c `seq` False = undefined
56 bPutChar :: BufHandle -> Char -> IO ()
58 bPutChar b@(BufHandle buf r hdl) c = do
61 then do hPutBuf hdl buf buf_size
64 else do pokeElemOff buf i (fromIntegral (ord c) :: Word8)
65 writeFastMutInt r (i+1)
67 bPutStr :: BufHandle -> String -> IO ()
69 bPutStr b@(BufHandle buf r hdl) str = do
72 where loop _ i | i `seq` False = undefined
73 loop "" i = do writeFastMutInt r i; return ()
76 hPutBuf hdl buf buf_size
79 pokeElemOff buf i (fromIntegral (ord c))
82 bPutFS :: BufHandle -> FastString -> IO ()
83 bPutFS b@(BufHandle buf r hdl) fs@(FastString _ len _ fp _) =
84 withForeignPtr fp $ \ptr -> do
86 if (i + len) >= buf_size
87 then do hPutBuf hdl buf i
90 then hPutBuf hdl ptr len
93 copyBytes (buf `plusPtr` i) ptr len
94 writeFastMutInt r (i+len)
96 bPutLitString :: BufHandle -> Addr# -> Int# -> IO ()
97 bPutLitString b@(BufHandle buf r hdl) a# len# = do
100 if (i+len) >= buf_size
101 then do hPutBuf hdl buf i
104 then hPutBuf hdl (Ptr a#) len
105 else bPutLitString b a# len#
107 copyBytes (buf `plusPtr` i) (Ptr a#) len
108 writeFastMutInt r (i+len)
110 bFlush :: BufHandle -> IO ()
111 bFlush b@(BufHandle buf r hdl) = do
112 i <- readFastMutInt r
113 when (i > 0) $ hPutBuf hdl buf i
118 myPutBuf s hdl buf i =
119 modifyIOError (\e -> ioeSetErrorString e (ioeGetErrorString e ++ ':':s ++ " (" ++ show buf ++ "," ++ show i ++ ")")) $