@@ -117,6 +117,8 @@ class Serialize a where
117117-- XXX We do not need to pass the end of data offset, we can just check the
118118-- mutable array end here to avoid a crash, and when we return from deserialize
119119-- we can check if the offset returned is beyond the bound or not.
120+--
121+#ifdef DEBUG
120122{-# INLINE checkBounds #-}
121123checkBounds :: String -> Int -> MutableByteArray -> IO ()
122124checkBounds _label _off _arr = do
@@ -128,14 +130,21 @@ checkBounds _label _off _arr = do
128130 ++ show (_off - 1)
129131 ++ " max valid offset = " ++ show (sz - 1)
130132 else return ()
133+#endif
131134
132135{-# INLINE deserializeUnsafe #-}
133136deserializeUnsafe :: forall a. Unbox a => Int -> MutableByteArray -> IO (Int, a)
134137deserializeUnsafe off arr =
135138 let next = off + Unbox.sizeOf (Proxy :: Proxy a)
136139 in do
137− checkBounds "deserialize" next arr
138− Unbox.peekByteIndex off arr >>= \val -> pure (next, val)
140+ sz <- sizeOfMutableByteArray arr
141+ -- Keep likely path in the straight branch.
142+ if (next <= sz)
143+ then Unbox.peekByteIndex off arr >>= \val -> pure (next, val)
144+ else error
145+ $ "deserialize: accessing array at offset = "
146+ ++ show (next - 1)
147+ ++ " max valid offset = " ++ show (sz - 1)
139148
140149{-# INLINE serializeUnsafe #-}
141150serializeUnsafe :: forall a. Unbox a => Int -> MutableByteArray -> a -> IO Int