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
9 , parseWWWFormURLEncoded
14 import Data.List hiding (last)
16 import Prelude hiding (last)
18 -- |> splitBy (== ':') "ab:c:def"
19 -- > ==> ["ab", "c", "def"]
20 splitBy :: (a -> Bool) -> [a] -> [[a]]
22 = case break isSep src
23 of (last , [] ) -> [last]
24 (first, _sep:rest) -> first : splitBy isSep rest
26 -- |> joinWith ":" ["ab", "c", "def"]
28 joinWith :: [a] -> [[a]] -> [a]
29 joinWith = (join .) . intersperse
31 -- |> trim (== '_') "__ab_c__def___"
33 trim :: (a -> Bool) -> [a] -> [a]
34 trim !p = trimTail . trimHead
36 trimHead = dropWhile p
37 trimTail = reverse . trimHead . reverse
39 -- |@'isWhiteSpace' c@ is 'Prelude.True' iff c is one of SP, HT, CR
41 isWhiteSpace :: Char -> Bool
42 isWhiteSpace ' ' = True
43 isWhiteSpace '\t' = True
44 isWhiteSpace '\r' = True
45 isWhiteSpace '\n' = True
46 isWhiteSpace _ = False
47 {-# INLINE isWhiteSpace #-}
53 -- > ==> "\"ab\\\"c\""
54 quoteStr :: String -> String
55 quoteStr !str = concat (["\""] ++ map quote str ++ ["\""])
57 quote :: Char -> String
62 -- |> parseWWWFormURLEncoded "aaa=bbb&ccc=ddd"
63 -- > ==> [("aaa", "bbb"), ("ccc", "ddd")]
64 parseWWWFormURLEncoded :: String -> [(String, String)]
65 parseWWWFormURLEncoded src
67 | otherwise = do pairStr <- splitBy (\ c -> c == ';' || c == '&') src
68 let (key, value) = break (== '=') pairStr
69 return ( unEscapeString key
70 , unEscapeString $ case value of