56e647f3cffb6c05834155a24318dc05d9f326e2
[darcs-mirrors/vector.git] / Data / Vector / Unboxed / Mutable.hs
1 {-# LANGUAGE MagicHash, UnboxedTuples, MultiParamTypeClasses, FlexibleInstances, ScopedTypeVariables #-}
2
3 -- |
4 -- Module : Data.Vector.Unboxed.Mutable
5 -- Copyright : (c) Roman Leshchinskiy 2008
6 -- License : BSD-style
7 --
8 -- Maintainer : rl@cse.unsw.edu.au
9 -- Stability : experimental
10 -- Portability : non-portable
11 --
12 -- Mutable unboxed vectors based on 'Unbox'.
13 --
14
15 module Data.Vector.Unboxed.Mutable ( Vector(..) )
16 where
17
18 import qualified Data.Vector.MVector as MVector
19 import Data.Vector.MVector ( MVector, MVectorPure )
20 import Data.Vector.Unboxed.Unbox
21
22 import GHC.Prim ( MutableByteArray#,
23 newByteArray#, sameMutableByteArray#, (+#) )
24
25 import GHC.ST ( ST(..) )
26
27 import GHC.Base ( Int(..) )
28
29 -- | Mutable unboxed vectors. They live in the 'ST' monad.
30 data Vector s a = Vector {-# UNPACK #-} !Int
31 {-# UNPACK #-} !Int
32 (MutableByteArray# s)
33
34 instance Unbox a => MVectorPure (Vector s) a where
35 length (Vector _ n _) = n
36 unsafeSlice (Vector i _ arr#) j m = Vector (i+j) m arr#
37
38 {-# INLINE overlaps #-}
39 overlaps (Vector i m arr1#) (Vector j n arr2#)
40 = sameMutableByteArray# arr1# arr2#
41 && (between i j (j+n) || between j i (i+m))
42 where
43 between x y z = x >= y && x < z
44
45
46 instance Unbox a => MVector (Vector s) (ST s) a where
47 {-# INLINE unsafeNew #-}
48 unsafeNew (I# n#) = ST (\s# ->
49 case newByteArray# (size# (undefined :: a) n#) s# of
50 (# s2#, arr# #) -> (# s2#, Vector 0 (I# n#) arr# #)
51 )
52
53 {-# INLINE unsafeRead #-}
54 unsafeRead (Vector (I# i#) _ arr#) (I# j#) = ST (read# arr# (i# +# j#))
55
56 {-# INLINE unsafeWrite #-}
57 unsafeWrite (Vector (I# i#) _ arr#) (I# j#) x = ST (\s# ->
58 case write# arr# (i# +# j#) x s# of s2# -> (# s2#, () #)
59 )
60
61