ced0233388d8b6c904cc2527e78ebe09bf4ecb99
[darcs-mirrors/vector.git] / Data / Vector / Mutable.hs
1 {-# LANGUAGE MagicHash, UnboxedTuples, MultiParamTypeClasses, GADTs, 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 )
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 #ifndef __HADDOCK__
29 data Vector m a where
30 Vector :: {-# UNPACK #-} !Int
31 -> {-# UNPACK #-} !Int
32 -> MutableArray# s a
33 -> Vector (ST s) a
34 #else
35 -- | Type of mutable boxed vectors. This is actually a GADT:
36 --
37 -- > data Vector m a where
38 -- > Vector :: !Int -> !Int -> MutableArray# s a -> Vector (ST s) a
39 --
40 data Vector m a = forall s. Vector !Int !Int (MutableArray# s a)
41 #endif
42
43 instance MVector Vector (ST s) a where
44 length (Vector _ n _) = n
45 unsafeSlice (Vector i _ arr#) j m = Vector (i+j) m arr#
46
47 {-# INLINE unsafeNew #-}
48 unsafeNew = unsafeNew
49
50 {-# INLINE unsafeNewWith #-}
51 unsafeNewWith = unsafeNewWith
52
53 {-# INLINE unsafeRead #-}
54 unsafeRead (Vector (I# i#) _ arr#) (I# j#) = ST (readArray# arr# (i# +# j#))
55
56 {-# INLINE unsafeWrite #-}
57 unsafeWrite (Vector (I# i#) _ arr#) (I# j#) x = ST (\s# ->
58 case writeArray# arr# (i# +# j#) x s# of s2# -> (# s2#, () #)
59 )
60
61 {-# INLINE overlaps #-}
62 overlaps (Vector i m arr1#) (Vector j n arr2#)
63 = sameMutableArray# arr1# arr2#
64 && (between i j (j+n) || between j i (i+m))
65 where
66 between x y z = x >= y && x < z
67
68 unsafeNew :: Int -> ST s (Vector (ST s) a)
69 {-# INLINE unsafeNew #-}
70 unsafeNew n = unsafeNewWith n (error "Data.Vector.Mutable: uninitialised elemen t")
71
72 unsafeNewWith :: Int -> a -> ST s (Vector (ST s) a)
73 {-# INLINE unsafeNewWith #-}
74 unsafeNewWith (I# n#) x = ST (\s# ->
75 case newArray# n# x s# of
76 (# s2#, arr# #) -> (# s2#, Vector 0 (I# n#) arr# #)
77 )
78