774fd5fcb9a7ce580d7a1b46991bd56d5338aaff
[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 ( Vector(..), IOVector, STVector )
16 where
17
18 import Data.Vector.Generic.Mutable ( MVector(..), MVectorPure(..) )
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 Vector m a = Vector {-# UNPACK #-} !Int
26 {-# UNPACK #-} !Int
27 {-# UNPACK #-} !(MutableByteArray m)
28
29 type IOVector = Vector IO
30 type STVector s = Vector (ST s)
31
32 instance Prim a => MVectorPure (Vector m) a where
33 length (Vector _ n _) = n
34 unsafeSlice (Vector i _ arr) j m = Vector (i+j) m arr
35
36 {-# INLINE overlaps #-}
37 overlaps (Vector i m arr1) (Vector 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) => MVector (Vector m) m a where
45 {-# INLINE unsafeNew #-}
46 unsafeNew n = do
47 arr <- newByteArray (n * sizeOf (undefined :: a))
48 return (Vector 0 n arr)
49
50 {-# INLINE unsafeRead #-}
51 unsafeRead (Vector i _ arr) j = readByteArray arr (i+j)
52
53 {-# INLINE unsafeWrite #-}
54 unsafeWrite (Vector i _ arr) j x = writeByteArray arr (i+j) x
55
56 {-# INLINE clear #-}
57 clear _ = return ()
58