/
UInt.purs
36 lines (27 loc) · 1.2 KB
/
UInt.purs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
module Network.Ethereum.Web3.Solidity.UInt
( UIntN,
unUIntN,
uIntNFromBigNumber
) where
import Prelude
import Data.Maybe (Maybe(..))
import Network.Ethereum.Web3.Types (BigNumber, embed, pow)
import Network.Ethereum.Web3.Solidity.Size (class KnownSize, sizeVal)
import Type.Proxy (Proxy(..))
--------------------------------------------------------------------------------
-- * Statically sized unsigned integers
--------------------------------------------------------------------------------
-- | Represents a statically sized unsigned integer of size `n`
newtype UIntN n = UIntN BigNumber
derive newtype instance showUIntN :: Show (UIntN n)
derive newtype instance eqUIntN :: Eq (UIntN n)
derive newtype instance ordUIntN :: Ord (UIntN n)
-- | Access the raw underlying unsigned integer
unUIntN :: forall n . KnownSize n => UIntN n -> BigNumber
unUIntN (UIntN a) = a
-- | Attempt to coerce an unsigned integer into a statically sized one
uIntNFromBigNumber :: forall n . KnownSize n => BigNumber -> Maybe (UIntN n)
uIntNFromBigNumber a
| a < zero = Nothing
| otherwise = let maxVal = (embed 2) `pow` (sizeVal (Proxy :: Proxy n)) - one
in if a > maxVal then Nothing else Just <<< UIntN $ a