Skip to content

Add GenericBinary wrapper that can be used with DerivingVia #173

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Data/Binary.hs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ module Data.Binary (
, GBinaryGet(..)
, GBinaryPut(..)

, GenericBinary(..)

-- * The Get and Put monads
, Get
, Put
Expand Down
33 changes: 33 additions & 0 deletions src/Data/Binary/Class.hs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE UndecidableInstances #-}

#if __GLASGOW_HASKELL__ >= 706
{-# LANGUAGE PolyKinds #-}
Expand Down Expand Up @@ -41,6 +42,8 @@ module Data.Binary.Class (
, GBinaryGet(..)
, GBinaryPut(..)

, GenericBinary(..)

) where

import Data.Word
Expand Down Expand Up @@ -1045,3 +1048,33 @@ instance Binary SomeTypeRep where
get = getSomeTypeRep
#endif


------------------------------------------------------------------------
-- Wrapper for DerivingVia

-- | 'GenericBinary' can be used in conjunction with DerivingVia. It is most useful when chaining
-- types that augment derived instances.
--
-- Simple usage with DerivingVia:
--
-- @
-- data Foo = Foo Int String
-- deriving Generic
-- deriving Binary via GenericBinary Foo
-- @
--
-- When chaining multiple augmentations:
--
-- @
-- data Foo = Foo Int String
-- deriving Generic
-- deriving Binary via Augmentation1 (Augmentation2 (GenericBinary Foo))
-- @
--
newtype GenericBinary a = GenericBinary
{ unGenericBinary :: a }

instance (Generic a, GBinaryPut (Rep a), GBinaryGet (Rep a)) => Binary (GenericBinary a) where
put = gput . from . unGenericBinary

get = fmap (GenericBinary . to) gget