1 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
3 -- | The 'Weight' type, its instances, and a Parsec parser to parse
4 -- one off the end of a 'Site'.
6 -- This is a simple newtype wrapper around an 'Int', meant to be
7 -- used wherever a weight or an RBL score is intended (to prevent
8 -- integer mixups). For example, the RBLs are all weighted with
9 -- 'Weight's, and when a user supplied a \"badness\" threshold, it
10 -- will be as a 'Weight' as well. The two are then comparable but
11 -- not with other 'Int's.
13 module Network.DNS.RBL.Weight (
26 import Text.Parsec.String ( Parser )
27 import Text.Read ( readMaybe )
29 import Network.DNS.RBL.Pretty ( Pretty(..) )
32 -- | The 'Weight' wrapper around an 'Int. We use
33 -- GeneralizedNewtypeDeriving to derive num automatically (so that we
34 -- can sum these things).
38 -- >>> let w1 = Weight 1
41 -- >>> let w2 = Weight 1
44 -- >>> let w3 = Weight 2
47 -- >>> sum [w1, w2, w3]
50 newtype Weight = Weight Int deriving (Eq, Num, Show)
53 -- | Pretty-print a 'Weight'. This just shows/prints the underlying 'Int'.
57 -- >>> pretty_print $ Weight 17
60 instance Pretty Weight where
61 pretty_show (Weight w) = show w
64 -- | Parse the weight multiplier off the end of an input 'Site'. This
65 -- expects there to be a \"multiplier\" character (an asterisk)
66 -- before the integral weight.
70 -- >>> import Text.Parsec ( parseTest )
72 -- Negative, zero, and positive integers are all supported:
74 -- >>> parseTest weight "*-5"
77 -- >>> parseTest weight "*0"
80 -- >>> parseTest weight "*17"
83 -- If the weight is empty, it defaults to @1@:
85 -- >>> parseTest weight ""
88 -- The default is used whenever parsing fails:
90 -- >>> parseTest weight "*hello"
93 -- The 'Pretty' instance works as intended:
95 -- >>> import Text.Parsec ( parse )
96 -- >>> pretty_print $ parse weight "" "*3"
99 weight :: Parser Weight
100 weight = try parse_weight <|> return (Weight 1)
104 sign <- (char '-') <|> (option '+' (char '+'))
106 case ( readMaybe w :: Maybe Int ) of
107 -- If "many1 digit" gives us a list of digits, we should be able
108 -- to convert that to an Int! It will overflow rather than fail
109 -- if the input is too big/small, so it should really always
111 Nothing -> unexpected "weight: readMaybe failed on a sequence of digits!"
112 Just k -> return $ Weight (if sign == '-' then negate k else k)