Debian Codegraph @

Network/Wai/Application/Classic/Lang.hs

raw
1 {-# LANGUAGE OverloadedStrings #-}
2
3 module Network.Wai.Application.Classic.Lang (parseLang) where
4
5 import Control.Applicative hiding (optional)
6 import Data.Attoparsec.ByteString (Parser, takeWhile, parseOnly)
7 import Data.Attoparsec.ByteString.Char8 (char, string, count, space, digit, option, sepBy1)
8 import Data.ByteString.Char8 hiding (map, count, take, takeWhile, notElem)
9 import Data.List (sortBy)
10 import Data.Ord
11 import Prelude hiding (takeWhile)
12
13 -- |
14 -- >>> parseLang "en-gb;q=0.8, en;q=0.7, da"
15 -- ["da","en-gb","en"]
16
17 parseLang :: ByteString -> [ByteString]
18 parseLang bs = case parseOnly acceptLanguage bs of
19 Right ls -> map fst $ sortBy detrimental ls
20 _ -> []
21 where
22 detrimental = flip (comparing snd)
23
24 ----------------------------------------------------------------
25
26 acceptLanguage :: Parser [(ByteString,Int)]
27 acceptLanguage = rangeQvalue `sepBy1` (spaces *> char ',' *> spaces)
28
29 rangeQvalue :: Parser (ByteString,Int)
30 rangeQvalue = (,) <$> languageRange <*> quality
31
32 languageRange :: Parser ByteString
33 languageRange = takeWhile (`notElem` [32, 44, 59])
34
35 quality :: Parser Int
36 quality = option 1000 (string ";q=" *> qvalue)
37
38 qvalue :: Parser Int
39 qvalue = 1000 <$ (char '1' *> optional (char '.' *> range 0 3 digit))
40 <|> read3 <$> (char '0' *> option "0" (char '.' *> range 0 3 digit))
41 where
42 read3 n = read . take 3 $ n ++ repeat '0'
43 optional p = () <$ p <|> return ()
44
45 ----------------------------------------------------------------
46
47 range :: Int -> Int -> Parser a -> Parser [a]
48 range n m p = (++) <$> count n p <*> upto (m - n) p
49
50 upto :: Int -> Parser a -> Parser [a]
51 upto 0 _ = return []
52 upto n p = (:) <$> p <*> upto (n - 1) p <|> return []
53
54 spaces :: Parser ()
55 spaces = () <$ many space