2 % (c) The University of Glasgow 2006
3 % (c) The University of Glasgow, 1997-2006
6 Buffers for scanning string input stored in external arrays.
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
19 -- non-abstract for vs\/HaskellService
21 -- * Creation\/destruction
23 hGetStringBufferBlock,
33 -- * Moving and comparison
46 #include "HsVersions.h"
49 import FastString ( FastString,mkFastString,mkFastStringBytes )
52 import System.IO ( hGetBuf, hFileSize,IOMode(ReadMode), hClose
56 import GHC.IOBase ( IO(..) )
57 import GHC.Base ( unsafeChr )
59 #if __GLASGOW_HASKELL__ >= 601
60 import System.IO ( openBinaryFile )
62 import IOExts ( openFileEx, IOModeEx(..) )
65 #if __GLASGOW_HASKELL__ < 601
66 openBinaryFile fp mode = openFileEx fp (BinaryMode mode)
69 -- -----------------------------------------------------------------------------
70 -- The StringBuffer type
72 -- |A StringBuffer is an internal pointer to a sized chunk of bytes.
73 -- The bytes are intended to be *immutable*. There are pure
74 -- operations to read the contents of a StringBuffer.
76 -- A StringBuffer may have a finalizer, depending on how it was
81 buf :: {-# UNPACK #-} !(ForeignPtr Word8),
82 len :: {-# UNPACK #-} !Int, -- length
83 cur :: {-# UNPACK #-} !Int -- current pos
85 -- The buffer is assumed to be UTF-8 encoded, and furthermore
86 -- we add three '\0' bytes to the end as sentinels so that the
87 -- decoder doesn't have to check for overflow at every single byte
88 -- of a multibyte sequence.
90 instance Show StringBuffer where
91 showsPrec _ s = showString "<stringbuffer("
92 . shows (len s) . showString "," . shows (cur s)
95 -- -----------------------------------------------------------------------------
96 -- Creation / Destruction
98 hGetStringBuffer :: FilePath -> IO StringBuffer
99 hGetStringBuffer fname = do
100 h <- openBinaryFile fname ReadMode
101 size_i <- hFileSize h
102 let size = fromIntegral size_i
103 buf <- mallocForeignPtrArray (size+3)
104 withForeignPtr buf $ \ptr -> do
105 r <- if size == 0 then return 0 else hGetBuf h ptr size
108 then ioError (userError "short read of file")
110 pokeArray (ptr `plusPtr` size :: Ptr Word8) [0,0,0]
111 -- sentinels for UTF-8 decoding
112 return (StringBuffer buf size 0)
114 hGetStringBufferBlock :: Handle -> Int -> IO StringBuffer
115 hGetStringBufferBlock handle wanted
116 = do size_i <- hFileSize handle
117 offset_i <- hTell handle
118 let size = min wanted (fromIntegral $ size_i-offset_i)
119 buf <- mallocForeignPtrArray (size+3)
120 withForeignPtr buf $ \ptr ->
121 do r <- if size == 0 then return 0 else hGetBuf handle ptr size
123 then ioError (userError $ "short read of file: "++show(r,size,size_i,handle))
124 else do pokeArray (ptr `plusPtr` size :: Ptr Word8) [0,0,0]
125 return (StringBuffer buf size 0)
127 appendStringBuffers :: StringBuffer -> StringBuffer -> IO StringBuffer
128 appendStringBuffers sb1 sb2
129 = do newBuf <- mallocForeignPtrArray (size+3)
130 withForeignPtr newBuf $ \ptr ->
131 withForeignPtr (buf sb1) $ \sb1Ptr ->
132 withForeignPtr (buf sb2) $ \sb2Ptr ->
133 do copyArray (sb1Ptr `advancePtr` cur sb1) ptr (calcLen sb1)
134 copyArray (sb2Ptr `advancePtr` cur sb2) (ptr `advancePtr` cur sb1) (calcLen sb2)
135 pokeArray (ptr `advancePtr` size) [0,0,0]
136 return (StringBuffer newBuf size 0)
137 where calcLen sb = len sb - cur sb
138 size = calcLen sb1 + calcLen sb2
140 stringToStringBuffer :: String -> IO StringBuffer
141 stringToStringBuffer str = do
142 let size = utf8EncodedLength str
143 buf <- mallocForeignPtrArray (size+3)
144 withForeignPtr buf $ \ptr -> do
145 utf8EncodeString ptr str
146 pokeArray (ptr `plusPtr` size :: Ptr Word8) [0,0,0]
147 -- sentinels for UTF-8 decoding
148 return (StringBuffer buf size 0)
150 -- -----------------------------------------------------------------------------
153 -- Getting our fingers dirty a little here, but this is performance-critical
154 {-# INLINE nextChar #-}
155 nextChar :: StringBuffer -> (Char,StringBuffer)
156 nextChar (StringBuffer buf len (I# cur#)) =
158 withForeignPtr buf $ \(Ptr a#) -> do
159 case utf8DecodeChar# (a# `plusAddr#` cur#) of
161 let cur' = I# (b# `minusAddr#` a#) in
162 return (C# c#, StringBuffer buf len cur')
164 currentChar :: StringBuffer -> Char
165 currentChar = fst . nextChar
167 prevChar :: StringBuffer -> Char -> Char
168 prevChar (StringBuffer buf len 0) deflt = deflt
169 prevChar (StringBuffer buf len cur) deflt =
171 withForeignPtr buf $ \p -> do
172 p' <- utf8PrevChar (p `plusPtr` cur)
173 return (fst (utf8DecodeChar p'))
175 -- -----------------------------------------------------------------------------
178 stepOn :: StringBuffer -> StringBuffer
179 stepOn s = snd (nextChar s)
181 offsetBytes :: Int -> StringBuffer -> StringBuffer
182 offsetBytes i s = s { cur = cur s + i }
184 byteDiff :: StringBuffer -> StringBuffer -> Int
185 byteDiff s1 s2 = cur s2 - cur s1
187 atEnd :: StringBuffer -> Bool
188 atEnd (StringBuffer _ l c) = l == c
190 -- -----------------------------------------------------------------------------
193 lexemeToString :: StringBuffer -> Int {-bytes-} -> String
194 lexemeToString _ 0 = ""
195 lexemeToString (StringBuffer buf _ cur) bytes =
197 withForeignPtr buf $ \ptr ->
198 utf8DecodeString (ptr `plusPtr` cur) bytes
200 lexemeToFastString :: StringBuffer -> Int {-bytes-} -> FastString
201 lexemeToFastString _ 0 = mkFastString ""
202 lexemeToFastString (StringBuffer buf _ cur) len =
204 withForeignPtr buf $ \ptr ->
205 return $! mkFastStringBytes (ptr `plusPtr` cur) len
207 -- -----------------------------------------------------------------------------
208 -- Parsing integer strings in various bases
210 byteOff :: StringBuffer -> Int -> Char
211 byteOff (StringBuffer buf _ cur) i =
212 inlinePerformIO $ withForeignPtr buf $ \ptr -> do
213 w <- peek (ptr `plusPtr` (cur+i))
214 return (unsafeChr (fromIntegral (w::Word8)))
216 -- | XXX assumes ASCII digits only (by using byteOff)
217 parseUnsignedInteger :: StringBuffer -> Int -> Integer -> (Char->Int) -> Integer
218 parseUnsignedInteger buf len radix char_to_int
221 go i x | i == len = x
222 | otherwise = go (i+1)
223 (x * radix + toInteger (char_to_int (byteOff buf i)))
225 -- -----------------------------------------------------------------------------
228 -- Just like unsafePerformIO, but we inline it.
229 {-# INLINE inlinePerformIO #-}
230 inlinePerformIO :: IO a -> a
231 inlinePerformIO (IO m) = case m realWorld# of (# _, r #) -> r