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

-- | Utilities for numbers.
module Util.Num
  ( fromIntegralChecked
  ) where

-- | Convert between integral types, checking for overflows/underflows.
fromIntegralChecked :: (Integral a, Integral b) => a -> Either Text b
fromIntegralChecked :: a -> Either Text b
fromIntegralChecked a :: a
a =
  let b :: b
b = a -> b
forall a b. (Integral a, Num b) => a -> b
fromIntegral a
a
  in if a -> Integer
forall a. Integral a => a -> Integer
toInteger a
a Integer -> Integer -> Bool
forall a. Eq a => a -> a -> Bool
== b -> Integer
forall a. Integral a => a -> Integer
toInteger b
b
    then b -> Either Text b
forall a b. b -> Either a b
Right b
b
    else Text -> Either Text b
forall a b. a -> Either a b
Left
      if a -> Integer
forall a. Integral a => a -> Integer
toInteger a
a Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> b -> Integer
forall a. Integral a => a -> Integer
toInteger b
b
        then "Numeric overflow"
        else "Numeric underflow"