ihttp-0.1.0: Network/IHttp/Tools.hs
-- |
-- Module: Network.IHttp.Tools
-- Copyright: (c) 2010 Ertugrul Soeylemez
-- License: BSD3
-- Maintainer: Ertugrul Soeylemez <es@ertes.de>
-- Stability: experimental
--
-- Enumeratees and other tools.
{-# LANGUAGE ScopedTypeVariables #-}
module Network.IHttp.Tools
( -- * Character tools
asciiToUpper,
-- * Parser tools
parseIter,
parseFull
)
where
import Control.Exception as Ex
import Data.Attoparsec.Char8 as P
import Data.ByteString as B
import Data.Char
import Data.Enumerator as E
import Data.List as L
import Text.Printf
-- | Fast ASCII version of 'toUpper'.
asciiToUpper :: Char -> Char
asciiToUpper c
| c >= 'a' && c <= 'z' = chr $ ord c - 0x20
| otherwise = c
-- | Fully parse a string with the given parser. Throw an iteratee
-- error with the given error constructor, if it fails.
parseIter ::
(Exception ex, Monad m) =>
Parser b -> (String -> ex) -> ByteString -> Iteratee a m b
parseIter parser ex str =
case parseFull parser str of
Left err -> throwError (ex err)
Right res -> return res
-- | Fully parse a string with the given parser.
parseFull :: forall a. Parser a -> ByteString -> Either String a
parseFull parser str =
loop (parse parser str)
where
loop :: Result a -> Either String a
loop (Fail _ ctxs msg) = Left (printf "%s (%s)" (L.intercalate ": " ctxs) msg)
loop (Partial k) = loop (k B.empty)
loop (Done _ res) = Right res