{-# OPTIONS_GHC -fno-warn-orphans #-}
{-
	Copyright (C) 2018 Dr. Alistair Ward

	This file is part of BishBosh.

	BishBosh is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	BishBosh is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with BishBosh.  If not, see <http://www.gnu.org/licenses/>.
-}
{- |
 [@AUTHOR@]	Dr. Alistair Ward

 [@DESCRIPTION@]
-}

module BishBosh.Data.Integral(
-- * Functions
	stringToUnsignedDecimal
) where

import qualified	Data.Char
import qualified	Data.Int
import qualified	Data.List
import qualified	Data.Word
import qualified	Text.XML.HXT.Arrow.Pickle	as HXT

instance HXT.XmlPickler Data.Int.Int8 where
	xpickle :: PU Int8
xpickle	= PU Int8
forall a. (Read a, Show a) => PU a
HXT.xpPrim

instance HXT.XmlPickler Data.Int.Int16 where
	xpickle :: PU Int16
xpickle	= PU Int16
forall a. (Read a, Show a) => PU a
HXT.xpPrim

instance HXT.XmlPickler Data.Int.Int32 where
	xpickle :: PU Int32
xpickle	= PU Int32
forall a. (Read a, Show a) => PU a
HXT.xpPrim

instance HXT.XmlPickler Data.Word.Word8 where
	xpickle :: PU Word8
xpickle	= PU Word8
forall a. (Read a, Show a) => PU a
HXT.xpPrim

instance HXT.XmlPickler Data.Word.Word16 where
	xpickle :: PU Word16
xpickle	= PU Word16
forall a. (Read a, Show a) => PU a
HXT.xpPrim

instance HXT.XmlPickler Data.Word.Word32 where
	xpickle :: PU Word32
xpickle	= PU Word32
forall a. (Read a, Show a) => PU a
HXT.xpPrim

instance HXT.XmlPickler Data.Word.Word where
	xpickle :: PU Word
xpickle	= PU Word
forall a. (Read a, Show a) => PU a
HXT.xpPrim

{- |
	* N.B. much faster than the instance of 'Read' for the integral type. TODO: compare with 'Numeric.readDec'.

	* N.B. ignores any leading zeroes.

	* CAVEAT: 'Data.Char.digitToInt' throws an exception if it receives a character which isn't a digit.

-}
stringToUnsignedDecimal :: Num i => String -> i
stringToUnsignedDecimal :: String -> i
stringToUnsignedDecimal	= Int -> i
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int -> i) -> (String -> Int) -> String -> i
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Int -> Char -> Int) -> Int -> String -> Int
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
Data.List.foldl' (\Int
i -> (Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
10 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
i) (Int -> Int) -> (Char -> Int) -> Char -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> Int
Data.Char.digitToInt) Int
0