Replace type families by GADTs for associating a monad with a mutable vector
[darcs-mirrors/vector.git] / Data / Vector / Unboxed / Mutable.hs
1 {-# LANGUAGE MagicHash, UnboxedTuples, MultiParamTypeClasses, FlexibleInstances, GADTs, ScopedTypeVariables #-}
2
3 module Data.Vector.Unboxed.Mutable ( Vector(..) )
4 where
5
6 import qualified Data.Vector.Base.Mutable as Base
7 import Data.Vector.Unboxed.Unbox
8
9 import GHC.Prim ( MutableByteArray#,
10 newByteArray#, sameMutableByteArray#, (+#) )
11
12 import GHC.ST ( ST(..) )
13
14 import GHC.Base ( Int(..) )
15
16 data Vector m a where
17 Vector :: {-# UNPACK #-} !Int
18 -> {-# UNPACK #-} !Int
19 -> MutableByteArray# s
20 -> Vector (ST s) a
21
22 instance Unbox a => Base.Base Vector (ST s) a where
23 length (Vector _ n _) = n
24 unsafeSlice (Vector i _ arr#) j m = Vector (i+j) m arr#
25
26 {-# INLINE unsafeNew #-}
27 unsafeNew (I# n#) = ST (\s# ->
28 case newByteArray# (size# (undefined :: a) n#) s# of
29 (# s2#, arr# #) -> (# s2#, Vector 0 (I# n#) arr# #)
30 )
31
32 {-# INLINE unsafeRead #-}
33 unsafeRead (Vector (I# i#) _ arr#) (I# j#) = ST (read# arr# (i# +# j#))
34
35 {-# INLINE unsafeWrite #-}
36 unsafeWrite (Vector (I# i#) _ arr#) (I# j#) x = ST (\s# ->
37 case write# arr# (i# +# j#) x s# of s2# -> (# s2#, () #)
38 )
39
40 {-# INLINE overlaps #-}
41 overlaps (Vector i m arr1#) (Vector j n arr2#)
42 = sameMutableByteArray# arr1# arr2#
43 && (between i j (j+n) || between j i (i+m))
44 where
45 between x y z = x >= y && x < z
46