Boxed Vectors
[darcs-mirrors/vector.git] / Data / Vector / Mutable.hs
1 {-# LANGUAGE BangPatterns #-}
2
3 module Data.Vector.Mutable (
4 Vector,
5
6 new, new', length, slice, read, write, fill,
7 dataOf
8 ) where
9
10 import qualified Data.Vector.Prim as Prim
11
12 import qualified Data.Vector.Stream as Stream
13 import Data.Vector.Stream ( Stream )
14
15 import Control.Exception ( assert )
16 import Control.Monad.ST ( ST )
17
18 import Prelude hiding ( length, read )
19
20 data Vector s a = Vector {-# UNPACK #-} !Int
21 {-# UNPACK #-} !Int
22 {-# UNPACK #-} !(Prim.MutableVector s a)
23
24 dataOf :: Vector s a -> (Prim.MutableVector s a, Int, Int)
25 {-# INLINE dataOf #-}
26 dataOf (Vector i n v) = (v, i, n)
27
28 new :: Int -> ST s (Vector s a)
29 {-# INLINE new #-}
30 new n = new' n (error "Data.Vector.Mutable: uninitialised element")
31
32 new' :: Int -> a -> ST s (Vector s a)
33 {-# INLINE new' #-}
34 new' n x = assert (n >= 0)
35 $ Vector 0 n `fmap` Prim.new' n x
36
37 length :: Vector s a -> Int
38 {-# INLINE length #-}
39 length (Vector _ n _) = n
40
41 slice :: Vector s a -> Int -> Int -> Vector s a
42 {-# INLINE slice #-}
43 slice (Vector i n v) j m
44 = assert (j + m <= n && j >= 0 && m >= 0)
45 $ Vector (i+j) m v
46
47 read :: Vector s a -> Int -> ST s a
48 {-# INLINE read #-}
49 read (Vector i n v) j
50 = assert (j < n)
51 $ Prim.read v (i+j)
52
53 write :: Vector s a -> Int -> a -> ST s ()
54 {-# INLINE write #-}
55 write (Vector i n v) j x
56 = assert (j < n)
57 $ Prim.write v (i+j) x
58
59 fill :: Vector s a -> Stream a -> ST s Int
60 {-# INLINE fill #-}
61 fill !v s = Stream.foldM put 0 s
62 where
63 {-# INLINE put #-}
64 put i x = do { write v i x; return (i+1) }
65