[#423] Make `fromIntegral` safe
Description
fromIntegral
is a dangerous function. This MR aims at making its usages safer. It replaces fromIntegral
with several new converters:
- Statically safe
fromIntegral = intCast
fromPrelude
. Being used for sucha
andb
types thata
is subtype ofb
:IsIntSubType a b ~ 'True
. E.g.Int64 -> Integer
- Statically safe
fromIntegralMaybe = intCastMaybe
fromPrelude
. Being used for anya
andb
that haveIntegral
andBits
instances. - Statically safe
fromIntegralToRealFrac
fromPrelude
. Being used to cast integral number to fractional one. E.g.Int64-> Float
. - Runtime-safe
fromIntegralOverflowing = Universum.fromIntegral
fromPrelude
. Being used for conversions where overflow is intended. Needed to semantically distinguish usages, where overflow is intended, from those that have to fail on overflow. E.g.Int8 -> Word8
with intended bits reinterpretation from lossyInteger -> Int
. - Unsafe
fromIntegralNoOverflow
fromUnsafe
. Being used for integral conversions where overflow/underflow is not expected. ReturnsRight value
if conversion does not produce overflow/underflow andLeft msg
with corresponding error message otherwise. - Unsafe
fromIntegral
fromUnsafe
. Being used for integral conversions checking for overflow/underflow likefromIntegralNoOverflow
, but raising an exception witherror
in case of overflow/underflow.
Additionally, type annotations are applied for all Unsafe.fromIntegral
usages (except for obvious ones) to increase readability. Also, some changes are added to Morley.Tezos.Core
module, in particular 2 similar functions mkMutez
and mkMutez'
are merged in a single mkMutez
and unsafeMkMutez
is replaced with toMutez
where possible. Finally, fromInteger
is redefined in Prelude
to fail on overflow/underflow.
Related issue(s)
Resolves #423 (closed)
✅ Checklist for your Merge Request
Related changes (conditional)
-
Tests (see short guidelines)
-
If I added new functionality, I added tests covering it. -
If I fixed a bug, I added a regression test to prevent the bug from silently reappearing again.
-
-
Documentation
Stylistic guide (mandatory)
-
My commits comply with the following policy. -
My code complies with the style guide.
Edited by Alyona Antonova