[project @ 1999-11-26 16:26:32 by simonmar]
[ghc-hetmet.git] / ghc / lib / exts / ByteArray.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1997
3 %
4 \section[ByteArray]{The @ByteArray@ interface}
5
6 Immutable, read-only chunks of bytes, the @ByteArray@ collects
7 together the definitions in @ArrBase@ and exports them as one.
8
9 \begin{code}
10 module ByteArray
11        (
12         ByteArray(..),  -- not abstract, for now. Instance of : CCallable, Eq.
13         Ix,
14
15         newByteArray,         -- :: Ix ix => (ix,ix) -> ST s (ByteArray ix)
16
17         --Indexing of ordinary @Arrays@ is standard Haskell and isn't defined here.
18         indexCharArray,       -- :: Ix ix => ByteArray ix -> ix -> Char 
19         indexIntArray,        -- :: Ix ix => ByteArray ix -> ix -> Int
20         indexWordArray,       -- :: Ix ix => ByteArray ix -> ix -> Word
21         indexAddrArray,       -- :: Ix ix => ByteArray ix -> ix -> Addr
22         indexFloatArray,      -- :: Ix ix => ByteArray ix -> ix -> Float
23         indexDoubleArray,     -- :: Ix ix => ByteArray ix -> ix -> Double
24         indexStablePtrArray,  -- :: Ix ix => ByteArray ix -> ix -> (StablePtr a)
25
26         sizeofByteArray,      -- :: Ix ix => ByteArray ix -> Int
27         boundsOfByteArray     -- :: Ix ix => ByteArray ix -> (ix, ix)
28  
29        ) where
30
31 import PrelArr
32 import PrelBase
33 import PrelStable( StablePtr(..) )
34 import PrelST
35 import Ix
36 \end{code}
37
38 \begin{code}
39 indexStablePtrArray    :: Ix ix => ByteArray ix -> ix -> (StablePtr a)
40 indexStablePtrArray (ByteArray l u barr#) n
41   = case (index (l,u) n)                of { I# n# ->
42     case indexStablePtrArray# barr# n#  of { r# ->
43     (StablePtr r#)}}
44 \end{code}
45
46 The size returned is in bytes.
47
48 \begin{code}
49 sizeofByteArray :: Ix ix => ByteArray ix -> Int
50 sizeofByteArray (ByteArray _ _ arr#) = 
51   case (sizeofByteArray# arr#) of
52     i# -> (I# i#)
53
54 boundsOfByteArray :: Ix ix => ByteArray ix -> (ix, ix)
55 boundsOfByteArray (ByteArray     l u _) = (l,u)
56 \end{code}
57
58 \begin{code}
59 newByteArray :: Ix ix => (ix,ix) -> ST s (ByteArray ix)
60 newByteArray ixs = do
61    m_arr <- newCharArray ixs
62    unsafeFreezeByteArray m_arr
63 \end{code}
64
65 If it should turn out to be an issue, could probably be speeded
66 up quite a bit.
67
68 \begin{code}
69 instance Ix ix => Eq (ByteArray ix) where
70    b1 == b2 = eqByteArray b1 b2
71
72 eqByteArray :: Ix ix => ByteArray ix -> ByteArray ix -> Bool
73 eqByteArray b1 b2 =
74   sizeofByteArray b1 == sizeofByteArray b2 &&
75   all (\ x -> indexCharArray b1 x == indexCharArray b2 x) (range (boundsOfByteArray b1))
76 \end{code}