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