1 -- |Utility functions used internally in the Lucu httpd. These
2 -- functions may be useful too for something else.
3 module Network.HTTP.Lucu.Utils
10 , parseWWWFormURLEncoded
14 import Control.Monad.Trans
21 -- |> splitBy (== ':') "ab:c:def"
22 -- > ==> ["ab", "c", "def"]
23 splitBy :: (a -> Bool) -> [a] -> [[a]]
24 splitBy isSeparator src
25 = case break isSeparator src
26 of (last , [] ) -> last : []
27 (first, sep:rest) -> first : splitBy isSeparator rest
29 -- |> joinWith ':' ["ab", "c", "def"]
31 joinWith :: [a] -> [[a]] -> [a]
33 = foldr (++) [] $ intersperse separator xs
35 -- |> trim (== '_') "__ab_c__def___"
37 trim :: (a -> Bool) -> [a] -> [a]
38 trim p = trimTail . trimHead
40 trimHead = dropWhile p
41 trimTail = reverse . trimHead . reverse
43 -- |@'noCaseEq' a b@ is equivalent to @(map toLower a) == (map toLower
45 noCaseEq :: String -> String -> Bool
47 = (map toLower a) == (map toLower b)
49 -- |@'isWhiteSpace' c@ is True iff c is one of SP, HT, CR and LF.
50 isWhiteSpace :: Char -> Bool
51 isWhiteSpace = flip elem " \t\r\n"
57 -- > ==> "\"ab\\\"c\""
58 quoteStr :: String -> String
59 quoteStr str = foldr (++) "" (["\""] ++ map quote str ++ ["\""])
61 quote :: Char -> String
66 -- |> parseWWWFormURLEncoded "aaa=bbb&ccc=ddd"
67 -- > ==> [("aaa", "bbb"), ("ccc", "ddd")]
68 parseWWWFormURLEncoded :: String -> [(String, String)]
69 parseWWWFormURLEncoded src
71 | otherwise = do pairStr <- splitBy (\ c -> c == ';' || c == '&') src
72 let pair = break (== '=') pairStr
73 return ( unEscapeString $ fst pair
74 , unEscapeString $ snd pair