Rename D.V.IVector, D.V.MVector and D.V.MVector.New
[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 Data.Vector.Generic.Mutable ( MVector(..), MVectorPure(..) )
16 import Data.Primitive.ByteArray
17 import Data.Primitive ( Prim, sizeOf )
18 import Control.Monad.Primitive
19 import Control.Monad.ST ( ST )
20
21 -- | Mutable unboxed vectors. They live in the 'ST' monad.
22 data Vector m a = Vector {-# UNPACK #-} !Int
23 {-# UNPACK #-} !Int
24 {-# UNPACK #-} !(MutableByteArray m)
25
26 type IOVector = Vector IO
27 type STVector s = Vector (ST s)
28
29 instance Prim a => MVectorPure (Vector m) a where
30 length (Vector _ n _) = n
31 unsafeSlice (Vector i _ arr) j m = Vector (i+j) m arr
32
33 {-# INLINE overlaps #-}
34 overlaps (Vector i m arr1) (Vector j n arr2)
35 = sameMutableByteArray arr1 arr2
36 && (between i j (j+n) || between j i (i+m))
37 where
38 between x y z = x >= y && x < z
39
40
41 instance (Prim a, PrimMonad m) => MVector (Vector m) m a where
42 {-# INLINE unsafeNew #-}
43 unsafeNew n = do
44 arr <- newByteArray (n * sizeOf (undefined :: a))
45 return (Vector 0 n arr)
46
47 {-# INLINE unsafeRead #-}
48 unsafeRead (Vector i _ arr) j = readByteArray arr (i+j)
49
50 {-# INLINE unsafeWrite #-}
51 unsafeWrite (Vector i _ arr) j x = writeByteArray arr (i+j) x
52
53 {-# INLINE clear #-}
54 clear _ = return ()
55