Skip to content

Instantly share code, notes, and snippets.

@Icelandjack
Forked from ndmitchell/Binary.hs
Created September 1, 2017 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Icelandjack/7a63a3a6abc4e3c6aea8af39fa4fd09d to your computer and use it in GitHub Desktop.
Save Icelandjack/7a63a3a6abc4e3c6aea8af39fa4fd09d to your computer and use it in GitHub Desktop.
Binary existentials
{-# LANGUAGE StaticPointers #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE ScopedTypeVariables #-}
import Data.Binary
import Data.Typeable
import System.IO.Unsafe
import GHC.StaticPtr
data Foo = forall a . (Typeable a, Binary a, Show a) => Foo (StaticPtr (Get Foo)) a
foo_string :: StaticPtr (Get Foo)
foo_string = static (Foo foo_string <$> (get :: Get String))
foo_int :: StaticPtr (Get Foo)
foo_int = static (Foo foo_int <$> (get :: Get Int))
main = do
let a = encode $ Foo foo_string ("test" :: String)
let b = encode $ Foo foo_int (123456 :: Int)
let f s = case decode s of Foo _ x -> print x
f a
f b
instance Binary Foo where
get :: Get Foo
get = do
ptr <- get
case unsafePerformIO (unsafeLookupStaticPtr ptr) of
Just value -> deRefStaticPtr value :: Get Foo
Nothing -> error "Binary Foo: unknown static pointer"
put :: Foo -> Put
put (Foo a b) = do
put $ staticKey a
put b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment