5851a740e3499f9f39be7d8893967ea9ed78b8ec
[darcs-mirrors/vector.git] / Data / Vector / Mutable.hs
1 {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, TypeFamilies #-}
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
21 import Control.Monad.ST ( ST )
22
23 #include "vector.h"
24
25 -- | Mutable boxed vectors keyed on the monad they live in ('IO' or @'ST' s@).
26 data MVector s a = MVector {-# UNPACK #-} !Int
27 {-# UNPACK #-} !Int
28 {-# UNPACK #-} !(MutableArray s a)
29
30 type IOVector = MVector RealWorld
31 type STVector s = MVector s
32
33 instance G.MVector MVector a where
34 length (MVector _ n _) = n
35 unsafeSlice (MVector i n arr) j m
36 = UNSAFE_CHECK(checkSlice) "unsafeSlice" j m n
37 $ MVector (i+j) m arr
38
39 {-# INLINE overlaps #-}
40 overlaps (MVector i m arr1) (MVector j n arr2)
41 = sameMutableArray arr1 arr2
42 && (between i j (j+n) || between j i (i+m))
43 where
44 between x y z = x >= y && x < z
45
46 {-# INLINE unsafeNew #-}
47 unsafeNew n = UNSAFE_CHECK(checkLength) "unsafeNew" n
48 $ do
49 arr <- newArray n uninitialised
50 return (MVector 0 n arr)
51
52 {-# INLINE unsafeNewWith #-}
53 unsafeNewWith n x = UNSAFE_CHECK(checkLength) "unsafeNewWith" n
54 $ do
55 arr <- newArray n x
56 return (MVector 0 n arr)
57
58 {-# INLINE unsafeRead #-}
59 unsafeRead (MVector i n arr) j = UNSAFE_CHECK(checkIndex) "unsafeRead" j n
60 $ readArray arr (i+j)
61
62 {-# INLINE unsafeWrite #-}
63 unsafeWrite (MVector i n arr) j x = UNSAFE_CHECK(checkIndex) "unsafeWrite" j n
64 $ writeArray arr (i+j) x
65
66 {-# INLINE clear #-}
67 clear v = G.set v uninitialised
68
69 uninitialised :: a
70 uninitialised = error "Data.Vector.Mutable: uninitialised element"
71