0 | module Data.IOMatrix
 1 |
 2 | import Data.IOArray.Prims
 3 |
 4 | %default total
 5 |
 6 | export
 7 | record IOMatrix a where
 8 |   constructor MkIOMatrix
 9 |   maxWidth  : Int
10 |   maxHeight : Int
11 |   content   : ArrayData (Maybe a)
12 |
13 | export
14 | width : IOMatrix a -> Int
15 | width = maxWidth
16 |
17 | export
18 | height : IOMatrix a -> Int
19 | height = maxHeight
20 |
21 | export
22 | new : HasIO io => (width, height : Int) -> io (IOMatrix a)
23 | new width height
24 |   = pure $ MkIOMatrix width height
25 |          !(primIO (prim__newArray (width * height) Nothing))
26 |
27 | toPosition : IOMatrix a -> Int -> Int -> Maybe Int
28 | toPosition (MkIOMatrix w h arr) i j
29 |   = do guard (not (i < 0 || j < 0 || i >= w || j >= h))
30 |        pure (i * h + j)
31 |
32 | export
33 | write : HasIO io => IOMatrix a -> Int -> Int -> a -> io Bool
34 | write mat i j el = case toPosition mat i j of
35 |   Nothing => pure False
36 |   Just pos => True <$ primIO (prim__arraySet (content mat) pos (Just el))
37 |
38 | export
39 | read : HasIO io => IOMatrix a -> Int -> Int -> io (Maybe a)
40 | read mat i j = case toPosition mat i j of
41 |   Nothing => pure Nothing
42 |   Just pos => primIO (prim__arrayGet (content mat) pos)
43 |