{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}

module Hedgehog.Classes.Binary (binaryLaws) where

import Hedgehog
import Hedgehog.Classes.Common
import Data.Binary (Binary)
import qualified Data.Binary as Binary

-- | Tests the following 'Binary' laws:
--
-- [__Encoding Partial Isomorphism__]: @'Binary.decode' '.' 'Binary.encode'@ ≡ @'id'@
binaryLaws :: (Binary a, Eq a, Show a) => Gen a -> Laws
binaryLaws :: forall a. (Binary a, Eq a, Show a) => Gen a -> Laws
binaryLaws Gen a
gen = String -> [(String, Property)] -> Laws
Laws String
"Binary"
  [ (String
"Partial Isomorphism", forall a. (Binary a, Show a, Eq a) => Gen a -> Property
binaryPartialIsomorphism Gen a
gen)
  ]

binaryPartialIsomorphism :: forall a. (Binary a, Show a, Eq a) => Gen a -> Property
binaryPartialIsomorphism :: forall a. (Binary a, Show a, Eq a) => Gen a -> Property
binaryPartialIsomorphism Gen a
gen = HasCallStack => PropertyT IO () -> Property
property forall a b. (a -> b) -> a -> b
$ do
  a
x <- forall (m :: * -> *) a.
(Monad m, Show a, HasCallStack) =>
Gen a -> PropertyT m a
forAll Gen a
gen
  let encoded :: ByteString
encoded = forall a. Binary a => a -> ByteString
Binary.encode a
x
  let lhs :: a
lhs = forall a. Binary a => ByteString -> a
Binary.decode @a ByteString
encoded
  let rhs :: a
rhs = a
x
  let ctx :: Context
ctx = LawContext -> Context
contextualise forall a b. (a -> b) -> a -> b
$ LawContext
        { lawContextLawName :: String
lawContextLawName = String
"Partial Isomorphism", lawContextTcName :: String
lawContextTcName = String
"Binary"
        , lawContextLawBody :: String
lawContextLawBody = String
"decode . encode" String -> String -> String
`congruency` String
"id"
        , lawContextTcProp :: String
lawContextTcProp =
            let showX :: String
showX = forall a. Show a => a -> String
show a
x
                showEncoded :: String
showEncoded = forall a. Show a => a -> String
show ByteString
encoded
            in [String] -> String
lawWhere
              [ String
"decode . encode $ x" String -> String -> String
`congruency` String
"x, where"
              , String
"x = " forall a. [a] -> [a] -> [a]
++ String
showX
              , String
"encode x = " forall a. [a] -> [a] -> [a]
++ String
showEncoded
              ]
        , lawContextReduced :: String
lawContextReduced = forall a. Show a => a -> a -> String
reduced a
lhs a
rhs
        }
  forall (m :: * -> *) a.
(MonadTest m, HasCallStack, Eq a, Show a) =>
a -> a -> Context -> m ()
heqCtx a
lhs a
rhs Context
ctx