packages feed

morley-1.15.0: src/Michelson/Interpret/Pack.hs

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

-- | Module, carrying logic of @PACK@ instruction.
--
-- This is nearly symmetric to adjacent Unpack.hs module.
module Michelson.Interpret.Pack
  ( packValue
  , packValue'
  , packValuePrefix
  , toBinary
  , toBinary'
  ) where

import Prelude hiding (EQ, GT, LT)

import Michelson.Typed
import Morley.Micheline.Binary (encodeExpression, encodeExpression')
import Morley.Micheline.Class (ToExpression(..))

-- | Generic serializer.
toBinary :: ToExpression a => a -> LByteString
toBinary = encodeExpression . toExpression

-- | Same as 'toBinary', for strict bytestring.
toBinary' :: ToExpression a => a -> ByteString
toBinary' = encodeExpression' . toExpression

-- | Serialize a value given to @PACK@ instruction.
packValue :: PackedValScope t => Value t -> LByteString
packValue x =
  let uval = untypeValueHashable x
  in packValuePrefix <> (encodeExpression $ toExpression uval)

-- | Same as 'packValue', for strict bytestring.
packValue' :: PackedValScope t => Value t -> ByteString
packValue' x =
  let uval = untypeValueHashable x
  in packValuePrefix <> (encodeExpression' $ toExpression uval)

-- | Prefix prepended to the binary representation of a value.
packValuePrefix :: IsString s => s
packValuePrefix = "\x05"