@@ -9,22 +9,29 @@
9module Streamly.Internal.Data.Serialize
9module Streamly.Internal.Data.Serialize
10 ( Size(..)
10 ( Size(..)
11 , Serialize(..)
11 , Serialize(..)
14--------------------------------------------------------------------------------
17--------------------------------------------------------------------------------
16--------------------------------------------------------------------------------
19--------------------------------------------------------------------------------
18import Control.Monad (void)
23import Control.Monad (void)
19import Data.List (foldl')
24import Data.List (foldl')
20import Data.Proxy (Proxy (..))
25import Data.Proxy (Proxy (..))
21−import Streamly.Internal.Data.Unbox (MutableByteArray(..))
26+import Streamly.Internal.Data.Unbox (MutableByteArray(..), PinnedState(..))
22−
27+import Streamly.Internal.Data.Array.Type (Array(..))
28+import Streamly.Internal.System.IO (unsafeInlineIO)
23import GHC.Int (Int16(..), Int32(..), Int64(..), Int8(..))
29import GHC.Int (Int16(..), Int32(..), Int64(..), Int8(..))
24import GHC.Word (Word16(..), Word32(..), Word64(..), Word8(..))
30import GHC.Word (Word16(..), Word32(..), Word64(..), Word8(..))
25import GHC.Stable (StablePtr(..))
31import GHC.Stable (StablePtr(..))
27import qualified Streamly.Internal.Data.Unbox as Unbox
33import qualified Streamly.Internal.Data.Unbox as Unbox
34+import qualified Streamly.Internal.Data.Array as Array
29import GHC.Exts
36import GHC.Exts
@@ -167,3 +174,41 @@ instance forall a. Serialize a => Serialize [a] where
167 o1 <- serialize o arr x
174 o1 <- serialize o arr x
168 pokeList o1 xs
175 pokeList o1 xs
169 pokeList off1 val
176 pokeList off1 val
178+--------------------------------------------------------------------------------
179+-- High level functions
180+--------------------------------------------------------------------------------
182+{-# INLINE encodeAs #-}
183+encodeAs :: forall a. Serialize a => PinnedState -> a -> Array Word8
187+ case size :: Size a of
190+ -- We encode the length of the encoding as a header hence the 8 extra
191+ -- bytes to encode Int64
192+ mbarr <- Unbox.newBytesAs ps (8 + len)
193+ off1 <- serialize 0 mbarr (fromIntegral len :: Int64)
194+ off2 <- serialize off1 mbarr a
195+ assertM(off2 == len + off1)
196+ pure $ Array mbarr 0 len
198+{-# INLINE encode #-}
199+encode :: Serialize a => a -> Array Word8
200+encode = encodeAs Unpinned
202+{-# INLINE pinnedEncode #-}
203+pinnedEncode :: Serialize a => a -> Array Word8
204+pinnedEncode = encodeAs Pinned
206+{-# INLINE decode #-}
207+decode :: Serialize a => Array Word8 -> a
208+decode arr@(Array {..}) = unsafeInlineIO $ do
209+ let lenArr = Array.length arr
210+ (off1, lenEncoding :: Int64) <- deserialize 0 arrContents
211+ (off2, val) <- deserialize off1 arrContents
212+ assertM(fromIntegral lenEncoding + off1 == off2)
213+ assertM(lenArr == off2)