643bd298a1de282988f34c5a29a3050e63a87aa7
[darcs-mirrors/vector.git] / Data / Vector / Storable / Mutable.hs
1 {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
2
3 -- |
4 -- Module : Data.Vector.Storable.Mutable
5 -- Copyright : (c) Roman Leshchinskiy 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 vectors based on Storable.
13 --
14
15 module Data.Vector.Storable.Mutable( Vector(..) )
16 where
17
18 import qualified Data.Vector.MVector as MVector
19 import Data.Vector.MVector ( MVector, MVectorPure )
20
21 import Foreign.Storable
22 import Foreign.ForeignPtr
23
24 -- | Mutable 'Storable'-based vectors in the 'IO' monad.
25 data Vector a = Vector {-# UNPACK #-} !Int
26 {-# UNPACK #-} !Int
27 {-# UNPACK #-} !(ForeignPtr a)
28
29 instance MVectorPure Vector a where
30 {-# INLINE length #-}
31 length (Vector _ n _) = n
32
33 {-# INLINE unsafeSlice #-}
34 unsafeSlice (Vector i _ p) j m = Vector (i+j) m p
35
36 -- FIXME: implement this properly
37 {-# INLINE overlaps #-}
38 overlaps (Vector i m p) (Vector j n q)
39 = True
40
41 instance Storable a => MVector Vector IO a where
42 {-# INLINE unsafeNew #-}
43 unsafeNew n = Vector 0 n `fmap` mallocForeignPtrArray n
44
45 {-# INLINE unsafeRead #-}
46 unsafeRead (Vector i n p) j = withForeignPtr p $ \ptr ->
47 peekElemOff ptr (i+j)
48
49 {-# INLINE unsafeWrite #-}
50 unsafeWrite (Vector i n p) j x = withForeignPtr p $ \ptr ->
51 pokeElemOff ptr (i+j) x
52
53 {-# INLINE clear #-}
54 clear _ = return ()
55