File: BitMask.hs

package info (click to toggle)
haskell-text-icu 0.8.0.5-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 536 kB
  • sloc: haskell: 1,210; ansic: 1,147; makefile: 4
file content (34 lines) | stat: -rw-r--r-- 908 bytes parent folder | download | duplicates (2)
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