Replace type families by GADTs for associating a monad with a mutable vector
[darcs-mirrors/vector.git] / Data / Vector.hs
1 {-# LANGUAGE MagicHash, UnboxedTuples, FlexibleInstances, MultiParamTypeClasses #-}
2
3 module Data.Vector (
4 Vector(..), module Data.Vector.Base
5 ) where
6
7 import Data.Vector.Base
8 import qualified Data.Vector.Mutable as Mut
9
10 import Control.Monad.ST ( runST )
11
12 import GHC.ST ( ST(..) )
13 import GHC.Prim ( Array#, unsafeFreezeArray#, indexArray#, (+#) )
14 import GHC.Base ( Int(..) )
15
16 data Vector a = Vector {-# UNPACK #-} !Int
17 {-# UNPACK #-} !Int
18 (Array# a)
19
20 instance Base Vector a where
21 {-# INLINE create #-}
22 create init = runST (do_create init)
23 where
24 do_create :: ST s (Mut.Vector (ST s) a) -> ST s (Vector a)
25 do_create init = do
26 Mut.Vector i n marr# <- init
27 ST (\s# -> case unsafeFreezeArray# marr# s# of
28 (# s2#, arr# #) -> (# s2#, Vector i n arr# #)
29 )
30
31 {-# INLINE length #-}
32 length (Vector _ n _) = n
33
34 {-# INLINE unsafeSlice #-}
35 unsafeSlice (Vector i _ arr#) j n = Vector (i+j) n arr#
36
37 {-# INLINE unsafeIndex #-}
38 unsafeIndex (Vector (I# i#) _ arr#) (I# j#) f
39 = case indexArray# arr# (i# +# j#) of (# x #) -> f x
40