Change handling of Monad in MVector and get rid of GADTs
[darcs-mirrors/vector.git] / Data / Vector / Mutable.hs
1 {-# LANGUAGE MagicHash, UnboxedTuples, MultiParamTypeClasses, FlexibleInstances #-}
2
3 -- |
4 -- Module : Data.Vector.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 boxed vectors.
13 --
14
15 module Data.Vector.Mutable ( Vector(..) )
16 where
17
18 import qualified Data.Vector.MVector as MVector
19 import Data.Vector.MVector ( MVector, MVectorPure )
20
21 import GHC.Prim ( MutableArray#,
22 newArray#, readArray#, writeArray#, sameMutableArray#, (+#) )
23
24 import GHC.ST ( ST(..) )
25
26 import GHC.Base ( Int(..) )
27
28 -- | Mutable boxed vectors. They live in the 'ST' monad.
29 data Vector s a = Vector {-# UNPACK #-} !Int
30 {-# UNPACK #-} !Int
31 (MutableArray# s a)
32
33 instance MVectorPure (Vector s) a where
34 length (Vector _ n _) = n
35 unsafeSlice (Vector i _ arr#) j m = Vector (i+j) m arr#
36
37 {-# INLINE overlaps #-}
38 overlaps (Vector i m arr1#) (Vector j n arr2#)
39 = sameMutableArray# arr1# arr2#
40 && (between i j (j+n) || between j i (i+m))
41 where
42 between x y z = x >= y && x < z
43
44
45 instance MVector (Vector s) (ST s) a where
46 {-# INLINE unsafeNew #-}
47 unsafeNew = unsafeNew
48
49 {-# INLINE unsafeNewWith #-}
50 unsafeNewWith = unsafeNewWith
51
52 {-# INLINE unsafeRead #-}
53 unsafeRead (Vector (I# i#) _ arr#) (I# j#) = ST (readArray# arr# (i# +# j#))
54
55 {-# INLINE unsafeWrite #-}
56 unsafeWrite (Vector (I# i#) _ arr#) (I# j#) x = ST (\s# ->
57 case writeArray# arr# (i# +# j#) x s# of s2# -> (# s2#, () #)
58 )
59
60
61 unsafeNew :: Int -> ST s (Vector s a)
62 {-# INLINE unsafeNew #-}
63 unsafeNew n = unsafeNewWith n (error "Data.Vector.Mutable: uninitialised elemen t")
64
65 unsafeNewWith :: Int -> a -> ST s (Vector s a)
66 {-# INLINE unsafeNewWith #-}
67 unsafeNewWith (I# n#) x = ST (\s# ->
68 case newArray# n# x s# of
69 (# s2#, arr# #) -> (# s2#, Vector 0 (I# n#) arr# #)
70 )
71