Change D.V.IVector.unsafeIndex to be monadic
[darcs-mirrors/vector.git] / Data / Vector / Unboxed.hs
1 {-# LANGUAGE MagicHash, UnboxedTuples, FlexibleInstances, MultiParamTypeClasses #-}
2
3 -- |
4 -- Module : Data.Vector.Unboxed
5 -- Copyright : (c) Roman Leshchinskiy 2008
6 -- License : BSD-style
7 --
8 -- Maintainer : Roman Leshchinskiy <rl@cse.unsw.edu.au>
9 -- Stability : experimental
10 -- Portability : non-portable
11 --
12 -- Unboxed vectors based on 'Unbox'.
13 --
14
15 module Data.Vector.Unboxed (
16 Vector(..), module Data.Vector.IVector
17 ) where
18
19 import Data.Vector.IVector
20 import qualified Data.Vector.Unboxed.Mutable.ST as Mut
21 import Data.Vector.Unboxed.Unbox
22
23 import Control.Monad.ST ( runST )
24
25 import GHC.ST ( ST(..) )
26 import GHC.Prim ( ByteArray#, unsafeFreezeByteArray#, (+#) )
27 import GHC.Base ( Int(..) )
28
29 -- | Unboxed vectors
30 data Vector a = Vector {-# UNPACK #-} !Int
31 {-# UNPACK #-} !Int
32 ByteArray#
33
34 instance (Show a, Unbox a) => Show (Vector a) where
35 show = (Prelude.++ " :: Data.Vector.Unboxed.Vector") . ("fromList " Prelude.++) . show . toList
36
37 instance Unbox a => IVector Vector a where
38 {-# INLINE vnew #-}
39 vnew init = runST (do
40 Mut.Vector i n marr# <- init
41 ST (\s# -> case unsafeFreezeByteArray# marr# s# of
42 (# s2#, arr# #) -> (# s2#, Vector i n arr# #)))
43
44 {-# INLINE vlength #-}
45 vlength (Vector _ n _) = n
46
47 {-# INLINE unsafeSlice #-}
48 unsafeSlice (Vector i _ arr#) j n = Vector (i+j) n arr#
49
50 {-# INLINE unsafeIndexM #-}
51 unsafeIndexM (Vector (I# i#) _ arr#) (I# j#) = return (at# arr# (i# +# j#))
52
53 instance (Unbox a, Eq a) => Eq (Vector a) where
54 {-# INLINE (==) #-}
55 (==) = eq
56
57 instance (Unbox a, Ord a) => Ord (Vector a) where
58 {-# INLINE compare #-}
59 compare = cmp
60