[project @ 2000-03-28 08:52:28 by simonmar]
[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 -fno-implicit-prelude #-}
13
14 module PrelArrExtra where
15
16 import Ix
17 import PrelArr
18 import PrelByteArr
19 import PrelST
20 import PrelIOBase
21 import PrelBase
22 import PrelGHC
23 \end{code}
24
25 %*********************************************************
26 %*                                                      *
27 \subsection{Moving between mutable and immutable}
28 %*                                                      *
29 %*********************************************************
30
31 \begin{code}
32 freezeByteArray   :: Ix ix => MutableByteArray s ix -> ST s (ByteArray ix)
33
34 {-# SPECIALISE freezeByteArray :: MutableByteArray s Int -> ST s (ByteArray Int) #-}
35
36 -- This coercion of memcpy to the ST monad is safe, because memcpy
37 -- only modifies its destination operand, which is already MutableByteArray.
38 freezeByteArray (MutableByteArray l u arr) = ST $ \ s ->
39         let n = sizeofMutableByteArray# arr in
40         case (newCharArray# n s)                   of { (# s, newarr #) -> 
41         case ((unsafeCoerce# memcpy) newarr arr n s) of { (# s, () #) ->
42         case unsafeFreezeByteArray# newarr s       of { (# s, frozen #) ->
43         (# s, ByteArray l u frozen #) }}}
44
45 foreign import "memcpy" unsafe 
46   memcpy :: MutableByteArray# RealWorld -> ByteArray# -> Int# -> IO ()
47
48 unsafeFreezeByteArray :: Ix ix => MutableByteArray s ix -> ST s (ByteArray ix)
49
50 {-# SPECIALIZE unsafeFreezeByteArray :: MutableByteArray s Int -> ST s (ByteArray Int)
51   #-}
52
53 unsafeFreezeByteArray (MutableByteArray l u arr#) = ST $ \ s# ->
54     case unsafeFreezeByteArray# arr# s# of { (# s2#, frozen# #) ->
55     (# s2#, ByteArray l u frozen# #) }
56 \end{code}