on master help sign in
Add Serialize instance for (Array a)
commit3043a3f699fed4ae74fc9657da402da4bc8f89bd authorAdithya Kumar <adithya@composewell.com> dateSun 10 Sep 2023, 12:33 (3 years ago) parentb5667ae
2 files changed+23
core/src/Streamly/Internal/Data/Serialize/Type.hs+20 test/Streamly/Test/Data/Serialize.hs+3
core/src/Streamly/Internal/Data/Serialize/Type.hs+20
@@ -39,6 +39,7 @@ import GHC.Stable (StablePtr(..))
3939
4040import qualified Streamly.Internal.Data.Unbox as Unbox
4141import qualified Streamly.Internal.Data.Array as Array
42+import qualified Streamly.Internal.Data.MutArray as MutArray
4243
4344import GHC.Exts
4445
@@ -247,6 +248,25 @@ instance forall a. Serialize a => Serialize [a] where
247248 pokeList o1 xs
248249 pokeList off1 val
249250
251+instance Serialize (Array a) where
252+ {-# INLINE size #-}
253+ size i (Array {..}) = i + (arrEnd - arrStart) + 8
254+
255+ {-# INLINE deserialize #-}
256+ deserialize off arr end = do
257+ (off1, byteLen) <- deserialize off arr end :: IO (Int, Int)
258+ let off2 = off1 + byteLen
259+ let slice = MutArray.MutArray arr off1 off2 off2
260+ newArr <- MutArray.clone slice
261+ pure (off2, Array.unsafeFreeze newArr)
262+
263+ {-# INLINE serialize #-}
264+ serialize off arr (Array {..}) = do
265+ let arrLen = arrEnd - arrStart
266+ off1 <- serialize off arr arrLen
267+ Unbox.putSliceUnsafe arrContents arrStart arr off1 arrLen
268+ pure (off1 + arrLen)
269+
250270--------------------------------------------------------------------------------
251271-- High level functions
252272--------------------------------------------------------------------------------
test/Streamly/Test/Data/Serialize.hs+3
@@ -170,6 +170,9 @@ testCases = do
170170 it "HigherOrderType"
171171 $ roundtrip $ HigherOrderType (Identity 5) (Identity 'e')
172172
173+ prop "Array Int"
174+ $ \(x :: [Int]) -> roundtrip (Array.fromList x)
175+
173176 limitQC
174177 $ prop "CustomDatatype"
175178 $ \(x :: CustomDatatype) -> roundtrip x