Mutable.Vector -> MVector everywhere
[darcs-mirrors/vector.git] / Data / Vector / Primitive / Mutable.hs
1 {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, ScopedTypeVariables #-}
2
3 -- |
4 -- Module : Data.Vector.Primitive.Mutable
5 -- Copyright : (c) Roman Leshchinskiy 2008-2009
6 -- License : BSD-style
7 --
8 -- Maintainer : Roman Leshchinskiy <rl@cse.unsw.edu.au>
9 -- Stability : experimental
10 -- Portability : non-portable
11 --
12 -- Mutable primitive vectors.
13 --
14
15 module Data.Vector.Primitive.Mutable ( MVector(..), IOVector, STVector )
16 where
17
18 import qualified Data.Vector.Generic.Mutable as G
19 import Data.Primitive.ByteArray
20 import Data.Primitive ( Prim, sizeOf )
21 import Control.Monad.Primitive
22 import Control.Monad.ST ( ST )
23
24 -- | Mutable unboxed vectors. They live in the 'ST' monad.
25 data MVector m a = MVector {-# UNPACK #-} !Int
26 {-# UNPACK #-} !Int
27 {-# UNPACK #-} !(MutableByteArray m)
28
29 type IOVector = MVector IO
30 type STVector s = MVector (ST s)
31
32 instance Prim a => G.MVectorPure (MVector m) a where
33 length (MVector _ n _) = n
34 unsafeSlice (MVector i _ arr) j m = MVector (i+j) m arr
35
36 {-# INLINE overlaps #-}
37 overlaps (MVector i m arr1) (MVector j n arr2)
38 = sameMutableByteArray arr1 arr2
39 && (between i j (j+n) || between j i (i+m))
40 where
41 between x y z = x >= y && x < z
42
43
44 instance (Prim a, PrimMonad m) => G.MVector (MVector m) m a where
45 {-# INLINE unsafeNew #-}
46 unsafeNew n = do
47 arr <- newByteArray (n * sizeOf (undefined :: a))
48 return (MVector 0 n arr)
49
50 {-# INLINE unsafeRead #-}
51 unsafeRead (MVector i _ arr) j = readByteArray arr (i+j)
52
53 {-# INLINE unsafeWrite #-}
54 unsafeWrite (MVector i _ arr) j x = writeByteArray arr (i+j) x
55
56 {-# INLINE clear #-}
57 clear _ = return ()
58