529283102d0c3d5f2f4f9007f8ac2ef9908b81cc
[darcs-mirrors/vector.git] / Data / Vector / Mutable.hs
1 {-# LANGUAGE MagicHash, UnboxedTuples, MultiParamTypeClasses, GADTs, FlexibleInstances #-}
2
3 module Data.Vector.Mutable ( Vector(..) )
4 where
5
6 import qualified Data.Vector.MVector as MVector
7 import Data.Vector.MVector ( MVector )
8
9 import GHC.Prim ( MutableArray#,
10 newArray#, readArray#, writeArray#, sameMutableArray#, (+#) )
11
12 import GHC.ST ( ST(..) )
13
14 import GHC.Base ( Int(..) )
15
16 #ifndef __HADDOCK__
17 data Vector m a where
18 Vector :: {-# UNPACK #-} !Int
19 -> {-# UNPACK #-} !Int
20 -> MutableArray# s a
21 -> Vector (ST s) a
22 #else
23 data Vector m a = forall s. Vector !Int !Int (MutableArray# s a)
24 #endif
25
26 instance MVector Vector (ST s) a where
27 length (Vector _ n _) = n
28 unsafeSlice (Vector i _ arr#) j m = Vector (i+j) m arr#
29
30 {-# INLINE unsafeNew #-}
31 unsafeNew = unsafeNew
32
33 {-# INLINE unsafeNewWith #-}
34 unsafeNewWith = unsafeNewWith
35
36 {-# INLINE unsafeRead #-}
37 unsafeRead (Vector (I# i#) _ arr#) (I# j#) = ST (readArray# arr# (i# +# j#))
38
39 {-# INLINE unsafeWrite #-}
40 unsafeWrite (Vector (I# i#) _ arr#) (I# j#) x = ST (\s# ->
41 case writeArray# arr# (i# +# j#) x s# of s2# -> (# s2#, () #)
42 )
43
44 {-# INLINE overlaps #-}
45 overlaps (Vector i m arr1#) (Vector j n arr2#)
46 = sameMutableArray# arr1# arr2#
47 && (between i j (j+n) || between j i (i+m))
48 where
49 between x y z = x >= y && x < z
50
51 unsafeNew :: Int -> ST s (Vector (ST s) a)
52 {-# INLINE unsafeNew #-}
53 unsafeNew n = unsafeNewWith n (error "Data.Vector.Mutable: uninitialised elemen t")
54
55 unsafeNewWith :: Int -> a -> ST s (Vector (ST s) a)
56 {-# INLINE unsafeNewWith #-}
57 unsafeNewWith (I# n#) x = ST (\s# ->
58 case newArray# n# x s# of
59 (# s2#, arr# #) -> (# s2#, Vector 0 (I# n#) arr# #)
60 )
61