3 -- (c) The University of Glasgow 2002
5 -- Binary I/O library, with special tweaks for GHC
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/
18 openBinIO, openBinIO_,
31 -- for writing instances:
44 getBinFileWithDict, -- :: Binary a => FilePath -> IO a
45 putBinFileWithDict, -- :: Binary a => FilePath -> ModuleName -> a -> IO ()
49 #include "HsVersions.h"
51 -- The *host* architecture version:
60 #if __GLASGOW_HASKELL__ < 503
68 import GlaExts hiding (ByteArray, newByteArray, freezeByteArray)
71 import PrelIOBase ( IOError(..), IOErrorType(..)
72 #if __GLASGOW_HASKELL__ > 411
76 import PrelReal ( Ratio(..) )
77 import PrelIOBase ( IO(..) )
78 import IOExts ( openFileEx, IOModeEx(..) )
86 import Data.Char ( ord, chr )
87 import Data.Array.Base ( unsafeRead, unsafeWrite )
88 import Control.Monad ( when )
89 import Control.Exception ( throwDyn )
90 import System.IO as IO
91 import System.IO.Unsafe ( unsafeInterleaveIO )
92 import System.IO.Error ( mkIOError, eofErrorType )
93 import GHC.Real ( Ratio(..) )
95 import GHC.IOBase ( IO(..) )
96 import GHC.Word ( Word8(..) )
97 #if __GLASGOW_HASKELL__ < 601
98 -- openFileEx is available from the lang package, but we want to
99 -- be independent of hslibs libraries.
100 import GHC.Handle ( openFileEx, IOModeEx(..) )
102 import System.IO ( openBinaryFile )
106 #if __GLASGOW_HASKELL__ < 601
107 openBinaryFile f mode = openFileEx f (BinaryMode mode)
110 #if __GLASGOW_HASKELL__ < 503
111 type BinArray = MutableByteArray RealWorld Int
112 newArray_ bounds = stToIO (newCharArray bounds)
113 unsafeWrite arr ix e = stToIO (writeWord8Array arr ix e)
114 unsafeRead arr ix = stToIO (readWord8Array arr ix)
115 #if __GLASGOW_HASKELL__ < 411
116 newByteArray# = newCharArray#
118 hPutArray h arr sz = hPutBufBAFull h arr sz
119 hGetArray h sz = hGetBufBAFull h sz
121 mkIOError :: IOErrorType -> String -> Maybe Handle -> Maybe FilePath -> Exception
122 mkIOError t location maybe_hdl maybe_filename
123 = IOException (IOError maybe_hdl t location ""
124 #if __GLASGOW_HASKELL__ > 411
132 #define SIZEOF_HSINT INT_SIZE_IN_BYTES
135 #ifndef SIZEOF_HSWORD
136 #define SIZEOF_HSWORD WORD_SIZE_IN_BYTES
140 type BinArray = IOUArray Int Word8
143 ---------------------------------------------------------------
145 ---------------------------------------------------------------
148 = BinMem { -- binary data stored in an unboxed array
149 bh_usr :: UserData, -- sigh, need parameterized modules :-)
150 off_r :: !FastMutInt, -- the current offset
151 sz_r :: !FastMutInt, -- size of the array (cached)
152 arr_r :: !(IORef BinArray) -- the array (bounds: (0,size-1))
154 -- XXX: should really store a "high water mark" for dumping out
155 -- the binary data to a file.
157 | BinIO { -- binary data stored in a file
159 off_r :: !FastMutInt, -- the current offset (cached)
160 hdl :: !IO.Handle -- the file handle (must be seekable)
162 -- cache the file ptr in BinIO; using hTell is too expensive
163 -- to call repeatedly. If anyone else is modifying this Handle
164 -- at the same time, we'll be screwed.
166 getUserData :: BinHandle -> UserData
167 getUserData bh = bh_usr bh
169 setUserData :: BinHandle -> UserData -> BinHandle
170 setUserData bh us = bh { bh_usr = us }
173 ---------------------------------------------------------------
175 ---------------------------------------------------------------
177 newtype Bin a = BinPtr Int
178 deriving (Eq, Ord, Show, Bounded)
180 castBin :: Bin a -> Bin b
181 castBin (BinPtr i) = BinPtr i
183 ---------------------------------------------------------------
185 ---------------------------------------------------------------
188 put_ :: BinHandle -> a -> IO ()
189 put :: BinHandle -> a -> IO (Bin a)
190 get :: BinHandle -> IO a
192 -- define one of put_, put. Use of put_ is recommended because it
193 -- is more likely that tail-calls can kick in, and we rarely need the
194 -- position return value.
195 put_ bh a = do put bh a; return ()
196 put bh a = do p <- tellBin bh; put_ bh a; return p
198 putAt :: Binary a => BinHandle -> Bin a -> a -> IO ()
199 putAt bh p x = do seekBin bh p; put bh x; return ()
201 getAt :: Binary a => BinHandle -> Bin a -> IO a
202 getAt bh p = do seekBin bh p; get bh
204 openBinIO_ :: IO.Handle -> IO BinHandle
205 openBinIO_ h = openBinIO h
207 openBinIO :: IO.Handle -> IO BinHandle
211 return (BinIO noUserData r h)
213 openBinMem :: Int -> IO BinHandle
215 | size <= 0 = error "Data.Binary.openBinMem: size must be >= 0"
217 arr <- newArray_ (0,size-1)
218 arr_r <- newIORef arr
219 ix_r <- newFastMutInt
220 writeFastMutInt ix_r 0
221 sz_r <- newFastMutInt
222 writeFastMutInt sz_r size
223 return (BinMem noUserData ix_r sz_r arr_r)
225 tellBin :: BinHandle -> IO (Bin a)
226 tellBin (BinIO _ r _) = do ix <- readFastMutInt r; return (BinPtr ix)
227 tellBin (BinMem _ r _ _) = do ix <- readFastMutInt r; return (BinPtr ix)
229 seekBin :: BinHandle -> Bin a -> IO ()
230 seekBin (BinIO _ ix_r h) (BinPtr p) = do
231 writeFastMutInt ix_r p
232 hSeek h AbsoluteSeek (fromIntegral p)
233 seekBin h@(BinMem _ ix_r sz_r a) (BinPtr p) = do
234 sz <- readFastMutInt sz_r
236 then do expandBin h p; writeFastMutInt ix_r p
237 else writeFastMutInt ix_r p
239 isEOFBin :: BinHandle -> IO Bool
240 isEOFBin (BinMem _ ix_r sz_r a) = do
241 ix <- readFastMutInt ix_r
242 sz <- readFastMutInt sz_r
244 isEOFBin (BinIO _ ix_r h) = hIsEOF h
246 writeBinMem :: BinHandle -> FilePath -> IO ()
247 writeBinMem (BinIO _ _ _) _ = error "Data.Binary.writeBinMem: not a memory handle"
248 writeBinMem (BinMem _ ix_r sz_r arr_r) fn = do
249 h <- openBinaryFile fn WriteMode
250 arr <- readIORef arr_r
251 ix <- readFastMutInt ix_r
253 #if __GLASGOW_HASKELL__ <= 500
254 -- workaround a bug in old implementation of hPutBuf (it doesn't
255 -- set the FILEOBJ_RW_WRITTEN flag on the file object, so the file doens't
256 -- get flushed properly). Adding an extra '\0' doens't do any harm.
261 readBinMem :: FilePath -> IO BinHandle
262 -- Return a BinHandle with a totally undefined State
263 readBinMem filename = do
264 h <- openBinaryFile filename ReadMode
265 filesize' <- hFileSize h
266 let filesize = fromIntegral filesize'
267 arr <- newArray_ (0,filesize-1)
268 count <- hGetArray h arr filesize
269 when (count /= filesize)
270 (error ("Binary.readBinMem: only read " ++ show count ++ " bytes"))
272 arr_r <- newIORef arr
273 ix_r <- newFastMutInt
274 writeFastMutInt ix_r 0
275 sz_r <- newFastMutInt
276 writeFastMutInt sz_r filesize
277 return (BinMem noUserData ix_r sz_r arr_r)
279 -- expand the size of the array to include a specified offset
280 expandBin :: BinHandle -> Int -> IO ()
281 expandBin (BinMem _ ix_r sz_r arr_r) off = do
282 sz <- readFastMutInt sz_r
283 let sz' = head (dropWhile (<= off) (iterate (* 2) sz))
284 arr <- readIORef arr_r
285 arr' <- newArray_ (0,sz'-1)
286 sequence_ [ unsafeRead arr i >>= unsafeWrite arr' i
287 | i <- [ 0 .. sz-1 ] ]
288 writeFastMutInt sz_r sz'
289 writeIORef arr_r arr'
291 hPutStrLn stderr ("Binary: expanding to size: " ++ show sz')
294 expandBin (BinIO _ _ _) _ = return ()
295 -- no need to expand a file, we'll assume they expand by themselves.
297 -- -----------------------------------------------------------------------------
298 -- Low-level reading/writing of bytes
300 putWord8 :: BinHandle -> Word8 -> IO ()
301 putWord8 h@(BinMem _ ix_r sz_r arr_r) w = do
302 ix <- readFastMutInt ix_r
303 sz <- readFastMutInt sz_r
304 -- double the size of the array if it overflows
306 then do expandBin h ix
308 else do arr <- readIORef arr_r
310 writeFastMutInt ix_r (ix+1)
312 putWord8 (BinIO _ ix_r h) w = do
313 ix <- readFastMutInt ix_r
314 hPutChar h (chr (fromIntegral w)) -- XXX not really correct
315 writeFastMutInt ix_r (ix+1)
318 getWord8 :: BinHandle -> IO Word8
319 getWord8 (BinMem _ ix_r sz_r arr_r) = do
320 ix <- readFastMutInt ix_r
321 sz <- readFastMutInt sz_r
323 #if __GLASGOW_HASKELL__ <= 408
324 throw (mkIOError eofErrorType "Data.Binary.getWord8" Nothing Nothing)
326 ioError (mkIOError eofErrorType "Data.Binary.getWord8" Nothing Nothing)
328 arr <- readIORef arr_r
329 w <- unsafeRead arr ix
330 writeFastMutInt ix_r (ix+1)
332 getWord8 (BinIO _ ix_r h) = do
333 ix <- readFastMutInt ix_r
335 writeFastMutInt ix_r (ix+1)
336 return $! (fromIntegral (ord c)) -- XXX not really correct
338 putByte :: BinHandle -> Word8 -> IO ()
339 putByte bh w = put_ bh w
341 getByte :: BinHandle -> IO Word8
344 -- -----------------------------------------------------------------------------
345 -- Primitve Word writes
347 instance Binary Word8 where
351 instance Binary Word16 where
352 put_ h w = do -- XXX too slow.. inline putWord8?
353 putByte h (fromIntegral (w `shiftR` 8))
354 putByte h (fromIntegral (w .&. 0xff))
358 return $! ((fromIntegral w1 `shiftL` 8) .|. fromIntegral w2)
361 instance Binary Word32 where
363 putByte h (fromIntegral (w `shiftR` 24))
364 putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff))
365 putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff))
366 putByte h (fromIntegral (w .&. 0xff))
372 return $! ((fromIntegral w1 `shiftL` 24) .|.
373 (fromIntegral w2 `shiftL` 16) .|.
374 (fromIntegral w3 `shiftL` 8) .|.
378 instance Binary Word64 where
380 putByte h (fromIntegral (w `shiftR` 56))
381 putByte h (fromIntegral ((w `shiftR` 48) .&. 0xff))
382 putByte h (fromIntegral ((w `shiftR` 40) .&. 0xff))
383 putByte h (fromIntegral ((w `shiftR` 32) .&. 0xff))
384 putByte h (fromIntegral ((w `shiftR` 24) .&. 0xff))
385 putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff))
386 putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff))
387 putByte h (fromIntegral (w .&. 0xff))
397 return $! ((fromIntegral w1 `shiftL` 56) .|.
398 (fromIntegral w2 `shiftL` 48) .|.
399 (fromIntegral w3 `shiftL` 40) .|.
400 (fromIntegral w4 `shiftL` 32) .|.
401 (fromIntegral w5 `shiftL` 24) .|.
402 (fromIntegral w6 `shiftL` 16) .|.
403 (fromIntegral w7 `shiftL` 8) .|.
406 -- -----------------------------------------------------------------------------
407 -- Primitve Int writes
409 instance Binary Int8 where
410 put_ h w = put_ h (fromIntegral w :: Word8)
411 get h = do w <- get h; return $! (fromIntegral (w::Word8))
413 instance Binary Int16 where
414 put_ h w = put_ h (fromIntegral w :: Word16)
415 get h = do w <- get h; return $! (fromIntegral (w::Word16))
417 instance Binary Int32 where
418 put_ h w = put_ h (fromIntegral w :: Word32)
419 get h = do w <- get h; return $! (fromIntegral (w::Word32))
421 instance Binary Int64 where
422 put_ h w = put_ h (fromIntegral w :: Word64)
423 get h = do w <- get h; return $! (fromIntegral (w::Word64))
425 -- -----------------------------------------------------------------------------
426 -- Instances for standard types
428 instance Binary () where
429 put_ bh () = return ()
431 -- getF bh p = case getBitsF bh 0 p of (_,b) -> ((),b)
433 instance Binary Bool where
434 put_ bh b = putByte bh (fromIntegral (fromEnum b))
435 get bh = do x <- getWord8 bh; return $! (toEnum (fromIntegral x))
436 -- getF bh p = case getBitsF bh 1 p of (x,b) -> (toEnum x,b)
438 instance Binary Char where
439 put_ bh c = put_ bh (fromIntegral (ord c) :: Word32)
440 get bh = do x <- get bh; return $! (chr (fromIntegral (x :: Word32)))
441 -- getF bh p = case getBitsF bh 8 p of (x,b) -> (toEnum x,b)
443 instance Binary Int where
444 #if SIZEOF_HSINT == 4
445 put_ bh i = put_ bh (fromIntegral i :: Int32)
448 return $! (fromIntegral (x :: Int32))
449 #elif SIZEOF_HSINT == 8
450 put_ bh i = put_ bh (fromIntegral i :: Int64)
453 return $! (fromIntegral (x :: Int64))
455 #error "unsupported sizeof(HsInt)"
457 -- getF bh = getBitsF bh 32
459 instance Binary a => Binary [a] where
460 put_ bh [] = putByte bh 0
461 put_ bh (x:xs) = do putByte bh 1; put_ bh x; put_ bh xs
462 get bh = do h <- getWord8 bh
469 instance (Binary a, Binary b) => Binary (a,b) where
470 put_ bh (a,b) = do put_ bh a; put_ bh b
471 get bh = do a <- get bh
475 instance (Binary a, Binary b, Binary c) => Binary (a,b,c) where
476 put_ bh (a,b,c) = do put_ bh a; put_ bh b; put_ bh c
477 get bh = do a <- get bh
482 instance (Binary a, Binary b, Binary c, Binary d) => Binary (a,b,c,d) where
483 put_ bh (a,b,c,d) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d
484 get bh = do a <- get bh
490 instance Binary a => Binary (Maybe a) where
491 put_ bh Nothing = putByte bh 0
492 put_ bh (Just a) = do putByte bh 1; put_ bh a
493 get bh = do h <- getWord8 bh
496 _ -> do x <- get bh; return (Just x)
498 instance (Binary a, Binary b) => Binary (Either a b) where
499 put_ bh (Left a) = do putByte bh 0; put_ bh a
500 put_ bh (Right b) = do putByte bh 1; put_ bh b
501 get bh = do h <- getWord8 bh
503 0 -> do a <- get bh ; return (Left a)
504 _ -> do b <- get bh ; return (Right b)
506 #ifdef __GLASGOW_HASKELL__
507 instance Binary Integer where
508 put_ bh (S# i#) = do putByte bh 0; put_ bh (I# i#)
509 put_ bh (J# s# a#) = do
512 let sz# = sizeofByteArray# a# -- in *bytes*
513 put_ bh (I# sz#) -- in *bytes*
514 putByteArray bh a# sz#
519 0 -> do (I# i#) <- get bh
521 _ -> do (I# s#) <- get bh
523 (BA a#) <- getByteArray bh sz
526 putByteArray :: BinHandle -> ByteArray# -> Int# -> IO ()
527 putByteArray bh a s# = loop 0#
529 | n# ==# s# = return ()
531 putByte bh (indexByteArray a n#)
534 getByteArray :: BinHandle -> Int -> IO ByteArray
535 getByteArray bh (I# sz) = do
536 (MBA arr) <- newByteArray sz
538 | n ==# sz = return ()
541 writeByteArray arr n w
547 data ByteArray = BA ByteArray#
548 data MBA = MBA (MutableByteArray# RealWorld)
550 newByteArray :: Int# -> IO MBA
551 newByteArray sz = IO $ \s ->
552 case newByteArray# sz s of { (# s, arr #) ->
555 freezeByteArray :: MutableByteArray# RealWorld -> IO ByteArray
556 freezeByteArray arr = IO $ \s ->
557 case unsafeFreezeByteArray# arr s of { (# s, arr #) ->
560 writeByteArray :: MutableByteArray# RealWorld -> Int# -> Word8 -> IO ()
562 #if __GLASGOW_HASKELL__ < 503
563 writeByteArray arr i w8 = IO $ \s ->
564 case word8ToWord w8 of { W# w# ->
565 case writeCharArray# arr i (chr# (word2Int# w#)) s of { s ->
568 writeByteArray arr i (W8# w) = IO $ \s ->
569 case writeWord8Array# arr i w s of { s ->
573 #if __GLASGOW_HASKELL__ < 503
574 indexByteArray a# n# = fromIntegral (I# (ord# (indexCharArray# a# n#)))
576 indexByteArray a# n# = W8# (indexWord8Array# a# n#)
579 instance (Integral a, Binary a) => Binary (Ratio a) where
580 put_ bh (a :% b) = do put_ bh a; put_ bh b
581 get bh = do a <- get bh; b <- get bh; return (a :% b)
584 instance Binary (Bin a) where
585 put_ bh (BinPtr i) = put_ bh i
586 get bh = do i <- get bh; return (BinPtr i)
588 -- -----------------------------------------------------------------------------
589 -- Lazy reading/writing
591 lazyPut :: Binary a => BinHandle -> a -> IO ()
593 -- output the obj with a ptr to skip over it:
595 put_ bh pre_a -- save a slot for the ptr
596 put_ bh a -- dump the object
597 q <- tellBin bh -- q = ptr to after object
598 putAt bh pre_a q -- fill in slot before a with ptr to q
599 seekBin bh q -- finally carry on writing at q
601 lazyGet :: Binary a => BinHandle -> IO a
603 p <- get bh -- a BinPtr
605 a <- unsafeInterleaveIO (getAt bh p_a)
606 seekBin bh p -- skip over the object for now
609 -- --------------------------------------------------------------
610 -- Main wrappers: getBinFileWithDict, putBinFileWithDict
612 -- This layer is built on top of the stuff above,
613 -- and should not know anything about BinHandles
614 -- --------------------------------------------------------------
616 initBinMemSize = (1024*1024) :: Int
617 binaryInterfaceMagic = 0x1face :: Word32
619 getBinFileWithDict :: Binary a => FilePath -> IO a
620 getBinFileWithDict file_path = do
621 bh <- Binary.readBinMem file_path
623 -- Read the magic number to check that this really is a GHC .hi file
624 -- (This magic number does not change when we change
625 -- GHC interface file format)
627 when (magic /= binaryInterfaceMagic) $
628 throwDyn (ProgramError (
629 "magic number mismatch: old/corrupt interface file?"))
631 -- Read the dictionary
632 -- The next word in the file is a pointer to where the dictionary is
633 -- (probably at the end of the file)
634 dict_p <- Binary.get bh -- Get the dictionary ptr
635 data_p <- tellBin bh -- Remember where we are now
637 dict <- getDictionary bh
638 seekBin bh data_p -- Back to where we were before
640 -- Initialise the user-data field of bh
641 let bh' = setUserData bh (initReadState dict)
643 -- At last, get the thing
646 putBinFileWithDict :: Binary a => FilePath -> a -> IO ()
647 putBinFileWithDict file_path the_thing = do
648 bh <- openBinMem initBinMemSize
649 put_ bh binaryInterfaceMagic
651 -- Remember where the dictionary pointer will go
652 dict_p_p <- tellBin bh
653 put_ bh dict_p_p -- Placeholder for ptr to dictionary
655 -- Make some intial state
656 usr_state <- newWriteState
658 -- Put the main thing,
659 put_ (setUserData bh usr_state) the_thing
661 -- Get the final-state
662 j <- readIORef (ud_next usr_state)
663 fm <- readIORef (ud_map usr_state)
664 dict_p <- tellBin bh -- This is where the dictionary will start
666 -- Write the dictionary pointer at the fornt of the file
667 putAt bh dict_p_p dict_p -- Fill in the placeholder
668 seekBin bh dict_p -- Seek back to the end of the file
670 -- Write the dictionary itself
671 putDictionary bh j (constructDictionary j fm)
673 -- And send the result to the file
674 writeBinMem bh file_path
676 -- -----------------------------------------------------------------------------
678 -- -----------------------------------------------------------------------------
681 UserData { -- This field is used only when reading
682 ud_dict :: Dictionary,
684 -- The next two fields are only used when writing
685 ud_next :: IORef Int, -- The next index to use
686 ud_map :: IORef (UniqFM (Int,FastString))
689 noUserData = error "Binary.UserData: no user data"
691 initReadState :: Dictionary -> UserData
692 initReadState dict = UserData{ ud_dict = dict,
693 ud_next = undef "next",
694 ud_map = undef "map" }
696 newWriteState :: IO UserData
699 out_r <- newIORef emptyUFM
700 return (UserData { ud_dict = panic "dict",
705 undef s = panic ("Binary.UserData: no " ++ s)
707 ---------------------------------------------------------
709 ---------------------------------------------------------
711 type Dictionary = Array Int FastString -- The dictionary
712 -- Should be 0-indexed
714 putDictionary :: BinHandle -> Int -> Dictionary -> IO ()
715 putDictionary bh sz dict = do
717 mapM_ (putFS bh) (elems dict)
719 getDictionary :: BinHandle -> IO Dictionary
720 getDictionary bh = do
722 elems <- sequence (take sz (repeat (getFS bh)))
723 return (listArray (0,sz-1) elems)
725 constructDictionary :: Int -> UniqFM (Int,FastString) -> Dictionary
726 constructDictionary j fm = array (0,j-1) (eltsUFM fm)
728 ---------------------------------------------------------
729 -- Reading and writing FastStrings
730 ---------------------------------------------------------
732 putFS bh (FastString id l ba) = do
735 putFS bh s = error ("Binary.put_(FastString): " ++ unpackFS s)
736 -- Note: the length of the FastString is *not* the same as
737 -- the size of the ByteArray: the latter is rounded up to a
738 -- multiple of the word size.
740 {- -- possible faster version, not quite there yet:
741 getFS bh@BinMem{} = do
743 arr <- readIORef (arr_r bh)
744 off <- readFastMutInt (off_r bh)
745 return $! (mkFastSubStringBA# arr off l)
749 (BA ba) <- getByteArray bh (I# l)
750 return $! (mkFastSubStringBA# ba 0# l)
752 instance Binary FastString where
753 put_ bh f@(FastString id l ba) =
754 case getUserData bh of {
755 UserData { ud_next = j_r, ud_map = out_r, ud_dict = dict} -> do
756 out <- readIORef out_r
757 let uniq = getUnique f
758 case lookupUFM out uniq of
759 Just (j,f) -> put_ bh j
764 writeIORef out_r (addToUFM out uniq (j,f))
766 put_ bh s = error ("Binary.put_(FastString): " ++ show (unpackFS s))
770 return $! (ud_dict (getUserData bh) ! j)