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
13 import Data.List hiding (last)
15 import Prelude hiding (last)
17 -- |> splitBy (== ':') "ab:c:def"
18 -- > ==> ["ab", "c", "def"]
19 splitBy :: (a -> Bool) -> [a] -> [[a]]
21 = case break isSep src
22 of (last , [] ) -> last : []
23 (first, _sep:rest) -> first : splitBy isSep rest
25 -- |> joinWith ":" ["ab", "c", "def"]
27 joinWith :: [a] -> [[a]] -> [a]
29 = separator `seq` xs `seq`
30 foldr (++) [] $! intersperse separator xs
32 -- |> trim (== '_') "__ab_c__def___"
34 trim :: (a -> Bool) -> [a] -> [a]
35 trim p = p `seq` trimTail . trimHead
37 trimHead = dropWhile p
38 trimTail = reverse . trimHead . reverse
40 -- |@'isWhiteSpace' c@ is 'Prelude.True' iff c is one of SP, HT, CR
42 isWhiteSpace :: Char -> Bool
43 isWhiteSpace ' ' = True
44 isWhiteSpace '\t' = True
45 isWhiteSpace '\r' = True
46 isWhiteSpace '\n' = True
47 isWhiteSpace _ = False
48 {-# INLINE isWhiteSpace #-}
54 -- > ==> "\"ab\\\"c\""
55 quoteStr :: String -> String
56 quoteStr str = str `seq`
57 foldr (++) "" (["\""] ++ map quote str ++ ["\""])
59 quote :: Char -> String
64 -- |> parseWWWFormURLEncoded "aaa=bbb&ccc=ddd"
65 -- > ==> [("aaa", "bbb"), ("ccc", "ddd")]
66 parseWWWFormURLEncoded :: String -> [(String, String)]
67 parseWWWFormURLEncoded src
69 | otherwise = do pairStr <- splitBy (\ c -> c == ';' || c == '&') src
70 let (key, value) = break (== '=') pairStr
71 return ( unEscapeString key
72 , unEscapeString $ case value of