1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
{-# LANGUAGE DefaultSignatures, ScopedTypeVariables #-}
-- From http://stackoverflow.com/a/15911213
module Data.Text.ICU.BitMask
(
-- * Bit mask twiddling API
-- $api
-- * Types
ToBitMask(..)
-- * Functions
, fromBitMask
, highestValueInBitMask
) where
import Data.Bits ((.&.), (.|.))
import Data.Maybe (listToMaybe)
-- $api
-- Conversion to and from enumerated types representable as
-- a compact bitmask.
class ToBitMask a where
toBitMask :: a -> Int
instance (ToBitMask a) => ToBitMask [a] where
toBitMask = foldr ((.|.) . toBitMask) 0
fromBitMask :: (Enum a, Bounded a, ToBitMask a) => Int -> [a]
fromBitMask bm = filter inBitMask $ enumFrom minBound
where inBitMask val = (bm .&. toBitMask val) == toBitMask val
highestValueInBitMask :: (Enum a, Bounded a, ToBitMask a) => Int -> Maybe a
highestValueInBitMask = listToMaybe . reverse . fromBitMask
|