From 4a2ee5ec888cb525d9777b391fe54012808d195e Mon Sep 17 00:00:00 2001
From: Ramakrishnan Muthukrishnan <ram@rkrishnan.org>
Date: Wed, 4 Feb 2015 09:55:13 +0530
Subject: [PATCH] correctly handle negative/zero integers

---
 src/Bencode.hs | 17 +++++++++++++----
 1 file changed, 13 insertions(+), 4 deletions(-)

diff --git a/src/Bencode.hs b/src/Bencode.hs
index 87da970..adc6d1a 100644
--- a/src/Bencode.hs
+++ b/src/Bencode.hs
@@ -32,16 +32,25 @@ bencStr = do _ <- spaces
              s <- count (read ds) anyChar
              return (BC.pack s)
 
+-- | parse integers
+--
+-- >>> parse bencInt "Bint" (BC.pack "i42e")
+-- Right 42
+-- >>> parse bencInt "Bint" (BC.pack "i1e")
+-- Right 1
+-- >>> parse bencInt "Bint" (BC.pack "i0e")
+-- Right 0
+-- >>> parse bencInt "Bint" (BC.pack "i-1e")
+-- Right (-1)
 bencInt :: ParsecBS.Parser Integer
 bencInt = do _ <- spaces
              ds <- between (char 'i') (char 'e') numbers
              return (read ds)
                where numbers = do d' <- (char '-' <|> digit)
-                                  if d' == '0'
+                                  ds' <- many digit
+                                  if d' == '0' && ds' /= []
                                     then unexpected "numbers cannot be left-padded with zeros"
-                                    else
-                                      do ds' <- many1 digit
-                                         return (d' : ds')
+                                    else return (d' : ds')
 
 bencParser :: ParsecBS.Parser BVal
 bencParser = Bstr <$> bencStr <|>
-- 
2.45.2