+instance Bounded IPv4Address where
+ -- | The minimum possible IPv4 address, 0.0.0.0.
+ minBound = IPv4Address minBound minBound minBound minBound
+
+ -- | The maximum possible IPv4 address, 255.255.255.255.
+ maxBound = IPv4Address maxBound maxBound maxBound maxBound
+
+
+
+
+instance Enum IPv4Address where
+ -- | Convert an 'Int' @x@ to an 'IPv4Address'. Each octet of @x@ is
+ -- right-shifted by the appropriate number of bits, and the fractional
+ -- part is dropped.
+ toEnum signed_x =
+ IPv4Address oct1 oct2 oct3 oct4
+ where
+ -- Convert the input Int to a Word32 before we proceed. On x86,
+ -- the Int that we get could be negative (half of all IP
+ -- addresses correspond to negative numbers), and then the magic
+ -- below doesn't work. The Word32 type is unsigned, so we do the
+ -- math on that and then convert everything back to Int later on
+ -- once we have four much-smaller non-negative numbers.
+ x = fromIntegral signed_x :: Word32
+
+ -- Chop off the higher octets. x1 = x `mod` 2^32, would be
+ -- redundant.
+ x2 = x `mod` 2^(24 :: Integer)
+ x3 = x `mod` 2^(16 :: Integer)
+ x4 = (fromIntegral $ x `mod` 2^(8 :: Integer)) :: Int
+ -- Perform right-shifts. x4 doesn't need a shift.
+ shifted_x1 = (fromIntegral $ x `quot` 2^(24 :: Integer)) :: Int
+ shifted_x2 = (fromIntegral $ x2 `quot` 2^(16 :: Integer)) :: Int
+ shifted_x3 = fromIntegral $ x3 `quot` 2^(8 :: Integer) :: Int
+ oct1 = toEnum shifted_x1 :: Octet
+ oct2 = toEnum shifted_x2 :: Octet
+ oct3 = toEnum shifted_x3 :: Octet
+ oct4 = toEnum x4 :: Octet
+
+ -- | Convert @addr@ to an 'Int' by converting each octet to an 'Int'
+ -- and shifting the result to the left by 0,8.16, or 24 bits.
+ fromEnum addr =
+ (shifted_oct1) + (shifted_oct2) + (shifted_oct3) + oct4
+ where
+ oct1 = fromEnum (octet1 addr)
+ oct2 = fromEnum (octet2 addr)
+ oct3 = fromEnum (octet3 addr)
+ oct4 = fromEnum (octet4 addr)
+ shifted_oct1 = oct1 * 2^(24 :: Integer)
+ shifted_oct2 = oct2 * 2^(16 :: Integer)
+ shifted_oct3 = oct3 * 2^(8 :: Integer)