Use primitive-types in D.V.Primitive
[darcs-mirrors/vector.git] / Data / Vector / Primitive / Mutable / ST.hs
1 {-# LANGUAGE MagicHash, UnboxedTuples, MultiParamTypeClasses, FlexibleInstances, ScopedTypeVariables #-}
2
3 -- |
4 -- Module : Data.Vector.Primitive.Mutable.ST
5 -- Copyright : (c) Roman Leshchinskiy 2008
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 based in the ST monad.
13 --
14
15 module Data.Vector.Primitive.Mutable.ST ( Vector(..) )
16 where
17
18 import qualified Data.Vector.MVector as MVector
19 import Data.Vector.MVector ( MVector, MVectorPure )
20 import Data.Primitive.ByteArray
21 import Data.Primitive ( Prim, sizeOf )
22
23 import GHC.ST ( ST(..) )
24
25 import GHC.Base ( Int(..) )
26
27 -- | Mutable unboxed vectors. They live in the 'ST' monad.
28 data Vector s a = Vector {-# UNPACK #-} !Int
29 {-# UNPACK #-} !Int
30 {-# UNPACK #-} !(MutableByteArray s)
31
32 instance Prim a => MVectorPure (Vector s) 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 => MVector (Vector s) (ST s) 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