Drop NFData constraint from compact.
[ghc.git] / libraries / compact / tests / compact_serialize.hs
1 module Main where
2
3 import Control.Exception
4 import Control.Monad
5 import System.Mem
6
7 import Data.IORef
8 import Data.ByteString (ByteString, packCStringLen)
9 import Foreign.Ptr
10
11 import Data.Compact
12 import Data.Compact.Internal
13 import Data.Compact.Serialized
14
15 assertFail :: String -> IO ()
16 assertFail msg = throwIO $ AssertionFailed msg
17
18 assertEquals :: (Eq a, Show a) => a -> a -> IO ()
19 assertEquals expected actual =
20 if expected == actual then return ()
21 else assertFail $ "expected " ++ (show expected)
22 ++ ", got " ++ (show actual)
23
24 serialize :: a -> IO (SerializedCompact a, [ByteString])
25 serialize val = do
26 cnf <- compactSized 4096 True val
27
28 bytestrref <- newIORef undefined
29 scref <- newIORef undefined
30 withSerializedCompact cnf $ \sc -> do
31 writeIORef scref sc
32 performMajorGC
33 bytestrs <- forM (serializedCompactBlockList sc) $ \(ptr, size) -> do
34 packCStringLen (castPtr ptr, fromIntegral size)
35 writeIORef bytestrref bytestrs
36
37 performMajorGC
38
39 bytestrs <- readIORef bytestrref
40 sc <- readIORef scref
41 return (sc, bytestrs)
42
43 main = do
44 let val = ("hello", 1, 42, 42, Just 42) ::
45 (String, Int, Int, Integer, Maybe Int)
46
47 (sc, bytestrs) <- serialize val
48 performMajorGC
49
50 mcnf <- importCompactByteStrings sc bytestrs
51 case mcnf of
52 Nothing -> assertFail "import failed"
53 Just cnf -> assertEquals val (getCompact cnf)