Skip to content

Commit

Permalink
Cleaned up code style.
Browse files Browse the repository at this point in the history
  • Loading branch information
mightybyte committed Dec 12, 2010
1 parent 99b3311 commit 0beeba4
Show file tree
Hide file tree
Showing 8 changed files with 134 additions and 86 deletions.
21 changes: 20 additions & 1 deletion src/Data/CIByteString.hs
@@ -1,6 +1,7 @@
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}

------------------------------------------------------------------------------
-- | "Data.CIByteString" is a module containing 'CIByteString', a wrapper for
-- 'ByteString' which provides case-insensitive (ASCII-wise) 'Ord' and 'Eq'
-- instances.
Expand All @@ -11,7 +12,8 @@
--
-- @
-- \> let a = \"Foo\" in
-- putStrLn $ (show $ unCI a) ++ \"==\\\"FoO\\\" is \" ++ show (a == \"FoO\")
-- putStrLn $ (show $ unCI a) ++ \"==\\\"FoO\\\" is \" ++
-- show (a == \"FoO\")
-- \"Foo\"==\"FoO\" is True
-- @

Expand All @@ -22,6 +24,8 @@ module Data.CIByteString
, ciToLower
) where


------------------------------------------------------------------------------
-- for IsString instance
import Data.ByteString.Char8 ()
import Data.ByteString (ByteString)
Expand All @@ -31,30 +35,45 @@ import Data.Char
import Data.String


------------------------------------------------------------------------------
-- | A case-insensitive newtype wrapper for 'ByteString'
data CIByteString = CIByteString { unCI :: !ByteString
, _lowercased :: !ByteString }


------------------------------------------------------------------------------
toCI :: ByteString -> CIByteString
toCI s = CIByteString s t
where
t = lowercase s


------------------------------------------------------------------------------
ciToLower :: CIByteString -> ByteString
ciToLower = _lowercased


------------------------------------------------------------------------------
instance Show CIByteString where
show (CIByteString s _) = show s


------------------------------------------------------------------------------
lowercase :: ByteString -> ByteString
lowercase = S.map (c2w . toLower . w2c)


------------------------------------------------------------------------------
instance Eq CIByteString where
(CIByteString _ a) == (CIByteString _ b) = a == b
(CIByteString _ a) /= (CIByteString _ b) = a /= b


------------------------------------------------------------------------------
instance Ord CIByteString where
(CIByteString _ a) <= (CIByteString _ b) = a <= b


------------------------------------------------------------------------------
instance IsString CIByteString where
fromString = toCI . fromString
49 changes: 26 additions & 23 deletions src/Snap/Internal/Http/Types.hs
Expand Up @@ -98,8 +98,9 @@ class HasHeaders a where


------------------------------------------------------------------------------
-- | Adds a header key-value-pair to the 'HasHeaders' datatype. If a header with
-- the same name already exists, the new value is appended to the headers list.
-- | Adds a header key-value-pair to the 'HasHeaders' datatype. If a header
-- with the same name already exists, the new value is appended to the headers
-- list.
addHeader :: (HasHeaders a) => CIByteString -> ByteString -> a -> a
addHeader k v = updateHeaders $ Map.insertWith' (++) k [v]

Expand Down Expand Up @@ -222,30 +223,30 @@ data Request = Request
, rqCookies :: [Cookie]


-- | We'll be doing web components (or \"snaplets\") for version 0.2. The
-- \"snaplet path\" refers to the place on the URL where your containing
-- snaplet is hung. The value of 'rqSnapletPath' is either @\"\"@ (at the
-- top-level context) or is a path beginning with a slash, but not ending
-- with one.
-- | We'll be doing web components (or \"snaplets\") for version 0.2.
-- The \"snaplet path\" refers to the place on the URL where your
-- containing snaplet is hung. The value of 'rqSnapletPath' is either
-- @\"\"@ (at the top-level context) or is a path beginning with a
-- slash, but not ending with one.
--
-- An identity is that:
--
-- > rqURI r == 'S.concat' [ rqSnapletPath r
-- > , rqContextPath r
-- > , rqPathInfo r ]
--
-- note that until we introduce snaplets in v0.2, 'rqSnapletPath' will be
-- \"\"
-- note that until we introduce snaplets in v0.2, 'rqSnapletPath' will
-- be \"\"
, rqSnapletPath :: !ByteString

-- | Handlers can (/will be; --ed/) be hung on a @URI@ \"entry point\";
-- this is called the \"context path\". If a handler is hung on the
-- context path @\"\/foo\/\"@, and you request @\"\/foo\/bar\"@, the value
-- of 'rqPathInfo' will be @\"bar\"@.
-- context path @\"\/foo\/\"@, and you request @\"\/foo\/bar\"@, the
-- value of 'rqPathInfo' will be @\"bar\"@.
, rqPathInfo :: !ByteString

-- | The \"context path\" of the request; catenating 'rqContextPath', and
-- 'rqPathInfo' should get you back to the original 'rqURI'. The
-- | The \"context path\" of the request; catenating 'rqContextPath',
-- and 'rqPathInfo' should get you back to the original 'rqURI'. The
-- 'rqContextPath' always begins and ends with a slash (@\"\/\"@)
-- character, and represents the path (relative to your
-- component\/snaplet) you took to get to your handler.
Expand Down Expand Up @@ -429,8 +430,8 @@ instance HasHeaders Response where
------------------------------------------------------------------------------
-- | Looks up the value(s) for the given named parameter. Parameters initially
-- come from the request's query string and any decoded POST body (if the
-- request's @Content-Type@ is @application\/x-www-form-urlencoded@). Parameter
-- values can be modified within handlers using "rqModifyParams".
-- request's @Content-Type@ is @application\/x-www-form-urlencoded@).
-- Parameter values can be modified within handlers using "rqModifyParams".
rqParam :: ByteString -- ^ parameter name to look up
-> Request -- ^ HTTP request
-> Maybe [ByteString]
Expand All @@ -439,8 +440,8 @@ rqParam k rq = Map.lookup k $ rqParams rq


------------------------------------------------------------------------------
-- | Modifies the parameters mapping (which is a @Map ByteString ByteString@) in
-- a 'Request' using the given function.
-- | Modifies the parameters mapping (which is a @Map ByteString ByteString@)
-- in a 'Request' using the given function.
rqModifyParams :: (Params -> Params) -> Request -> Request
rqModifyParams f r = r { rqParams = p }
where
Expand All @@ -449,7 +450,8 @@ rqModifyParams f r = r { rqParams = p }


------------------------------------------------------------------------------
-- | Writes a key-value pair to the parameters mapping within the given request.
-- | Writes a key-value pair to the parameters mapping within the given
-- request.
rqSetParam :: ByteString -- ^ parameter name
-> [ByteString] -- ^ parameter values
-> Request -- ^ request
Expand Down Expand Up @@ -529,21 +531,22 @@ addCookie (Cookie k v mbExpTime mbDomain mbPath) = updateHeaders f
path = maybe "" (S.append "; path=") mbPath
domain = maybe "" (S.append "; domain=") mbDomain
exptime = maybe "" (S.append "; expires=" . fmt) mbExpTime
fmt = fromStr . formatTime defaultTimeLocale "%a, %d-%b-%Y %H:%M:%S GMT"
fmt = fromStr .
formatTime defaultTimeLocale "%a, %d-%b-%Y %H:%M:%S GMT"


------------------------------------------------------------------------------
-- | A note here: if you want to set the @Content-Length@ for the response,
-- Snap forces you to do it with this function rather than by setting it in the
-- headers; the @Content-Length@ in the headers will be ignored.
-- Snap forces you to do it with this function rather than by setting it in
-- the headers; the @Content-Length@ in the headers will be ignored.
--
-- The reason for this is that Snap needs to look up the value of
-- @Content-Length@ for each request, and looking the string value up in the
-- headers and parsing the number out of the text will be too expensive.
--
-- If you don't set a content length in your response, HTTP keep-alive will be
-- disabled for HTTP\/1.0 clients, forcing a @Connection: close@. For HTTP\/1.1
-- clients, Snap will switch to the chunked transfer encoding if
-- disabled for HTTP\/1.0 clients, forcing a @Connection: close@. For
-- HTTP\/1.1 clients, Snap will switch to the chunked transfer encoding if
-- @Content-Length@ is not specified.
setContentLength :: Int64 -> Response -> Response
setContentLength l r = r { rspContentLength = Just l }
Expand Down
3 changes: 2 additions & 1 deletion src/Snap/Internal/Iteratee/Debug.hs
Expand Up @@ -54,7 +54,8 @@ iterateeDebugWrapper name iter = do

where
whatWasReturn (Continue _) = debug $ name ++ ": continue"
whatWasReturn (Yield _ z) = debug $ name ++ ": yield, with remainder " ++ show z
whatWasReturn (Yield _ z) = debug $ name ++ ": yield, with remainder "
++ show z
whatWasReturn (Error e) = debug $ name ++ ": error, with " ++ show e

check (Continue k) = continue $ f k
Expand Down
17 changes: 10 additions & 7 deletions src/Snap/Internal/Routing.hs
Expand Up @@ -36,9 +36,11 @@ triggering its fallback. It's NoRoute, so we go to the nearest parent
fallback and try that, which is the baz action.
-}
data Route a m = Action ((MonadSnap m) => m a) -- wraps a 'Snap' action
| Capture ByteString (Route a m) (Route a m) -- captures the dir in a param
| Dir (Map.Map ByteString (Route a m)) (Route a m) -- match on a dir
data Route a m = Action ((MonadSnap m) => m a) -- wraps a 'Snap' action
-- captures the dir in a param
| Capture ByteString (Route a m) (Route a m)
-- match on a dir
| Dir (Map.Map ByteString (Route a m)) (Route a m)
| NoRoute


Expand Down Expand Up @@ -137,8 +139,8 @@ routeEarliestNC r n = case r of
--
-- > [ ("a", h1), ("a/b", h2), ("a/:x", h3) ]
--
-- a request for \"@\/a\/b@\" will go to @h2@, \"@\/a\/s@\" for any /s/ will go
-- to @h3@, and \"@\/a@\" will go to @h1@.
-- a request for \"@\/a\/b@\" will go to @h2@, \"@\/a\/s@\" for any /s/ will
-- go to @h3@, and \"@\/a@\" will go to @h1@.
--
-- The following example matches \"@\/article@\" to an article index,
-- \"@\/login@\" to a login, and \"@\/article\/...@\" to an article renderer.
Expand All @@ -156,8 +158,8 @@ route rts = do


------------------------------------------------------------------------------
-- | The 'routeLocal' function is the same as 'route'', except it doesn't change
-- the request's context path. This is useful if you want to route to a
-- | The 'routeLocal' function is the same as 'route'', except it doesn't
-- change the request's context path. This is useful if you want to route to a
-- particular handler but you want that handler to receive the 'rqPathInfo' as
-- it is.
routeLocal :: MonadSnap m => [(ByteString, m a)] -> m a
Expand All @@ -173,6 +175,7 @@ routeLocal rts = do
where
rts' = mconcat (map pRoute rts)


------------------------------------------------------------------------------
splitPath :: ByteString -> [ByteString]
splitPath = B.splitWith (== (c2w '/'))
Expand Down
58 changes: 30 additions & 28 deletions src/Snap/Internal/Types.hs
Expand Up @@ -78,8 +78,8 @@ import Snap.Internal.Iteratee.Debug
> r <- getResponse
> finishWith r
then any subsequent processing will be skipped and supplied 'Response' value
will be returned from 'runSnap' as-is.
then any subsequent processing will be skipped and supplied 'Response'
value will be returned from 'runSnap' as-is.
6. access to the 'IO' monad through a 'MonadIO' instance:
Expand All @@ -103,9 +103,11 @@ class (Monad m, MonadIO m, MonadCatchIO m, MonadPlus m, Functor m,
Applicative m, Alternative m) => MonadSnap m where
liftSnap :: Snap a -> m a


------------------------------------------------------------------------------
newtype Snap a = Snap {
unSnap :: StateT SnapState (Iteratee ByteString IO) (Maybe (Either Response a))
unSnap :: StateT SnapState (Iteratee ByteString IO)
(Maybe (Either Response a))
}


Expand Down Expand Up @@ -228,10 +230,10 @@ getRequestBody = liftM L.fromChunks $ runRequestBody consume


------------------------------------------------------------------------------
-- | Normally Snap is careful to ensure that the request body is fully consumed
-- after your web handler runs, but before the 'Response' enumerator is
-- streamed out the socket. If you want to transform the request body into some
-- output in O(1) space, you should use this function.
-- | Normally Snap is careful to ensure that the request body is fully
-- consumed after your web handler runs, but before the 'Response' enumerator
-- is streamed out the socket. If you want to transform the request body into
-- some output in O(1) space, you should use this function.
--
-- Note that upon calling this function, response processing finishes early as
-- if you called 'finishWith'. Make sure you set any content types, headers,
Expand Down Expand Up @@ -337,10 +339,10 @@ dir = pathWith f


------------------------------------------------------------------------------
-- | Runs a 'Snap' monad action only for requests where 'rqPathInfo' is exactly
-- equal to the given string. If the path matches, locally sets 'rqContextPath'
-- to the old value of 'rqPathInfo', sets 'rqPathInfo'=\"\", and runs the given
-- handler.
-- | Runs a 'Snap' monad action only for requests where 'rqPathInfo' is
-- exactly equal to the given string. If the path matches, locally sets
-- 'rqContextPath' to the old value of 'rqPathInfo', sets 'rqPathInfo'=\"\",
-- and runs the given handler.
path :: MonadSnap m
=> ByteString -- ^ path to match against
-> m a -- ^ handler to run
Expand Down Expand Up @@ -417,9 +419,9 @@ modifyResponse f = liftSnap $
------------------------------------------------------------------------------
-- | Performs a redirect by setting the @Location@ header to the given target
-- URL/path and the status code to 302 in the 'Response' object stored in a
-- 'Snap' monad. Note that the target URL is not validated in any way. Consider
-- using 'redirect\'' instead, which allows you to choose the correct status
-- code.
-- 'Snap' monad. Note that the target URL is not validated in any way.
-- Consider using 'redirect\'' instead, which allows you to choose the correct
-- status code.
redirect :: MonadSnap m => ByteString -> m ()
redirect target = redirect' target 302
{-# INLINE redirect #-}
Expand Down Expand Up @@ -461,8 +463,8 @@ addToOutput enum = modifyResponse $ modifyResponseBody (>==> enum)


------------------------------------------------------------------------------
-- | Adds the given strict 'ByteString' to the body of the 'Response' stored in
-- the 'Snap' monad state.
-- | Adds the given strict 'ByteString' to the body of the 'Response' stored
-- in the 'Snap' monad state.
--
-- Warning: This function is intentionally non-strict. If any pure
-- exceptions are raised by the expression creating the 'ByteString',
Expand All @@ -472,8 +474,8 @@ writeBS s = addToOutput $ enumBS s


------------------------------------------------------------------------------
-- | Adds the given lazy 'L.ByteString' to the body of the 'Response' stored in
-- the 'Snap' monad state.
-- | Adds the given lazy 'L.ByteString' to the body of the 'Response' stored
-- in the 'Snap' monad state.
--
-- Warning: This function is intentionally non-strict. If any pure
-- exceptions are raised by the expression creating the 'ByteString',
Expand All @@ -483,8 +485,8 @@ writeLBS s = addToOutput $ enumLBS s


------------------------------------------------------------------------------
-- | Adds the given strict 'T.Text' to the body of the 'Response' stored in the
-- 'Snap' monad state.
-- | Adds the given strict 'T.Text' to the body of the 'Response' stored in
-- the 'Snap' monad state.
--
-- Warning: This function is intentionally non-strict. If any pure
-- exceptions are raised by the expression creating the 'ByteString',
Expand Down Expand Up @@ -512,23 +514,23 @@ writeLazyText s = writeLBS $ LT.encodeUtf8 s
-- 'sendFile', Snap will use the efficient @sendfile()@ system call on
-- platforms that support it.
--
-- If the response body is modified (using 'modifyResponseBody'), the file will
-- be read using @mmap()@.
-- If the response body is modified (using 'modifyResponseBody'), the file
-- will be read using @mmap()@.
sendFile :: (MonadSnap m) => FilePath -> m ()
sendFile f = modifyResponse $ \r -> r { rspBody = SendFile f Nothing }


------------------------------------------------------------------------------
-- | Sets the output to be the contents of the specified file, within the given
-- (start,end) range.
-- | Sets the output to be the contents of the specified file, within the
-- given (start,end) range.
--
-- Calling 'sendFilePartial' will overwrite any output queued to be sent in the
-- 'Response'. If the response body is not modified after the call to
-- Calling 'sendFilePartial' will overwrite any output queued to be sent in
-- the 'Response'. If the response body is not modified after the call to
-- 'sendFilePartial', Snap will use the efficient @sendfile()@ system call on
-- platforms that support it.
--
-- If the response body is modified (using 'modifyResponseBody'), the file will
-- be read using @mmap()@.
-- If the response body is modified (using 'modifyResponseBody'), the file
-- will be read using @mmap()@.
sendFilePartial :: (MonadSnap m) => FilePath -> (Int64,Int64) -> m ()
sendFilePartial f rng = modifyResponse $ \r ->
r { rspBody = SendFile f (Just rng) }
Expand Down

0 comments on commit 0beeba4

Please sign in to comment.