Debian Codegraph @

src/Network/HTTP/Media/Utils.hs

raw
1 -- | Common utilities.
2 module Network.HTTP.Media.Utils
3 ( breakChar,
4 trimBS,
5 mediaChars,
6 isMediaChar,
7 tokenChars,
8 isTokenChar,
9 isValidToken,
10 )
11 where
12
13 import Data.ByteString (ByteString)
14 import qualified Data.ByteString.Char8 as BS
15 import Data.Char (isControl)
16
17 -- | Equivalent to 'Data.ByteString.break' (on equality against the given
18 -- character), but leaves out the byte that the string is broken on.
19 breakChar :: Char -> ByteString -> Maybe (ByteString, ByteString)
20 breakChar c = safeTail . BS.break (== c)
21 where
22 safeTail (a, b)
23 | BS.null b = Nothing
24 | otherwise = Just (a, BS.tail b)
25
26 -- | Trims tab and space characters from both ends of a ByteString.
27 trimBS :: ByteString -> ByteString
28 trimBS = fst . BS.spanEnd isLWS . BS.dropWhile isLWS
29 where
30 isLWS c = c == ' ' || c == '\t'
31
32 -- | List of the valid characters for a media-type `reg-name` as per RFC 4288.
33 mediaChars :: [Char]
34 mediaChars = ['A' .. 'Z'] ++ ['a' .. 'z'] ++ ['0' .. '9'] ++ "!#$&.+-^_"
35
36 -- | Evaluates whether the given character is valid in a media type `reg-name`
37 -- as per RFC 4288.
38 isMediaChar :: Char -> Bool
39 isMediaChar = (`elem` mediaChars)
40
41 -- | Evaluates whether the given character is valid in an HTTP header token as
42 -- per RFC 2616.
43 isTokenChar :: Char -> Bool
44 isTokenChar = (||) <$> not . isControl <*> (`notElem` separators)
45 where
46 separators =
47 [ '(',
48 ')',
49 '<',
50 '>',
51 '@',
52 ',',
53 ';',
54 ':',
55 '\\',
56 '"',
57 '/',
58 '[',
59 ']',
60 '?',
61 '=',
62 '{',
63 '}',
64 ' '
65 ]
66
67 -- | HTTP header token characters as per RFC 2616.
68 tokenChars :: [Char]
69 tokenChars = filter isTokenChar ['\0' .. '\127']
70
71 -- | Evaluates whether the given ASCII string is valid as an HTTP header token
72 -- as per RFC 2616.
73 isValidToken :: ByteString -> Bool
74 isValidToken = (&&) <$> not . BS.null <*> BS.all isTokenChar