Commits

wren romano committed 3ac4fcc

Data.Attoparsec.Char8: added nonzeroDecimal

Comments (0)

Files changed (1)

Data/Attoparsec/Char8.hs

 
     -- * Numeric parsers
     , decimal
+    , nonzeroDecimal
     , hexadecimal
     , signed
     , double
 {-# SPECIALISE decimal :: Parser Word32 #-}
 {-# SPECIALISE decimal :: Parser Word64 #-}
 
+-- | Like 'decimal' except that it disallows leading zeros, and
+-- therefore the zero value as well.
+nonzeroDecimal :: Integral a => Parser a
+nonzeroDecimal =
+    B8.foldl' (\acc w -> acc * 10 + digit2integral w)
+        <$> (digit2integral <$> A.satisfy isNonzeroDigit_w8)
+        <*> A.takeWhile isDigit_w8
+    where
+    digit2integral    w = fromIntegral (w - 0x30)
+    isNonzeroDigit_w8 w = w <= 0x39 && w >= 0x31
+{-# SPECIALISE nonzeroDecimal :: Parser Int     #-}
+{-# SPECIALISE nonzeroDecimal :: Parser Int8    #-}
+{-# SPECIALISE nonzeroDecimal :: Parser Int16   #-}
+{-# SPECIALISE nonzeroDecimal :: Parser Int32   #-}
+{-# SPECIALISE nonzeroDecimal :: Parser Int64   #-}
+{-# SPECIALISE nonzeroDecimal :: Parser Integer #-}
+{-# SPECIALISE nonzeroDecimal :: Parser Word    #-}
+{-# SPECIALISE nonzeroDecimal :: Parser Word8   #-}
+{-# SPECIALISE nonzeroDecimal :: Parser Word16  #-}
+{-# SPECIALISE nonzeroDecimal :: Parser Word32  #-}
+{-# SPECIALISE nonzeroDecimal :: Parser Word64  #-}
+
+
 -- | Parse a number with an optional leading @\'+\'@ or @\'-\'@ sign
 -- character.
 signed :: Num a => Parser a -> Parser a