module Binrep.BLen.Internal.AsBLen where
import GHC.Natural ( minusNaturalMaybe )
import GHC.Num.Natural
import GHC.Exts
import Binrep.Util ( posIntToNat )
class AsBLen a where
safeBLenSub :: a -> a -> Maybe a
posIntToBLen :: Int -> a
wordToBLen# :: Word# -> a
natToBLen :: Natural -> a
instance AsBLen Int where
safeBLenSub :: Int -> Int -> Maybe Int
safeBLenSub Int
x Int
y = if Int
z forall a. Ord a => a -> a -> Bool
>= Int
0 then forall a. a -> Maybe a
Just Int
z else forall a. Maybe a
Nothing where z :: Int
z = Int
x forall a. Num a => a -> a -> a
- Int
y
{-# INLINE safeBLenSub #-}
posIntToBLen :: Int -> Int
posIntToBLen = forall a. a -> a
id
{-# INLINE posIntToBLen #-}
natToBLen :: Natural -> Int
natToBLen = \case
NS Word#
w# -> forall a. AsBLen a => Word# -> a
wordToBLen# Word#
w#
NB ByteArray#
_ -> forall a. HasCallStack => [Char] -> a
error [Char]
"TODO natural too large"
{-# INLINE natToBLen #-}
wordToBLen# :: Word# -> Int
wordToBLen# Word#
w# = Int# -> Int
I# (Word# -> Int#
word2Int# Word#
w#)
{-# INLINE wordToBLen# #-}
instance AsBLen Natural where
safeBLenSub :: Natural -> Natural -> Maybe Natural
safeBLenSub = Natural -> Natural -> Maybe Natural
minusNaturalMaybe
{-# INLINE safeBLenSub #-}
posIntToBLen :: Int -> Natural
posIntToBLen = Int -> Natural
posIntToNat
{-# INLINE posIntToBLen #-}
wordToBLen# :: Word# -> Natural
wordToBLen# = Word# -> Natural
NS
{-# INLINE wordToBLen# #-}
natToBLen :: Natural -> Natural
natToBLen = forall a. a -> a
id
{-# INLINE natToBLen #-}