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
17 -- |> splitBy (== ':') "ab:c:def"
18 -- > ==> ["ab", "c", "def"]
19 splitBy :: (a -> Bool) -> [a] -> [[a]]
20 splitBy isSeparator src
22 case break isSeparator src
23 of (last , [] ) -> last : []
24 (first, sep:rest) -> first : splitBy isSeparator rest
26 -- |> joinWith ":" ["ab", "c", "def"]
28 joinWith :: [a] -> [[a]] -> [a]
30 = separator `seq` xs `seq`
31 foldr (++) [] $! intersperse separator xs
33 -- |> trim (== '_') "__ab_c__def___"
35 trim :: (a -> Bool) -> [a] -> [a]
36 trim p = p `seq` trimTail . trimHead
38 trimHead = dropWhile p
39 trimTail = reverse . trimHead . reverse
41 -- |@'isWhiteSpace' c@ is 'Prelude.True' iff c is one of SP, HT, CR
43 isWhiteSpace :: Char -> Bool
44 isWhiteSpace ' ' = True
45 isWhiteSpace '\t' = True
46 isWhiteSpace '\r' = True
47 isWhiteSpace '\n' = True
48 isWhiteSpace _ = False
49 {-# INLINE isWhiteSpace #-}
55 -- > ==> "\"ab\\\"c\""
56 quoteStr :: String -> String
57 quoteStr str = str `seq`
58 foldr (++) "" (["\""] ++ map quote str ++ ["\""])
60 quote :: Char -> String
65 -- |> parseWWWFormURLEncoded "aaa=bbb&ccc=ddd"
66 -- > ==> [("aaa", "bbb"), ("ccc", "ddd")]
67 parseWWWFormURLEncoded :: String -> [(String, String)]
68 parseWWWFormURLEncoded src
70 | otherwise = do pairStr <- splitBy (\ c -> c == ';' || c == '&') src
71 let (key, value) = break (== '=') pairStr
72 return ( unEscapeString key
73 , unEscapeString $ case value of