Skip to content

Commit

Permalink
[plc] Support for Natural numbers in the default universe, backed b…
Browse files Browse the repository at this point in the history
…y `Integer`. (#6346)

Co-authored-by: Nikolaos Bezirgiannis <bezirg@users.noreply.github.com>
  • Loading branch information
2 people authored and effectfully committed Aug 6, 2024
1 parent 0777b70 commit d17c094
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
3 changes: 3 additions & 0 deletions plutus-core/changelog.d/20240726_102834_bezirg_ratinteger.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Added

- Support for `Natural` numbers in the default universe, backed by `Integer`.
20 changes: 20 additions & 0 deletions plutus-core/plutus-core/src/PlutusCore/Default/Universe.hs
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,26 @@ deriving newtype instance KnownBuiltinTypeIn DefaultUni term [a] =>
deriving newtype instance KnownBuiltinTypeIn DefaultUni term [a] =>
ReadKnownIn DefaultUni term (ListCostedByLength a)

deriving via AsInteger Natural instance
KnownTypeAst tyname DefaultUni Natural
deriving via AsInteger Natural instance HasConstantIn DefaultUni term =>
MakeKnownIn DefaultUni term Natural
instance HasConstantIn DefaultUni term => ReadKnownIn DefaultUni term Natural where
readKnown term =
-- See Note [Performance of ReadKnownIn and MakeKnownIn instances].
-- Funnily, we don't need 'inline' here, unlike in the default implementation of 'readKnown'
-- (go figure why).
inline readKnownConstant term >>= oneShot \(i :: Integer) ->
-- TODO: benchmark alternatives:signumInteger,integerIsNegative,integerToNaturalThrow
if i >= 0
-- TODO: benchmark alternatives: ghc8.10 naturalFromInteger, ghc>=9 integerToNatural
then pure $ fromInteger i
else throwing _OperationalUnliftingError . MkUnliftingError $ fold
[ Text.pack $ show i
, " is not within the bounds of Natural"
]
{-# INLINE readKnown #-}

{- Note [Stable encoding of tags]
'encodeUni' and 'decodeUni' are used for serialisation and deserialisation of types from the
universe and we need serialised things to be extremely stable, hence the definitions of 'encodeUni'
Expand Down

0 comments on commit d17c094

Please sign in to comment.