@@ -0,0 +1,55 @@
1+{-# LANGUAGE FlexibleInstances #-}
2+{-# LANGUAGE TypeSynonymInstances #-}
3+module Web.PathPieces
4+ ( SinglePiece (..)
5+ , MultiPiece (..)
6+ ) where
7+
8+import Data.Int (Int64)
9+import qualified Data.Text as S
10+import qualified Data.Text.Lazy as L
11+import qualified Data.Text.Read
12+
13+class SinglePiece s where
14+ fromSinglePiece :: S.Text -> Maybe s
15+ toSinglePiece :: s -> S.Text
16+instance SinglePiece String where
17+ fromSinglePiece s = if S.null s then Nothing else Just (S.unpack s)
18+ toSinglePiece = S.pack
19+instance SinglePiece S.Text where
20+ fromSinglePiece s = if S.null s then Nothing else Just s
21+ toSinglePiece = id
22+instance SinglePiece L.Text where
23+ fromSinglePiece s = if S.null s then Nothing else Just (L.fromChunks [s])
24+ toSinglePiece = S.concat . L.toChunks
25+instance SinglePiece Integer where
26+ fromSinglePiece s =
27+ case Data.Text.Read.decimal s of
28+ Right (i, _) -> Just i
29+ Left _ -> Nothing
30+ toSinglePiece = S.pack . show
31+instance SinglePiece Int where
32+ fromSinglePiece s =
33+ case Data.Text.Read.decimal s of
34+ Right (i, _) -> Just i
35+ Left _ -> Nothing
36+ toSinglePiece = S.pack . show
37+instance SinglePiece Int64 where
38+ fromSinglePiece s =
39+ case Data.Text.Read.decimal s of
40+ Right (i, _) -> Just i
41+ Left _ -> Nothing
42+ toSinglePiece = S.pack . show
43+
44+class MultiPiece s where
45+ fromMultiPiece :: [S.Text] -> Maybe s
46+ toMultiPiece :: s -> [S.Text]
47+instance MultiPiece [String] where
48+ fromMultiPiece = Just . map S.unpack
49+ toMultiPiece = map S.pack
50+instance MultiPiece [S.Text] where
51+ fromMultiPiece = Just
52+ toMultiPiece = id
53+instance MultiPiece [L.Text] where
54+ fromMultiPiece = Just . map (L.fromChunks . return)
55+ toMultiPiece = map $ S.concat . L.toChunks