packages feed

morley-1.4.0: src/Util/ByteString.hs

-- SPDX-FileCopyrightText: 2020 Tocqueville Group
--
-- SPDX-License-Identifier: LicenseRef-MIT-TQ

module Util.ByteString
  ( HexJSONByteString(..)
  ) where

import Data.Aeson (FromJSON(..), ToJSON(..), withText)
import Text.Hex (decodeHex, encodeHex)

-- | Newtype wrapper for ByteString which uses hexadecimal representation
-- for JSON serialization.
newtype HexJSONByteString = HexJSONByteString { unHexJSONByteString :: ByteString }
  deriving stock (Eq, Ord, Show, Generic)
  deriving newtype (NFData, Hashable)

instance ToJSON HexJSONByteString where
  toJSON = toJSON . encodeHex . unHexJSONByteString

instance FromJSON HexJSONByteString where
  parseJSON =
    withText "Hex-encoded bytestring" $ \t ->
      case decodeHex t of
        Nothing -> fail "Invalid hex encoding"
        Just res -> pure (HexJSONByteString res)