Make array indexing immune to seg-faults
|Reported by:||simonpj||Owned by:||igloo|
|Type of failure:||Difficulty:||Unknown|
|Test Case:||Blocked By:|
As Spencer Janssen points out (http://www.haskell.org/pipermail/libraries/2006-December/006539.html), it's possible for a bogus instance of Ix to cause a Haskell implementation to seg-fault, simply by returning an out-of-range index. This is definitely a Bad Thing.
The only way to avoid this possibility is to make (!) perform a bounds check after calling the index method of class Ix. GHC's current implementation (in GHC.Arr) is
(!) :: Ix i => Array i e -> i -> e arr@(Array l u _) ! i = unsafeAt arr (index (l,u) i)
Instead we could have
(!) :: Ix i => Array i e -> i -> e arr@(Array l u _) ! i = safeAt arr (index (l,u) i)
where safeAt performs a bounds check. But that would two bounds checks, one in index and one in safeAt. We could eliminate one by using unsafeIndex, which is a (usually hidden) method of GHC's Ix class definition. However, that might give rise to less-informative messages when the bounds check fails.
To implement safeAt, we'd need a new primop:
arraySize :: Array# a -> Int
There would need to be corresponding stuff for Data.Array.IArray and Data.Array.MArray.