Mutable.Vector -> MVector everywhere
[darcs-mirrors/vector.git] / Data / Vector / Mutable.hs
1 {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
2
3 -- |
4 -- Module : Data.Vector.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 boxed vectors.
13 --
14
15 module Data.Vector.Mutable ( MVector(..), IOVector, STVector )
16 where
17
18 import qualified Data.Vector.Generic.Mutable as G
19 import Data.Primitive.Array
20 import Control.Monad.Primitive ( PrimMonad )
21 import Control.Monad.ST ( ST )
22
23 -- | Mutable boxed vectors keyed on the monad they live in ('IO' or @'ST' s@).
24 data MVector m a = MVector {-# UNPACK #-} !Int
25 {-# UNPACK #-} !Int
26 {-# UNPACK #-} !(MutableArray m a)
27
28 type IOVector = MVector IO
29 type STVector s = MVector (ST s)
30
31 instance G.MVectorPure (MVector m) a where
32 length (MVector _ n _) = n
33 unsafeSlice (MVector i _ arr) j m = MVector (i+j) m arr
34
35 {-# INLINE overlaps #-}
36 overlaps (MVector i m arr1) (MVector j n arr2)
37 = sameMutableArray arr1 arr2
38 && (between i j (j+n) || between j i (i+m))
39 where
40 between x y z = x >= y && x < z
41
42
43 instance PrimMonad m => G.MVector (MVector m) m a where
44 {-# INLINE unsafeNew #-}
45 unsafeNew n = do
46 arr <- newArray n uninitialised
47 return (MVector 0 n arr)
48
49 {-# INLINE unsafeNewWith #-}
50 unsafeNewWith n x = do
51 arr <- newArray n x
52 return (MVector 0 n arr)
53
54 {-# INLINE unsafeRead #-}
55 unsafeRead (MVector i _ arr) j = readArray arr (i+j)
56
57 {-# INLINE unsafeWrite #-}
58 unsafeWrite (MVector i _ arr) j x = writeArray arr (i+j) x
59
60 {-# INLINE clear #-}
61 clear v = G.set v uninitialised
62
63 uninitialised :: a
64 uninitialised = error "Data.Vector.Mutable: uninitialised element"
65