| 1 | {-# LANGUAGE CPP, ScopedTypeVariables #-} |
| 2 | -- |
| 3 | -- (c) The University of Glasgow 2002 |
| 4 | -- |
| 5 | -- Binary I/O library, with special tweaks for GHC |
| 6 | -- |
| 7 | -- Based on the nhc98 Binary library, which is copyright |
| 8 | -- (c) Malcolm Wallace and Colin Runciman, University of York, 1998. |
| 9 | -- Under the terms of the license for that software, we must tell you |
| 10 | -- where you can obtain the original version of the Binary library, namely |
| 11 | -- http://www.cs.york.ac.uk/fp/nhc98/ |
| 12 | |
| 13 | module Binary |
| 14 | ( {-type-} Bin, |
| 15 | {-class-} Binary(..), |
| 16 | {-type-} BinHandle, |
| 17 | |
| 18 | openBinIO, openBinIO_, |
| 19 | openBinMem, |
| 20 | -- closeBin, |
| 21 | |
| 22 | seekBin, |
| 23 | tellBin, |
| 24 | castBin, |
| 25 | |
| 26 | writeBinMem, |
| 27 | readBinMem, |
| 28 | |
| 29 | isEOFBin, |
| 30 | |
| 31 | -- for writing instances: |
| 32 | putByte, |
| 33 | getByte, |
| 34 | putSharedString, |
| 35 | getSharedString, |
| 36 | |
| 37 | -- lazy Bin I/O |
| 38 | lazyGet, |
| 39 | lazyPut, |
| 40 | |
| 41 | #if __GLASGOW_HASKELL__<610 |
| 42 | -- GHC only: |
| 43 | ByteArray(..), |
| 44 | getByteArray, |
| 45 | putByteArray, |
| 46 | #endif |
| 47 | |
| 48 | getBinFileWithDict, -- :: Binary a => FilePath -> IO a |
| 49 | putBinFileWithDict, -- :: Binary a => FilePath -> ModuleName -> a -> IO () |
| 50 | |
| 51 | ) where |
| 52 | |
| 53 | #if __GLASGOW_HASKELL__>=604 |
| 54 | #include "ghcconfig.h" |
| 55 | #else |
| 56 | #include "config.h" |
| 57 | #endif |
| 58 | |
| 59 | import FastMutInt |
| 60 | |
| 61 | import Map (Map) |
| 62 | import qualified Map as Map |
| 63 | #if __GLASGOW_HASKELL__>=602 |
| 64 | # if __GLASGOW_HASKELL__>=707 |
| 65 | import Data.HashTable.Class as HashTable |
| 66 | (HashTable) |
| 67 | import Data.HashTable.IO as HashTable |
| 68 | (BasicHashTable, toList, new, insert, lookup) |
| 69 | # else |
| 70 | import Data.HashTable as HashTable |
| 71 | # endif |
| 72 | #endif |
| 73 | import Data.Array.IO |
| 74 | import Data.Array |
| 75 | import Data.Bits |
| 76 | import Data.Int |
| 77 | import Data.Word |
| 78 | import Data.IORef |
| 79 | import Data.Char ( ord, chr ) |
| 80 | import Data.Array.Base ( unsafeRead, unsafeWrite ) |
| 81 | import Control.Monad ( when, liftM ) |
| 82 | import System.IO as IO |
| 83 | import System.IO.Unsafe ( unsafeInterleaveIO ) |
| 84 | import System.IO.Error ( mkIOError, eofErrorType ) |
| 85 | import GHC.Real ( Ratio(..) ) |
| 86 | import GHC.Exts |
| 87 | # if __GLASGOW_HASKELL__>=612 |
| 88 | import GHC.IO (IO(IO)) |
| 89 | #else |
| 90 | import GHC.IOBase (IO(IO)) |
| 91 | #endif |
| 92 | import GHC.Word ( Word8(..) ) |
| 93 | # if __GLASGOW_HASKELL__<602 |
| 94 | import GHC.Handle ( hSetBinaryMode ) |
| 95 | # endif |
| 96 | -- for debug |
| 97 | import System.CPUTime (getCPUTime) |
| 98 | import Numeric (showFFloat) |
| 99 | |
| 100 | #define SIZEOF_HSINT SIZEOF_VOID_P |
| 101 | |
| 102 | type BinArray = IOUArray Int Word8 |
| 103 | |
| 104 | --------------------------------------------------------------- |
| 105 | -- BinHandle |
| 106 | --------------------------------------------------------------- |
| 107 | |
| 108 | data BinHandle |
| 109 | = BinMem { -- binary data stored in an unboxed array |
| 110 | bh_usr :: UserData, -- sigh, need parameterized modules :-) |
| 111 | off_r :: !FastMutInt, -- the current offset |
| 112 | sz_r :: !FastMutInt, -- size of the array (cached) |
| 113 | arr_r :: !(IORef BinArray) -- the array (bounds: (0,size-1)) |
| 114 | } |
| 115 | -- XXX: should really store a "high water mark" for dumping out |
| 116 | -- the binary data to a file. |
| 117 | |
| 118 | | BinIO { -- binary data stored in a file |
| 119 | bh_usr :: UserData, |
| 120 | off_r :: !FastMutInt, -- the current offset (cached) |
| 121 | hdl :: !IO.Handle -- the file handle (must be seekable) |
| 122 | } |
| 123 | -- cache the file ptr in BinIO; using hTell is too expensive |
| 124 | -- to call repeatedly. If anyone else is modifying this Handle |
| 125 | -- at the same time, we'll be screwed. |
| 126 | |
| 127 | getUserData :: BinHandle -> UserData |
| 128 | getUserData bh = bh_usr bh |
| 129 | |
| 130 | setUserData :: BinHandle -> UserData -> BinHandle |
| 131 | setUserData bh us = bh { bh_usr = us } |
| 132 | |
| 133 | |
| 134 | --------------------------------------------------------------- |
| 135 | -- Bin |
| 136 | --------------------------------------------------------------- |
| 137 | |
| 138 | newtype Bin a = BinPtr Int |
| 139 | deriving (Eq, Ord, Show, Bounded) |
| 140 | |
| 141 | castBin :: Bin a -> Bin b |
| 142 | castBin (BinPtr i) = BinPtr i |
| 143 | |
| 144 | --------------------------------------------------------------- |
| 145 | -- class Binary |
| 146 | --------------------------------------------------------------- |
| 147 | |
| 148 | class Binary a where |
| 149 | put_ :: BinHandle -> a -> IO () |
| 150 | put :: BinHandle -> a -> IO (Bin a) |
| 151 | get :: BinHandle -> IO a |
| 152 | |
| 153 | -- define one of put_, put. Use of put_ is recommended because it |
| 154 | -- is more likely that tail-calls can kick in, and we rarely need the |
| 155 | -- position return value. |
| 156 | put_ bh a = do put bh a; return () |
| 157 | put bh a = do p <- tellBin bh; put_ bh a; return p |
| 158 | |
| 159 | putAt :: Binary a => BinHandle -> Bin a -> a -> IO () |
| 160 | putAt bh p x = do seekBin bh p; put bh x; return () |
| 161 | |
| 162 | getAt :: Binary a => BinHandle -> Bin a -> IO a |
| 163 | getAt bh p = do seekBin bh p; get bh |
| 164 | |
| 165 | openBinIO_ :: IO.Handle -> IO BinHandle |
| 166 | openBinIO_ h = openBinIO h |
| 167 | |
| 168 | openBinIO :: IO.Handle -> IO BinHandle |
| 169 | openBinIO h = do |
| 170 | r <- newFastMutInt |
| 171 | writeFastMutInt r 0 |
| 172 | return (BinIO noUserData r h) |
| 173 | |
| 174 | openBinMem :: Int -> IO BinHandle |
| 175 | openBinMem size |
| 176 | | size <= 0 = error "Data.Binary.openBinMem: size must be >= 0" |
| 177 | | otherwise = do |
| 178 | arr <- newArray_ (0,size-1) |
| 179 | arr_r <- newIORef arr |
| 180 | ix_r <- newFastMutInt |
| 181 | writeFastMutInt ix_r 0 |
| 182 | sz_r <- newFastMutInt |
| 183 | writeFastMutInt sz_r size |
| 184 | return (BinMem noUserData ix_r sz_r arr_r) |
| 185 | |
| 186 | tellBin :: BinHandle -> IO (Bin a) |
| 187 | tellBin (BinIO _ r _) = do ix <- readFastMutInt r; return (BinPtr ix) |
| 188 | tellBin (BinMem _ r _ _) = do ix <- readFastMutInt r; return (BinPtr ix) |
| 189 | |
| 190 | seekBin :: BinHandle -> Bin a -> IO () |
| 191 | seekBin (BinIO _ ix_r h) (BinPtr p) = do |
| 192 | writeFastMutInt ix_r p |
| 193 | hSeek h AbsoluteSeek (fromIntegral p) |
| 194 | seekBin h@(BinMem _ ix_r sz_r a) (BinPtr p) = do |
| 195 | sz <- readFastMutInt sz_r |
| 196 | if (p >= sz) |
| 197 | then do expandBin h p; writeFastMutInt ix_r p |
| 198 | else writeFastMutInt ix_r p |
| 199 | |
| 200 | isEOFBin :: BinHandle -> IO Bool |
| 201 | isEOFBin (BinMem _ ix_r sz_r a) = do |
| 202 | ix <- readFastMutInt ix_r |
| 203 | sz <- readFastMutInt sz_r |
| 204 | return (ix >= sz) |
| 205 | isEOFBin (BinIO _ ix_r h) = hIsEOF h |
| 206 | |
| 207 | writeBinMem :: BinHandle -> FilePath -> IO () |
| 208 | writeBinMem (BinIO _ _ _) _ = error "Data.Binary.writeBinMem: not a memory handle" |
| 209 | writeBinMem (BinMem _ ix_r sz_r arr_r) fn = do |
| 210 | h <- openFile fn WriteMode |
| 211 | hSetBinaryMode h True |
| 212 | arr <- readIORef arr_r |
| 213 | ix <- readFastMutInt ix_r |
| 214 | hPutArray h arr ix |
| 215 | hClose h |
| 216 | |
| 217 | readBinMem :: FilePath -> IO BinHandle |
| 218 | -- Return a BinHandle with a totally undefined State |
| 219 | readBinMem filename = do |
| 220 | h <- openFile filename ReadMode |
| 221 | hSetBinaryMode h True |
| 222 | filesize' <- hFileSize h |
| 223 | let filesize = fromIntegral filesize' |
| 224 | arr <- newArray_ (0,filesize-1) |
| 225 | count <- hGetArray h arr filesize |
| 226 | when (count /= filesize) |
| 227 | (error ("Binary.readBinMem: only read " ++ show count ++ " bytes")) |
| 228 | hClose h |
| 229 | arr_r <- newIORef arr |
| 230 | ix_r <- newFastMutInt |
| 231 | writeFastMutInt ix_r 0 |
| 232 | sz_r <- newFastMutInt |
| 233 | writeFastMutInt sz_r filesize |
| 234 | return (BinMem noUserData ix_r sz_r arr_r) |
| 235 | |
| 236 | -- expand the size of the array to include a specified offset |
| 237 | expandBin :: BinHandle -> Int -> IO () |
| 238 | expandBin (BinMem _ ix_r sz_r arr_r) off = do |
| 239 | sz <- readFastMutInt sz_r |
| 240 | let sz' = head (dropWhile (<= off) (iterate (* 2) sz)) |
| 241 | arr <- readIORef arr_r |
| 242 | arr' <- newArray_ (0,sz'-1) |
| 243 | sequence_ [ unsafeRead arr i >>= unsafeWrite arr' i |
| 244 | | i <- [ 0 .. sz-1 ] ] |
| 245 | writeFastMutInt sz_r sz' |
| 246 | writeIORef arr_r arr' |
| 247 | #ifdef DEBUG |
| 248 | hPutStrLn stderr ("Binary: expanding to size: " ++ show sz') |
| 249 | #endif |
| 250 | return () |
| 251 | expandBin (BinIO _ _ _) _ = return () |
| 252 | -- no need to expand a file, we'll assume they expand by themselves. |
| 253 | {-# INLINE expandBin #-} |
| 254 | |
| 255 | -- ----------------------------------------------------------------------------- |
| 256 | -- Low-level reading/writing of bytes |
| 257 | |
| 258 | putWord8 :: BinHandle -> Word8 -> IO () |
| 259 | putWord8 h@(BinMem _ ix_r sz_r arr_r) w = do |
| 260 | ix <- readFastMutInt ix_r |
| 261 | sz <- readFastMutInt sz_r |
| 262 | -- double the size of the array if it overflows |
| 263 | if (ix >= sz) |
| 264 | then do expandBin h ix |
| 265 | putWord8 h w |
| 266 | else do arr <- readIORef arr_r |
| 267 | unsafeWrite arr ix w |
| 268 | writeFastMutInt ix_r (ix+1) |
| 269 | return () |
| 270 | putWord8 (BinIO _ ix_r h) w = do |
| 271 | ix <- readFastMutInt ix_r |
| 272 | hPutChar h (chr (fromIntegral w)) -- XXX not really correct |
| 273 | writeFastMutInt ix_r (ix+1) |
| 274 | return () |
| 275 | |
| 276 | getWord8 :: BinHandle -> IO Word8 |
| 277 | getWord8 (BinMem _ ix_r sz_r arr_r) = do |
| 278 | ix <- readFastMutInt ix_r |
| 279 | sz <- readFastMutInt sz_r |
| 280 | when (ix >= sz) $ |
| 281 | ioError (mkIOError eofErrorType "Data.Binary.getWord8" Nothing Nothing) |
| 282 | arr <- readIORef arr_r |
| 283 | w <- unsafeRead arr ix |
| 284 | writeFastMutInt ix_r (ix+1) |
| 285 | return w |
| 286 | getWord8 (BinIO _ ix_r h) = do |
| 287 | ix <- readFastMutInt ix_r |
| 288 | c <- hGetChar h |
| 289 | writeFastMutInt ix_r (ix+1) |
| 290 | return $! (fromIntegral (ord c)) -- XXX not really correct |
| 291 | |
| 292 | putByte :: BinHandle -> Word8 -> IO () |
| 293 | putByte bh w = put_ bh w |
| 294 | |
| 295 | getByte :: BinHandle -> IO Word8 |
| 296 | getByte = getWord8 |
| 297 | |
| 298 | -- ----------------------------------------------------------------------------- |
| 299 | -- Primitive Word writes |
| 300 | |
| 301 | instance Binary Word8 where |
| 302 | put_ = putWord8 |
| 303 | get = getWord8 |
| 304 | |
| 305 | instance Binary Word16 where |
| 306 | put_ h w = do -- XXX too slow.. inline putWord8? |
| 307 | putByte h (fromIntegral (w `shiftR` 8)) |
| 308 | putByte h (fromIntegral (w .&. 0xff)) |
| 309 | get h = do |
| 310 | w1 <- getWord8 h |
| 311 | w2 <- getWord8 h |
| 312 | return $! ((fromIntegral w1 `shiftL` 8) .|. fromIntegral w2) |
| 313 | |
| 314 | |
| 315 | instance Binary Word32 where |
| 316 | put_ h w = do |
| 317 | putByte h (fromIntegral (w `shiftR` 24)) |
| 318 | putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff)) |
| 319 | putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff)) |
| 320 | putByte h (fromIntegral (w .&. 0xff)) |
| 321 | get h = do |
| 322 | w1 <- getWord8 h |
| 323 | w2 <- getWord8 h |
| 324 | w3 <- getWord8 h |
| 325 | w4 <- getWord8 h |
| 326 | return $! ((fromIntegral w1 `shiftL` 24) .|. |
| 327 | (fromIntegral w2 `shiftL` 16) .|. |
| 328 | (fromIntegral w3 `shiftL` 8) .|. |
| 329 | (fromIntegral w4)) |
| 330 | |
| 331 | |
| 332 | instance Binary Word64 where |
| 333 | put_ h w = do |
| 334 | putByte h (fromIntegral (w `shiftR` 56)) |
| 335 | putByte h (fromIntegral ((w `shiftR` 48) .&. 0xff)) |
| 336 | putByte h (fromIntegral ((w `shiftR` 40) .&. 0xff)) |
| 337 | putByte h (fromIntegral ((w `shiftR` 32) .&. 0xff)) |
| 338 | putByte h (fromIntegral ((w `shiftR` 24) .&. 0xff)) |
| 339 | putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff)) |
| 340 | putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff)) |
| 341 | putByte h (fromIntegral (w .&. 0xff)) |
| 342 | get h = do |
| 343 | w1 <- getWord8 h |
| 344 | w2 <- getWord8 h |
| 345 | w3 <- getWord8 h |
| 346 | w4 <- getWord8 h |
| 347 | w5 <- getWord8 h |
| 348 | w6 <- getWord8 h |
| 349 | w7 <- getWord8 h |
| 350 | w8 <- getWord8 h |
| 351 | return $! ((fromIntegral w1 `shiftL` 56) .|. |
| 352 | (fromIntegral w2 `shiftL` 48) .|. |
| 353 | (fromIntegral w3 `shiftL` 40) .|. |
| 354 | (fromIntegral w4 `shiftL` 32) .|. |
| 355 | (fromIntegral w5 `shiftL` 24) .|. |
| 356 | (fromIntegral w6 `shiftL` 16) .|. |
| 357 | (fromIntegral w7 `shiftL` 8) .|. |
| 358 | (fromIntegral w8)) |
| 359 | |
| 360 | -- ----------------------------------------------------------------------------- |
| 361 | -- Primitive Int writes |
| 362 | |
| 363 | instance Binary Int8 where |
| 364 | put_ h w = put_ h (fromIntegral w :: Word8) |
| 365 | get h = do w <- get h; return $! (fromIntegral (w::Word8)) |
| 366 | |
| 367 | instance Binary Int16 where |
| 368 | put_ h w = put_ h (fromIntegral w :: Word16) |
| 369 | get h = do w <- get h; return $! (fromIntegral (w::Word16)) |
| 370 | |
| 371 | instance Binary Int32 where |
| 372 | put_ h w = put_ h (fromIntegral w :: Word32) |
| 373 | get h = do w <- get h; return $! (fromIntegral (w::Word32)) |
| 374 | |
| 375 | instance Binary Int64 where |
| 376 | put_ h w = put_ h (fromIntegral w :: Word64) |
| 377 | get h = do w <- get h; return $! (fromIntegral (w::Word64)) |
| 378 | |
| 379 | -- ----------------------------------------------------------------------------- |
| 380 | -- Instances for standard types |
| 381 | |
| 382 | instance Binary () where |
| 383 | put_ bh () = return () |
| 384 | get _ = return () |
| 385 | -- getF bh p = case getBitsF bh 0 p of (_,b) -> ((),b) |
| 386 | |
| 387 | instance Binary Bool where |
| 388 | put_ bh b = putByte bh (fromIntegral (fromEnum b)) |
| 389 | get bh = do x <- getWord8 bh; return $! (toEnum (fromIntegral x)) |
| 390 | -- getF bh p = case getBitsF bh 1 p of (x,b) -> (toEnum x,b) |
| 391 | |
| 392 | instance Binary Char where |
| 393 | put_ bh c = put_ bh (fromIntegral (ord c) :: Word8) |
| 394 | get bh = do x <- get bh; return $! (chr (fromIntegral (x :: Word8))) |
| 395 | -- getF bh p = case getBitsF bh 8 p of (x,b) -> (toEnum x,b) |
| 396 | |
| 397 | instance Binary Int where |
| 398 | #if SIZEOF_HSINT == 4 |
| 399 | put_ bh i = put_ bh (fromIntegral i :: Int32) |
| 400 | get bh = do |
| 401 | x <- get bh |
| 402 | return $! (fromIntegral (x :: Int32)) |
| 403 | #elif SIZEOF_HSINT == 8 |
| 404 | put_ bh i = put_ bh (fromIntegral i :: Int64) |
| 405 | get bh = do |
| 406 | x <- get bh |
| 407 | return $! (fromIntegral (x :: Int64)) |
| 408 | #else |
| 409 | #error "unsupported sizeof(HsInt)" |
| 410 | #endif |
| 411 | -- getF bh = getBitsF bh 32 |
| 412 | |
| 413 | instance Binary a => Binary [a] where |
| 414 | put_ bh list = do put_ bh (length list) |
| 415 | mapM_ (put_ bh) list |
| 416 | get bh = do len <- get bh |
| 417 | let getMany :: Int -> IO [a] |
| 418 | getMany 0 = return [] |
| 419 | getMany n = do x <- get bh |
| 420 | xs <- getMany (n-1) |
| 421 | return (x:xs) |
| 422 | getMany len |
| 423 | |
| 424 | instance (Binary a, Binary b) => Binary (a,b) where |
| 425 | put_ bh (a,b) = do put_ bh a; put_ bh b |
| 426 | get bh = do a <- get bh |
| 427 | b <- get bh |
| 428 | return (a,b) |
| 429 | |
| 430 | instance (Binary a, Binary b, Binary c) => Binary (a,b,c) where |
| 431 | put_ bh (a,b,c) = do put_ bh a; put_ bh b; put_ bh c |
| 432 | get bh = do a <- get bh |
| 433 | b <- get bh |
| 434 | c <- get bh |
| 435 | return (a,b,c) |
| 436 | |
| 437 | instance (Binary a, Binary b, Binary c, Binary d) => Binary (a,b,c,d) where |
| 438 | put_ bh (a,b,c,d) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d |
| 439 | get bh = do a <- get bh |
| 440 | b <- get bh |
| 441 | c <- get bh |
| 442 | d <- get bh |
| 443 | return (a,b,c,d) |
| 444 | |
| 445 | instance Binary a => Binary (Maybe a) where |
| 446 | put_ bh Nothing = putByte bh 0 |
| 447 | put_ bh (Just a) = do putByte bh 1; put_ bh a |
| 448 | get bh = do h <- getWord8 bh |
| 449 | case h of |
| 450 | 0 -> return Nothing |
| 451 | _ -> do x <- get bh; return (Just x) |
| 452 | |
| 453 | instance (Binary a, Binary b) => Binary (Either a b) where |
| 454 | put_ bh (Left a) = do putByte bh 0; put_ bh a |
| 455 | put_ bh (Right b) = do putByte bh 1; put_ bh b |
| 456 | get bh = do h <- getWord8 bh |
| 457 | case h of |
| 458 | 0 -> do a <- get bh ; return (Left a) |
| 459 | _ -> do b <- get bh ; return (Right b) |
| 460 | |
| 461 | instance (Binary a, Binary i, Ix i) => Binary (Array i a) where |
| 462 | put_ bh arr = do put_ bh (Data.Array.bounds arr) |
| 463 | put_ bh (Data.Array.elems arr) |
| 464 | get bh = do bounds <- get bh |
| 465 | elems <- get bh |
| 466 | return $ listArray bounds elems |
| 467 | |
| 468 | instance (Binary key, Ord key, Binary elem) => Binary (Map key elem) where |
| 469 | -- put_ bh fm = put_ bh (Map.toList fm) |
| 470 | -- get bh = do list <- get bh |
| 471 | -- return (Map.fromList list) |
| 472 | |
| 473 | put_ bh fm = do let list = Map.toList fm |
| 474 | put_ bh (length list) |
| 475 | mapM_ (\(key, val) -> do put_ bh key |
| 476 | lazyPut bh val) list |
| 477 | get bh = do len <- get bh |
| 478 | let getMany :: Int -> IO [(key,elem)] |
| 479 | getMany 0 = return [] |
| 480 | getMany n = do key <- get bh |
| 481 | val <- lazyGet bh |
| 482 | xs <- getMany (n-1) |
| 483 | return ((key,val):xs) |
| 484 | -- printElapsedTime "before get Map" |
| 485 | list <- getMany len |
| 486 | -- printElapsedTime "after get Map" |
| 487 | return (Map.fromList list) |
| 488 | |
| 489 | #ifdef __GLASGOW_HASKELL__ |
| 490 | #if __GLASGOW_HASKELL__<610 |
| 491 | instance Binary Integer where |
| 492 | put_ bh (S# i#) = do putByte bh 0; put_ bh (I# i#) |
| 493 | put_ bh (J# s# a#) = do |
| 494 | p <- putByte bh 1; |
| 495 | put_ bh (I# s#) |
| 496 | let sz# = sizeofByteArray# a# -- in *bytes* |
| 497 | put_ bh (I# sz#) -- in *bytes* |
| 498 | putByteArray bh a# sz# |
| 499 | |
| 500 | get bh = do |
| 501 | b <- getByte bh |
| 502 | case b of |
| 503 | 0 -> do (I# i#) <- get bh |
| 504 | return (S# i#) |
| 505 | _ -> do (I# s#) <- get bh |
| 506 | sz <- get bh |
| 507 | (BA a#) <- getByteArray bh sz |
| 508 | return (J# s# a#) |
| 509 | |
| 510 | putByteArray :: BinHandle -> ByteArray# -> Int# -> IO () |
| 511 | putByteArray bh a s# = loop 0# |
| 512 | where loop n# |
| 513 | | n# ==# s# = return () |
| 514 | | otherwise = do |
| 515 | putByte bh (indexByteArray a n#) |
| 516 | loop (n# +# 1#) |
| 517 | |
| 518 | getByteArray :: BinHandle -> Int -> IO ByteArray |
| 519 | getByteArray bh (I# sz) = do |
| 520 | (MBA arr) <- newByteArray sz |
| 521 | let loop n |
| 522 | | n ==# sz = return () |
| 523 | | otherwise = do |
| 524 | w <- getByte bh |
| 525 | writeByteArray arr n w |
| 526 | loop (n +# 1#) |
| 527 | loop 0# |
| 528 | freezeByteArray arr |
| 529 | |
| 530 | |
| 531 | data ByteArray = BA ByteArray# |
| 532 | data MBA = MBA (MutableByteArray# RealWorld) |
| 533 | |
| 534 | newByteArray :: Int# -> IO MBA |
| 535 | newByteArray sz = IO $ \s -> |
| 536 | case newByteArray# sz s of { (# s, arr #) -> |
| 537 | (# s, MBA arr #) } |
| 538 | |
| 539 | freezeByteArray :: MutableByteArray# RealWorld -> IO ByteArray |
| 540 | freezeByteArray arr = IO $ \s -> |
| 541 | case unsafeFreezeByteArray# arr s of { (# s, arr #) -> |
| 542 | (# s, BA arr #) } |
| 543 | |
| 544 | writeByteArray :: MutableByteArray# RealWorld -> Int# -> Word8 -> IO () |
| 545 | |
| 546 | #if __GLASGOW_HASKELL__ < 503 |
| 547 | writeByteArray arr i w8 = IO $ \s -> |
| 548 | case word8ToWord w8 of { W# w# -> |
| 549 | case writeCharArray# arr i (chr# (word2Int# w#)) s of { s -> |
| 550 | (# s , () #) }} |
| 551 | #else |
| 552 | writeByteArray arr i (W8# w) = IO $ \s -> |
| 553 | case writeWord8Array# arr i w s of { s -> |
| 554 | (# s, () #) } |
| 555 | #endif |
| 556 | |
| 557 | #if __GLASGOW_HASKELL__ < 503 |
| 558 | indexByteArray a# n# = fromIntegral (I# (ord# (indexCharArray# a# n#))) |
| 559 | #else |
| 560 | indexByteArray a# n# = W8# (indexWord8Array# a# n#) |
| 561 | #endif |
| 562 | |
| 563 | instance (Integral a, Binary a) => Binary (Ratio a) where |
| 564 | put_ bh (a :% b) = do put_ bh a; put_ bh b |
| 565 | get bh = do a <- get bh; b <- get bh; return (a :% b) |
| 566 | |
| 567 | #else |
| 568 | |
| 569 | instance Binary Integer where |
| 570 | put_ h n = do |
| 571 | put h ((fromIntegral $ signum n) :: Int8) |
| 572 | when (n /= 0) $ do |
| 573 | let n' = abs n |
| 574 | nBytes = byteSize n' |
| 575 | put h (fromIntegral nBytes :: Word64) |
| 576 | mapM_ (putByte h) [ fromIntegral ((n' `shiftR` (b * 8)) .&. 0xff) |
| 577 | | b <- [ nBytes-1, nBytes-2 .. 0 ] ] |
| 578 | where byteSize n = |
| 579 | let f b = if (1 `shiftL` (b * 8)) > n |
| 580 | then b |
| 581 | else f (b + 1) |
| 582 | in f 0 |
| 583 | get h = do |
| 584 | sign :: Int8 <- get h |
| 585 | if sign == 0 |
| 586 | then return 0 |
| 587 | else do |
| 588 | nBytes :: Word64 <- get h |
| 589 | n <- accumBytes nBytes 0 |
| 590 | return $ fromIntegral sign * n |
| 591 | where accumBytes nBytes acc | nBytes == 0 = return acc |
| 592 | | otherwise = do |
| 593 | b <- getByte h |
| 594 | accumBytes (nBytes - 1) ((acc `shiftL` 8) .|. fromIntegral b) |
| 595 | #endif |
| 596 | |
| 597 | #endif |
| 598 | |
| 599 | instance Binary (Bin a) where |
| 600 | put_ bh (BinPtr i) = put_ bh i |
| 601 | get bh = do i <- get bh; return (BinPtr i) |
| 602 | |
| 603 | -- ----------------------------------------------------------------------------- |
| 604 | -- Lazy reading/writing |
| 605 | |
| 606 | lazyPut :: Binary a => BinHandle -> a -> IO () |
| 607 | lazyPut bh a = do |
| 608 | -- output the obj with a ptr to skip over it: |
| 609 | pre_a <- tellBin bh |
| 610 | put_ bh pre_a -- save a slot for the ptr |
| 611 | put_ bh a -- dump the object |
| 612 | q <- tellBin bh -- q = ptr to after object |
| 613 | putAt bh pre_a q -- fill in slot before a with ptr to q |
| 614 | seekBin bh q -- finally carry on writing at q |
| 615 | |
| 616 | lazyGet :: Binary a => BinHandle -> IO a |
| 617 | lazyGet bh = do |
| 618 | p <- get bh -- a BinPtr |
| 619 | p_a <- tellBin bh |
| 620 | a <- unsafeInterleaveIO (getAt bh p_a) |
| 621 | seekBin bh p -- skip over the object for now |
| 622 | return a |
| 623 | |
| 624 | -- -------------------------------------------------------------- |
| 625 | -- Main wrappers: getBinFileWithDict, putBinFileWithDict |
| 626 | -- |
| 627 | -- This layer is built on top of the stuff above, |
| 628 | -- and should not know anything about BinHandles |
| 629 | -- -------------------------------------------------------------- |
| 630 | |
| 631 | initBinMemSize = (1024*1024) :: Int |
| 632 | binaryInterfaceMagic = 0x1face :: Word32 |
| 633 | |
| 634 | getBinFileWithDict :: Binary a => FilePath -> IO a |
| 635 | getBinFileWithDict file_path = do |
| 636 | bh <- Binary.readBinMem file_path |
| 637 | |
| 638 | -- Read the magic number to check that this really is a GHC .hi file |
| 639 | -- (This magic number does not change when we change |
| 640 | -- GHC interface file format) |
| 641 | magic <- get bh |
| 642 | when (magic /= binaryInterfaceMagic) $ |
| 643 | error "magic number mismatch: old/corrupt interface file?" |
| 644 | |
| 645 | -- Read the dictionary |
| 646 | -- The next word in the file is a pointer to where the dictionary is |
| 647 | -- (probably at the end of the file) |
| 648 | dict_p <- Binary.get bh -- Get the dictionary ptr |
| 649 | data_p <- tellBin bh -- Remember where we are now |
| 650 | seekBin bh dict_p |
| 651 | dict <- getDictionary bh |
| 652 | seekBin bh data_p -- Back to where we were before |
| 653 | |
| 654 | -- Initialise the user-data field of bh |
| 655 | let bh' = setUserData bh (initReadState dict) |
| 656 | |
| 657 | -- At last, get the thing |
| 658 | get bh' |
| 659 | |
| 660 | putBinFileWithDict :: Binary a => FilePath -> a -> IO () |
| 661 | putBinFileWithDict file_path the_thing = do |
| 662 | -- hnd <- openBinaryFile file_path WriteMode |
| 663 | -- bh <- openBinIO hnd |
| 664 | bh <- openBinMem initBinMemSize |
| 665 | put_ bh binaryInterfaceMagic |
| 666 | |
| 667 | -- Remember where the dictionary pointer will go |
| 668 | dict_p_p <- tellBin bh |
| 669 | put_ bh dict_p_p -- Placeholder for ptr to dictionary |
| 670 | |
| 671 | -- Make some initial state |
| 672 | usr_state <- newWriteState |
| 673 | |
| 674 | -- Put the main thing, |
| 675 | put_ (setUserData bh usr_state) the_thing |
| 676 | |
| 677 | -- Get the final-state |
| 678 | j <- readIORef (ud_next usr_state) |
| 679 | #if __GLASGOW_HASKELL__>=602 |
| 680 | fm <- HashTable.toList (ud_map usr_state) |
| 681 | #else |
| 682 | fm <- liftM Map.toList $ readIORef (ud_map usr_state) |
| 683 | #endif |
| 684 | dict_p <- tellBin bh -- This is where the dictionary will start |
| 685 | |
| 686 | -- Write the dictionary pointer at the fornt of the file |
| 687 | putAt bh dict_p_p dict_p -- Fill in the placeholder |
| 688 | seekBin bh dict_p -- Seek back to the end of the file |
| 689 | |
| 690 | -- Write the dictionary itself |
| 691 | putDictionary bh j (constructDictionary j fm) |
| 692 | |
| 693 | -- And send the result to the file |
| 694 | writeBinMem bh file_path |
| 695 | -- hClose hnd |
| 696 | |
| 697 | -- ----------------------------------------------------------------------------- |
| 698 | -- UserData |
| 699 | -- ----------------------------------------------------------------------------- |
| 700 | |
| 701 | data UserData = |
| 702 | UserData { -- This field is used only when reading |
| 703 | ud_dict :: Dictionary, |
| 704 | |
| 705 | -- The next two fields are only used when writing |
| 706 | ud_next :: IORef Int, -- The next index to use |
| 707 | #if __GLASGOW_HASKELL__>=602 |
| 708 | # if __GLASGOW_HASKELL__>=707 |
| 709 | ud_map :: BasicHashTable String Int -- The index of each string |
| 710 | # else |
| 711 | ud_map :: HashTable String Int -- The index of each string |
| 712 | # endif |
| 713 | #else |
| 714 | ud_map :: IORef (Map String Int) |
| 715 | #endif |
| 716 | } |
| 717 | |
| 718 | noUserData = error "Binary.UserData: no user data" |
| 719 | |
| 720 | initReadState :: Dictionary -> UserData |
| 721 | initReadState dict = UserData{ ud_dict = dict, |
| 722 | ud_next = undef "next", |
| 723 | ud_map = undef "map" } |
| 724 | |
| 725 | newWriteState :: IO UserData |
| 726 | newWriteState = do |
| 727 | j_r <- newIORef 0 |
| 728 | #if __GLASGOW_HASKELL__>=602 |
| 729 | # if __GLASGOW_HASKELL__>=707 |
| 730 | out_r <- HashTable.new |
| 731 | # else |
| 732 | out_r <- HashTable.new (==) HashTable.hashString |
| 733 | # endif |
| 734 | #else |
| 735 | out_r <- newIORef Map.empty |
| 736 | #endif |
| 737 | return (UserData { ud_dict = error "dict", |
| 738 | ud_next = j_r, |
| 739 | ud_map = out_r }) |
| 740 | |
| 741 | |
| 742 | undef s = error ("Binary.UserData: no " ++ s) |
| 743 | |
| 744 | --------------------------------------------------------- |
| 745 | -- The Dictionary |
| 746 | --------------------------------------------------------- |
| 747 | |
| 748 | type Dictionary = Array Int String -- The dictionary |
| 749 | -- Should be 0-indexed |
| 750 | |
| 751 | putDictionary :: BinHandle -> Int -> Dictionary -> IO () |
| 752 | putDictionary bh sz dict = do |
| 753 | put_ bh sz |
| 754 | mapM_ (put_ bh) (elems dict) |
| 755 | |
| 756 | getDictionary :: BinHandle -> IO Dictionary |
| 757 | getDictionary bh = do |
| 758 | sz <- get bh |
| 759 | elems <- sequence (take sz (repeat (get bh))) |
| 760 | return (listArray (0,sz-1) elems) |
| 761 | |
| 762 | constructDictionary :: Int -> [(String,Int)] -> Dictionary |
| 763 | constructDictionary j fm = array (0,j-1) (map (\(x,y) -> (y,x)) fm) |
| 764 | |
| 765 | --------------------------------------------------------- |
| 766 | -- Reading and writing memoised Strings |
| 767 | --------------------------------------------------------- |
| 768 | |
| 769 | putSharedString :: BinHandle -> String -> IO () |
| 770 | putSharedString bh str = |
| 771 | case getUserData bh of |
| 772 | UserData { ud_next = j_r, ud_map = out_r, ud_dict = dict} -> do |
| 773 | #if __GLASGOW_HASKELL__>=602 |
| 774 | entry <- HashTable.lookup out_r str |
| 775 | #else |
| 776 | fm <- readIORef out_r |
| 777 | let entry = Map.lookup str fm |
| 778 | #endif |
| 779 | case entry of |
| 780 | Just j -> put_ bh j |
| 781 | Nothing -> do |
| 782 | j <- readIORef j_r |
| 783 | put_ bh j |
| 784 | writeIORef j_r (j+1) |
| 785 | #if __GLASGOW_HASKELL__>=602 |
| 786 | HashTable.insert out_r str j |
| 787 | #else |
| 788 | modifyIORef out_r (\fm -> Map.insert str j fm) |
| 789 | #endif |
| 790 | |
| 791 | getSharedString :: BinHandle -> IO String |
| 792 | getSharedString bh = do |
| 793 | j <- get bh |
| 794 | return $! (ud_dict (getUserData bh) ! j) |
| 795 | |
| 796 | {- |
| 797 | --------------------------------------------------------- |
| 798 | -- Reading and writing FastStrings |
| 799 | --------------------------------------------------------- |
| 800 | |
| 801 | putFS bh (FastString id l ba) = do |
| 802 | put_ bh (I# l) |
| 803 | putByteArray bh ba l |
| 804 | putFS bh s = error ("Binary.put_(FastString): " ++ unpackFS s) |
| 805 | -- Note: the length of the FastString is *not* the same as |
| 806 | -- the size of the ByteArray: the latter is rounded up to a |
| 807 | -- multiple of the word size. |
| 808 | |
| 809 | {- -- possible faster version, not quite there yet: |
| 810 | getFS bh@BinMem{} = do |
| 811 | (I# l) <- get bh |
| 812 | arr <- readIORef (arr_r bh) |
| 813 | off <- readFastMutInt (off_r bh) |
| 814 | return $! (mkFastSubStringBA# arr off l) |
| 815 | -} |
| 816 | getFS bh = do |
| 817 | (I# l) <- get bh |
| 818 | (BA ba) <- getByteArray bh (I# l) |
| 819 | return $! (mkFastSubStringBA# ba 0# l) |
| 820 | |
| 821 | instance Binary FastString where |
| 822 | put_ bh f@(FastString id l ba) = |
| 823 | case getUserData bh of { |
| 824 | UserData { ud_next = j_r, ud_map = out_r, ud_dict = dict} -> do |
| 825 | out <- readIORef out_r |
| 826 | let uniq = getUnique f |
| 827 | case lookupUFM out uniq of |
| 828 | Just (j,f) -> put_ bh j |
| 829 | Nothing -> do |
| 830 | j <- readIORef j_r |
| 831 | put_ bh j |
| 832 | writeIORef j_r (j+1) |
| 833 | writeIORef out_r (addToUFM out uniq (j,f)) |
| 834 | } |
| 835 | put_ bh s = error ("Binary.put_(FastString): " ++ show (unpackFS s)) |
| 836 | |
| 837 | get bh = do |
| 838 | j <- get bh |
| 839 | return $! (ud_dict (getUserData bh) ! j) |
| 840 | -} |
| 841 | |
| 842 | printElapsedTime :: String -> IO () |
| 843 | printElapsedTime msg = do |
| 844 | time <- getCPUTime |
| 845 | hPutStr stderr $ "elapsed time: " ++ Numeric.showFFloat (Just 2) ((fromIntegral time) / 10^12) " (" ++ msg ++ ")\n" |
| 846 |