on dacea01 help sign in
120 lines 2.5 kB history raw
1{-# LANGUAGE FlexibleInstances #-}
2{-# LANGUAGE OverloadedStrings #-}
3{-# LANGUAGE TypeSynonymInstances #-}
4module Servant.Common.Text where
6import Data.String.Conversions
7import Data.Int
8import Data.Text
9import Data.Text.Read
10import Data.Word
12-- | For getting values from url captures, get parameters
13class FromText a where
14 fromText :: Text -> Maybe a
16-- | For putting values in paths, get parameters
17class ToText a where
18 toText :: a -> Text
20instance FromText Text where
21 fromText = Just
23instance ToText Text where
24 toText = id
26instance FromText String where
27 fromText = Just . cs
29instance ToText String where
30 toText = cs
32instance FromText Bool where
33 fromText "true" = Just True
34 fromText "false" = Just False
35 fromText _ = Nothing
37instance ToText Bool where
38 toText True = "true"
39 toText False = "false"
41instance FromText Int where
42 fromText = runReader (signed decimal)
44instance ToText Int where
45 toText = cs . show
47instance FromText Int8 where
48 fromText = runReader (signed decimal)
50instance ToText Int8 where
51 toText = cs . show
53instance FromText Int16 where
54 fromText = runReader (signed decimal)
56instance ToText Int16 where
57 toText = cs . show
59instance FromText Int32 where
60 fromText = runReader (signed decimal)
62instance ToText Int32 where
63 toText = cs . show
65instance FromText Int64 where
66 fromText = runReader (signed decimal)
68instance ToText Int64 where
69 toText = cs . show
71instance FromText Word where
72 fromText = runReader decimal
74instance ToText Word where
75 toText = cs . show
77instance FromText Word8 where
78 fromText = runReader decimal
80instance ToText Word8 where
81 toText = cs . show
83instance FromText Word16 where
84 fromText = runReader decimal
86instance ToText Word16 where
87 toText = cs . show
89instance FromText Word32 where
90 fromText = runReader decimal
92instance ToText Word32 where
93 toText = cs . show
95instance FromText Word64 where
96 fromText = runReader decimal
98instance ToText Word64 where
99 toText = cs . show
101instance FromText Integer where
102 fromText = runReader decimal
104instance ToText Integer where
105 toText = cs . show
107instance FromText Double where
108 fromText = runReader rational
110instance ToText Double where
111 toText = cs . show
113instance FromText Float where
114 fromText = runReader rational
116instance ToText Float where
117 toText = cs . show
119runReader :: Reader a -> Text -> Maybe a
120runReader reader t = either (const Nothing) (Just . fst) $ reader t