Debian Codegraph @

src/Network/HTTP/Media/Encoding/Internal.hs

raw
1 -- | Defines the 'Encoding' accept header with an 'Accept' instance for use in
2 -- language negotiation.
3 module Network.HTTP.Media.Encoding.Internal
4 ( Encoding (..),
5 )
6 where
7
8 import Control.Monad (guard)
9 import Data.ByteString (ByteString)
10 import qualified Data.ByteString.Char8 as BS
11 import Data.CaseInsensitive (CI, original)
12 import qualified Data.CaseInsensitive as CI
13 import Data.Maybe (fromMaybe)
14 import Data.String (IsString (..))
15 import Network.HTTP.Media.Accept (Accept (..))
16 import Network.HTTP.Media.RenderHeader (RenderHeader (..))
17 import Network.HTTP.Media.Utils (isValidToken)
18
19 -- | Suitable for HTTP encoding as defined in
20 -- <https://tools.ietf.org/html/rfc7231#section-5.3.4 RFC7231>.
21 --
22 -- Specifically:
23 --
24 -- > codings = content-coding / "identity" / "*"
25 newtype Encoding = Encoding (CI ByteString)
26 deriving (Eq, Ord)
27
28 instance Show Encoding where
29 show = BS.unpack . renderHeader
30
31 instance IsString Encoding where
32 fromString str =
33 flip fromMaybe (parseAccept $ BS.pack str) $
34 error $
35 "Invalid encoding literal " ++ str
36
37 instance Accept Encoding where
38 -- This handles the case where the header value is empty, but it also
39 -- allows technically invalid values such as "compress;q=0.8,;q=0.5".
40 parseAccept "" = Just $ Encoding "identity"
41 parseAccept bs = do
42 guard $ isValidToken bs
43 return $ Encoding (CI.mk bs)
44
45 matches _ (Encoding "*") = True
46 matches a b = a == b
47
48 moreSpecificThan _ (Encoding "*") = True
49 moreSpecificThan _ _ = False
50
51 instance RenderHeader Encoding where
52 renderHeader (Encoding e) = original e