File: UnsafeSerialize.hs

package info (click to toggle)
haskell-cereal-vector 0.2.0.1-7
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 64 kB
  • sloc: haskell: 130; makefile: 6
file content (52 lines) | stat: -rw-r--r-- 1,988 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
{-# LANGUAGE ScopedTypeVariables, Unsafe #-}
{-# OPTIONS_GHC -Wall #-}

-- | Efficient, but unsafe 'Get' and 'Putter' for
-- "Data.Vector.Storable" vectors. The serialized format is an 'Int64'
-- representing the length of the 'Vector', followed by the raw
-- bytes. Therefore behavior may be unpredictable if serialized data
-- is transferred between machines with different word size or
-- endianness.
module Data.Vector.Storable.UnsafeSerialize (
    unsafeGetVector
  , unsafePutVector
) where

import Control.Monad (when)

import qualified Data.ByteString.Internal as BS
import Data.Int (Int64)
import Data.Serialize (Get, getBytes, putByteString, Putter, Serialize(..))
import Data.Vector.Storable ( unsafeFromForeignPtr0
                            , unsafeToForeignPtr0
                            , Vector)
import Data.Vector.Storable.Internal (updPtr)

import Foreign.ForeignPtr (castForeignPtr)
import Foreign.Marshal.Array (advancePtr)
import Foreign.Storable (Storable, sizeOf)

-- | Get a 'Vector' in host order, endian form, and word width.
unsafeGetVector :: forall a. Storable a => Get (Vector a)
{-# INLINE unsafeGetVector #-}
unsafeGetVector = do 
  len64 <- get :: Get Int64
  when (len64 > fromIntegral (maxBound :: Int)) $
    fail "Host can't deserialize a Vector longer than (maxBound :: Int)"
  let len    = fromIntegral len64
      nbytes = len * sizeOf (undefined :: a)
  bs <- getBytes nbytes
  let (fp, off, _)    = BS.toForeignPtr bs
      fp' | off /= 0  = updPtr (`advancePtr` off) fp
          | otherwise = fp
  return $ unsafeFromForeignPtr0 (castForeignPtr fp') len

-- | Put a 'Vector' in host order, endian form, and word width.
unsafePutVector :: forall a. Storable a => Putter (Vector a)
{-# INLINE unsafePutVector #-}
unsafePutVector v = do
  let (fp, len) = unsafeToForeignPtr0 v
      nbytes    = len * sizeOf (undefined :: a)
      bs        = BS.fromForeignPtr (castForeignPtr fp) 0 nbytes
  put (fromIntegral len :: Int64)
  putByteString bs