903d7ebe5e0d398950af3204b429c8e376794f7b
[ghc-hetmet.git] / compiler / utils / StringBuffer.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The University of Glasgow, 1997-2006
4 %
5
6 Buffers for scanning string input stored in external arrays.
7
8 \begin{code}
9 {-# OPTIONS_GHC -w #-}
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/WorkingConventions#Warnings
14 -- for details
15
16 module StringBuffer
17        (
18         StringBuffer(..),
19         -- non-abstract for vs\/HaskellService
20
21          -- * Creation\/destruction
22         hGetStringBuffer,
23         hGetStringBufferBlock,
24         appendStringBuffers,
25         stringToStringBuffer,
26
27         -- * Inspection
28         nextChar,
29         currentChar,
30         prevChar,
31         atEnd,
32
33         -- * Moving and comparison
34         stepOn,
35         offsetBytes,
36         byteDiff,
37
38         -- * Conversion
39         lexemeToString,
40         lexemeToFastString,
41
42          -- * Parsing integers
43         parseUnsignedInteger,
44        ) where
45
46 #include "HsVersions.h"
47
48 import Encoding
49 import FastString               ( FastString,mkFastString,mkFastStringBytes )
50
51 import Foreign
52 import System.IO                ( hGetBuf, hFileSize,IOMode(ReadMode), hClose
53                                 , Handle, hTell )
54
55 import GHC.Exts
56 import GHC.IOBase               ( IO(..) )
57 import GHC.Base                 ( unsafeChr )
58
59 #if __GLASGOW_HASKELL__ >= 601
60 import System.IO                ( openBinaryFile )
61 #else
62 import IOExts                   ( openFileEx, IOModeEx(..) )
63 #endif
64
65 #if __GLASGOW_HASKELL__ < 601
66 openBinaryFile fp mode = openFileEx fp (BinaryMode mode)
67 #endif
68
69 -- -----------------------------------------------------------------------------
70 -- The StringBuffer type
71
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.
75 --
76 -- A StringBuffer may have a finalizer, depending on how it was
77 -- obtained.
78 --
79 data StringBuffer
80  = StringBuffer {
81      buf :: {-# UNPACK #-} !(ForeignPtr Word8),
82      len :: {-# UNPACK #-} !Int,        -- length
83      cur :: {-# UNPACK #-} !Int         -- current pos
84   }
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.
89
90 instance Show StringBuffer where
91         showsPrec _ s = showString "<stringbuffer(" 
92                       . shows (len s) . showString "," . shows (cur s)
93                       . showString ">"
94
95 -- -----------------------------------------------------------------------------
96 -- Creation / Destruction
97
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
106      hClose h
107      if (r /= size)
108         then ioError (userError "short read of file")
109         else do
110           pokeArray (ptr `plusPtr` size :: Ptr Word8) [0,0,0]
111                  -- sentinels for UTF-8 decoding
112           return (StringBuffer buf size 0)
113
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
122                 if r /= 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)
126
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
139
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)
149
150 -- -----------------------------------------------------------------------------
151 -- Grab a character
152
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#)) =
157   inlinePerformIO $ do
158     withForeignPtr buf $ \(Ptr a#) -> do
159         case utf8DecodeChar# (a# `plusAddr#` cur#) of
160           (# c#, b# #) ->
161              let cur' = I# (b# `minusAddr#` a#) in
162              return (C# c#, StringBuffer buf len cur')
163
164 currentChar :: StringBuffer -> Char
165 currentChar = fst . nextChar
166
167 prevChar :: StringBuffer -> Char -> Char
168 prevChar (StringBuffer buf len 0)   deflt = deflt
169 prevChar (StringBuffer buf len cur) deflt = 
170   inlinePerformIO $ do
171     withForeignPtr buf $ \p -> do
172       p' <- utf8PrevChar (p `plusPtr` cur)
173       return (fst (utf8DecodeChar p'))
174
175 -- -----------------------------------------------------------------------------
176 -- Moving
177
178 stepOn :: StringBuffer -> StringBuffer
179 stepOn s = snd (nextChar s)
180
181 offsetBytes :: Int -> StringBuffer -> StringBuffer
182 offsetBytes i s = s { cur = cur s + i }
183
184 byteDiff :: StringBuffer -> StringBuffer -> Int
185 byteDiff s1 s2 = cur s2 - cur s1
186
187 atEnd :: StringBuffer -> Bool
188 atEnd (StringBuffer _ l c) = l == c
189
190 -- -----------------------------------------------------------------------------
191 -- Conversion
192
193 lexemeToString :: StringBuffer -> Int {-bytes-} -> String
194 lexemeToString _ 0 = ""
195 lexemeToString (StringBuffer buf _ cur) bytes =
196   inlinePerformIO $ 
197     withForeignPtr buf $ \ptr -> 
198       utf8DecodeString (ptr `plusPtr` cur) bytes
199
200 lexemeToFastString :: StringBuffer -> Int {-bytes-} -> FastString
201 lexemeToFastString _ 0 = mkFastString ""
202 lexemeToFastString (StringBuffer buf _ cur) len =
203    inlinePerformIO $
204      withForeignPtr buf $ \ptr ->
205        return $! mkFastStringBytes (ptr `plusPtr` cur) len
206
207 -- -----------------------------------------------------------------------------
208 -- Parsing integer strings in various bases
209
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)))
215
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 
219   = go 0 0
220   where
221     go i x | i == len  = x
222            | otherwise = go (i+1)
223               (x * radix + toInteger (char_to_int (byteOff buf i)))
224
225 -- -----------------------------------------------------------------------------
226 -- under the carpet
227
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
232
233 \end{code}