Skip to content
This repository
Fetching contributors…

Cannot retrieve contributors at this time

file 36 lines (29 sloc) 1.214 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
module Snap.Util.Readable
  ( Readable(..)
  ) where

------------------------------------------------------------------------------
import Data.ByteString.Char8 (ByteString)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding
import Data.Text.Read


------------------------------------------------------------------------------
-- | Runs a 'Snap' monad action only when 'rqPathInfo' is empty.
class Readable a where
    fromBS :: Monad m => ByteString -> m a


------------------------------------------------------------------------------
-- | Fails if the input wasn't parsed completely.
checkComplete :: Monad m => (t, Text) -> m t
checkComplete (a,rest)
  | T.null rest = return a
  | otherwise = fail "Readable: could not parse completely"


instance Readable ByteString where
    fromBS = return
instance Readable Text where
    fromBS = return . decodeUtf8
instance Readable Int where
    fromBS = either fail checkComplete . decimal . decodeUtf8
instance Readable Integer where
    fromBS = either fail checkComplete . decimal . decodeUtf8
instance Readable Double where
    fromBS = either fail checkComplete . double . decodeUtf8
Something went wrong with that request. Please try again.