on master help sign in
Deserialize: Keep the likely path in the straight branch
7c81bfbHarendra Kumar
core/src/Streamly/Internal/Data/Serialize.hs+11−2
@@ -117,6 +117,8 @@ class Serialize a where
117-- XXX We do not need to pass the end of data offset, we can just check the
117-- XXX We do not need to pass the end of data offset, we can just check the
118-- mutable array end here to avoid a crash, and when we return from deserialize
118-- mutable array end here to avoid a crash, and when we return from deserialize
119-- we can check if the offset returned is beyond the bound or not.
119-- we can check if the offset returned is beyond the bound or not.
120+--
121+#ifdef DEBUG
120{-# INLINE checkBounds #-}
122{-# INLINE checkBounds #-}
121checkBounds :: String -> Int -> MutableByteArray -> IO ()
123checkBounds :: String -> Int -> MutableByteArray -> IO ()
122checkBounds _label _off _arr = do
124checkBounds _label _off _arr = do
@@ -128,14 +130,21 @@ checkBounds _label _off _arr = do
128 ++ show (_off - 1)
130 ++ show (_off - 1)
129 ++ " max valid offset = " ++ show (sz - 1)
131 ++ " max valid offset = " ++ show (sz - 1)
130 else return ()
132 else return ()
133+#endif
131
134
132{-# INLINE deserializeUnsafe #-}
135{-# INLINE deserializeUnsafe #-}
133deserializeUnsafe :: forall a. Unbox a => Int -> MutableByteArray -> IO (Int, a)
136deserializeUnsafe :: forall a. Unbox a => Int -> MutableByteArray -> IO (Int, a)
134deserializeUnsafe off arr =
137deserializeUnsafe off arr =
135 let next = off + Unbox.sizeOf (Proxy :: Proxy a)
138 let next = off + Unbox.sizeOf (Proxy :: Proxy a)
136 in do
139 in do
137− checkBounds "deserialize" next arr
140+ sz <- sizeOfMutableByteArray arr
141+ -- Keep likely path in the straight branch.
142+ if (next <= sz)
138− Unbox.peekByteIndex off arr >>= \val -> pure (next, val)
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)
139
148
140{-# INLINE serializeUnsafe #-}
149{-# INLINE serializeUnsafe #-}
141serializeUnsafe :: forall a. Unbox a => Int -> MutableByteArray -> a -> IO Int
150serializeUnsafe :: forall a. Unbox a => Int -> MutableByteArray -> a -> IO Int