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