on 98e02ea help sign in
130 lines 2.8 kB history raw
1{-# LANGUAGE FlexibleInstances #-}
2{-# LANGUAGE OverloadedStrings #-}
3{-# LANGUAGE TypeSynonymInstances #-}
4module Servant.Common.Text
5 ( FromText(..)
6 , ToText(..)
7 ) where
9import Data.String.Conversions ( cs )
10import Data.Int ( Int8, Int16, Int32, Int64 )
11import Data.Text ( Text )
12import Data.Text.Read ( rational, signed, decimal, Reader )
13import Data.Word ( Word, Word8, Word16, Word32, Word64 )
15-- | For getting values from url captures and query string parameters
16class FromText a where
17 fromText :: Text -> Maybe a
19-- | For putting values in paths and query string parameters
20class ToText a where
21 toText :: a -> Text
23instance FromText Text where
24 fromText = Just
26instance ToText Text where
27 toText = id
29instance FromText String where
30 fromText = Just . cs
32instance ToText String where
33 toText = cs
35-- |
36-- > fromText "true" = Just True
37-- > fromText "false" = Just False
38-- > fromText _ = Nothing
39instance FromText Bool where
40 fromText "true" = Just True
41 fromText "false" = Just False
42 fromText _ = Nothing
44-- |
45-- > toText True = "true"
46-- > toText False = "false"
47instance ToText Bool where
48 toText True = "true"
49 toText False = "false"
51instance FromText Int where
52 fromText = runReader (signed decimal)
54instance ToText Int where
55 toText = cs . show
57instance FromText Int8 where
58 fromText = runReader (signed decimal)
60instance ToText Int8 where
61 toText = cs . show
63instance FromText Int16 where
64 fromText = runReader (signed decimal)
66instance ToText Int16 where
67 toText = cs . show
69instance FromText Int32 where
70 fromText = runReader (signed decimal)
72instance ToText Int32 where
73 toText = cs . show
75instance FromText Int64 where
76 fromText = runReader (signed decimal)
78instance ToText Int64 where
79 toText = cs . show
81instance FromText Word where
82 fromText = runReader decimal
84instance ToText Word where
85 toText = cs . show
87instance FromText Word8 where
88 fromText = runReader decimal
90instance ToText Word8 where
91 toText = cs . show
93instance FromText Word16 where
94 fromText = runReader decimal
96instance ToText Word16 where
97 toText = cs . show
99instance FromText Word32 where
100 fromText = runReader decimal
102instance ToText Word32 where
103 toText = cs . show
105instance FromText Word64 where
106 fromText = runReader decimal
108instance ToText Word64 where
109 toText = cs . show
111instance FromText Integer where
112 fromText = runReader decimal
114instance ToText Integer where
115 toText = cs . show
117instance FromText Double where
118 fromText = runReader rational
120instance ToText Double where
121 toText = cs . show
123instance FromText Float where
124 fromText = runReader rational
126instance ToText Float where
127 toText = cs . show
129runReader :: Reader a -> Text -> Maybe a
130runReader reader t = either (const Nothing) (Just . fst) $ reader t