git.iko.soy/typeable/http-api-data
on master help sign in
Fix some errors cases #7
4922b9bMichael Snoyman
Web/PathPieces.hs+10−9
@@ -1,4 +1,4 @@
1−{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-}
1+{-# LANGUAGE FlexibleInstances, TypeSynonymInstances, OverloadedStrings #-}
2module Web.PathPieces
2module Web.PathPieces
3 ( PathPiece (..)
3 ( PathPiece (..)
4 , PathMultiPiece (..)
4 , PathMultiPiece (..)
@@ -14,6 +14,7 @@ import qualified Data.Text as S
14import qualified Data.Text.Lazy as L
14import qualified Data.Text.Lazy as L
15import qualified Data.Text.Read
15import qualified Data.Text.Read
16import Data.Time (Day)
16import Data.Time (Day)
17+import Control.Exception (assert)
17
18
18class PathPiece s where
19class PathPiece s where
19 fromPathPiece :: S.Text -> Maybe s
20 fromPathPiece :: S.Text -> Maybe s
@@ -34,29 +35,29 @@ instance PathPiece L.Text where
34instance PathPiece Integer where
35instance PathPiece Integer where
35 fromPathPiece s =
36 fromPathPiece s =
36 case Data.Text.Read.signed Data.Text.Read.decimal s of
37 case Data.Text.Read.signed Data.Text.Read.decimal s of
37− Right (i, _) -> Just i
38+ Right (i, "") -> Just i
38− Left _ -> Nothing
39+ _ -> Nothing
39 toPathPiece = S.pack . show
40 toPathPiece = S.pack . show
40
41
41instance PathPiece Int where
42instance PathPiece Int where
42 fromPathPiece s =
43 fromPathPiece s =
43 case Data.Text.Read.signed Data.Text.Read.decimal s of
44 case Data.Text.Read.signed Data.Text.Read.decimal s of
44− Right (i, _) -> Just i
45+ Right (i, "") -> Just i
45− Left _ -> Nothing
46+ _ -> Nothing
46 toPathPiece = S.pack . show
47 toPathPiece = S.pack . show
47
48
48instance PathPiece Bool where
49instance PathPiece Bool where
49 fromPathPiece t =
50 fromPathPiece t =
50− case reads $ S.unpack t of
51+ case filter (null . snd) $ reads $ S.unpack t of
51− [(a,"")] -> Just a
52+ (a, s):_ -> assert (null s) (Just a)
52 _ -> Nothing
53 _ -> Nothing
53 toPathPiece = S.pack . show
54 toPathPiece = S.pack . show
54
55
55instance PathPiece Int64 where
56instance PathPiece Int64 where
56 fromPathPiece s =
57 fromPathPiece s =
57 case Data.Text.Read.signed Data.Text.Read.decimal s of
58 case Data.Text.Read.signed Data.Text.Read.decimal s of
58− Right (i, _) -> Just i
59+ Right (i, "") -> Just i
59− Left _ -> Nothing
60+ _ -> Nothing
60 toPathPiece = S.pack . show
61 toPathPiece = S.pack . show
61
62
62instance PathPiece Day where
63instance PathPiece Day where
test/main.hs+3
@@ -72,3 +72,6 @@ spec = do
72
72
73 prop "toPathMultiPiece <=> fromPathMultiPiece String" $ \(p::[T.Text]) ->
73 prop "toPathMultiPiece <=> fromPathMultiPiece String" $ \(p::[T.Text]) ->
74 p == (fromJust . fromPathMultiPiece . toPathMultiPiece) p
74 p == (fromJust . fromPathMultiPiece . toPathMultiPiece) p
75+
76+ it "bad ints are rejected" $ fromPathPiece (T.pack "123hello")
77+ `shouldBe` (Nothing :: Maybe Int)