on master help sign in
Add Serialize instance for (Array a)
3043a3fAdithya Kumar
core/src/Streamly/Internal/Data/Serialize/Type.hs+20
@@ -39,6 +39,7 @@ import GHC.Stable (StablePtr(..))
39
39
40import qualified Streamly.Internal.Data.Unbox as Unbox
40import qualified Streamly.Internal.Data.Unbox as Unbox
41import qualified Streamly.Internal.Data.Array as Array
41import qualified Streamly.Internal.Data.Array as Array
42+import qualified Streamly.Internal.Data.MutArray as MutArray
42
43
43import GHC.Exts
44import GHC.Exts
44
45
@@ -247,6 +248,25 @@ instance forall a. Serialize a => Serialize [a] where
247 pokeList o1 xs
248 pokeList o1 xs
248 pokeList off1 val
249 pokeList off1 val
249
250
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+
250--------------------------------------------------------------------------------
270--------------------------------------------------------------------------------
251-- High level functions
271-- High level functions
252--------------------------------------------------------------------------------
272--------------------------------------------------------------------------------
test/Streamly/Test/Data/Serialize.hs+3
@@ -170,6 +170,9 @@ testCases = do
170 it "HigherOrderType"
170 it "HigherOrderType"
171 $ roundtrip $ HigherOrderType (Identity 5) (Identity 'e')
171 $ roundtrip $ HigherOrderType (Identity 5) (Identity 'e')
172
172
173+ prop "Array Int"
174+ $ \(x :: [Int]) -> roundtrip (Array.fromList x)
175+
173 limitQC
176 limitQC
174 $ prop "CustomDatatype"
177 $ prop "CustomDatatype"
175 $ \(x :: CustomDatatype) -> roundtrip x
178 $ \(x :: CustomDatatype) -> roundtrip x