[project @ 2000-04-10 16:02:58 by simonpj]
[ghc-hetmet.git] / ghc / lib / std / PrelArrExtra.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1996
3 %
4 \section[PrelArrExtra]{Module @PrelArrExtra@}
5
6 The following functions should be in PrelArr, but need -monly-2-regs
7 to compile.  So as not to compile the whole of PrelArr with
8 -monly-2-regs, the culprits have been moved out into a separate
9 module.
10
11 \begin{code}
12 {-# OPTIONS -fcompiling-prelude -fno-implicit-prelude #-}
13
14 module PrelArrExtra where
15
16 import PrelArr
17 import PrelByteArr
18 import PrelST
19 import PrelIOBase
20 import PrelBase
21 import PrelGHC
22 \end{code}
23
24 %*********************************************************
25 %*                                                      *
26 \subsection{Moving between mutable and immutable}
27 %*                                                      *
28 %*********************************************************
29
30 \begin{code}
31 freezeByteArray   :: Ix ix => MutableByteArray s ix -> ST s (ByteArray ix)
32
33 {-# SPECIALISE freezeByteArray :: MutableByteArray s Int -> ST s (ByteArray Int) #-}
34
35 -- This coercion of memcpy to the ST monad is safe, because memcpy
36 -- only modifies its destination operand, which is already MutableByteArray.
37 freezeByteArray (MutableByteArray l u arr) = ST $ \ s ->
38         let n = sizeofMutableByteArray# arr in
39         case (newCharArray# n s)                   of { (# s, newarr #) -> 
40         case ((unsafeCoerce# memcpy) newarr arr n s) of { (# s, () #) ->
41         case unsafeFreezeByteArray# newarr s       of { (# s, frozen #) ->
42         (# s, ByteArray l u frozen #) }}}
43
44 foreign import "memcpy" unsafe 
45   memcpy :: MutableByteArray# RealWorld -> ByteArray# -> Int# -> IO ()
46
47 unsafeFreezeByteArray :: Ix ix => MutableByteArray s ix -> ST s (ByteArray ix)
48
49 {-# SPECIALIZE unsafeFreezeByteArray :: MutableByteArray s Int -> ST s (ByteArray Int)
50   #-}
51
52 unsafeFreezeByteArray (MutableByteArray l u arr#) = ST $ \ s# ->
53     case unsafeFreezeByteArray# arr# s# of { (# s2#, frozen# #) ->
54     (# s2#, ByteArray l u frozen# #) }
55 \end{code}