@@ -20,6 +20,11 @@ module Streamly.Internal.Data.Serialize
21#include "assert.hs"
21#include "assert.hs"
24+import Control.Exception (assert)
25+import Streamly.Internal.Data.Unbox (Unbox(..), sizeOfMutableByteArray)
23import Control.Monad (void)
28import Control.Monad (void)
24import Data.List (foldl')
29import Data.List (foldl')
25import Data.Proxy (Proxy (..))
30import Data.Proxy (Proxy (..))
@@ -105,20 +110,41 @@ class Serialize a where
105-- Instances
110-- Instances
106--------------------------------------------------------------------------------
111--------------------------------------------------------------------------------
113+{-# INLINE checkBounds #-}
114+checkBounds :: String -> Int -> MutableByteArray -> IO ()
115+checkBounds _label _off _arr = do
117+ sz <- sizeOfMutableByteArray _arr
121+ ++ ": accessing array at offset = "
123+ ++ " max valid offset = " ++ show (sz - 1)
108#define DERIVE_SERIALIZE_FROM_UNBOX(_type) \
129#define DERIVE_SERIALIZE_FROM_UNBOX(_type) \
109instance Serialize _type where \
130instance Serialize _type where \
110; {-# INLINE size #-} \
131; {-# INLINE size #-} \
111; size = Size (\acc _ -> acc + Unbox.sizeOf (Proxy :: Proxy _type)) \
132; size = Size (\acc _ -> acc + Unbox.sizeOf (Proxy :: Proxy _type)) \
112; {-# INLINE deserialize #-} \
133; {-# INLINE deserialize #-} \
113; deserialize off arr = \
134; deserialize off arr = \
114− Unbox.peekByteIndex off arr >>= \
115− \val -> let sz = Unbox.sizeOf (Proxy :: Proxy _type) \
135+ let next = off + Unbox.sizeOf (Proxy :: Proxy _type) \
116− in pure (off + sz, val) \
136+ in do { \
137+ checkBounds "deserialize" next arr; \
138+ Unbox.peekByteIndex off arr >>= \val -> pure (next, val); \
117; {-# INLINE serialize #-} \
140; {-# INLINE serialize #-} \
118; serialize off arr val = \
141; serialize off arr val = \
119− Unbox.pokeByteIndex off arr val \
120− >> let sz = Unbox.sizeOf (Proxy :: Proxy _type) \
142+ let next = off + Unbox.sizeOf (Proxy :: Proxy _type) \
144+ checkBounds "serialize" next arr; \
145+ Unbox.pokeByteIndex off arr val; \
121− in pure (off + sz)
146+ pure next \
123DERIVE_SERIALIZE_FROM_UNBOX(Bool)
149DERIVE_SERIALIZE_FROM_UNBOX(Bool)
124DERIVE_SERIALIZE_FROM_UNBOX(Char)
150DERIVE_SERIALIZE_FROM_UNBOX(Char)