Skip to content

Instantly share code, notes, and snippets.

@acowley
Created June 7, 2013 21:59
Show Gist options
  • Save acowley/5732709 to your computer and use it in GitHub Desktop.
Save acowley/5732709 to your computer and use it in GitHub Desktop.
Demonstrate building a ByteString from heterogenous Storable types.
{-# LANGUAGE ScopedTypeVariables #-}
import Data.Binary.Builder
import Data.Binary.Builder.Internal
import Foreign.Ptr (castPtr)
import Foreign.Storable (Storable(sizeOf,poke))
-- For testing
import Linear
import Data.ByteString.Lazy (ByteString)
import Data.Monoid ((<>))
store :: forall a. Storable a => a -> Builder
store x = writeN (sizeOf (undefined::a)) (flip poke x . castPtr)
-- Testing
data Foo = Foo (V2 Float) (V3 Double)
fooBytes :: Foo -> ByteString
fooBytes (Foo bar baz) = toLazyByteString $ store bar <> store baz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment