<commit_before>{-# LANGUAGE BangPatterns #-}

module Network.HPACK.Bit (
    B(..)
  , Bits
  , toInt
  , toBits
  ) where

import Data.List (foldl')

data B = F | T deriving (Eq,Ord,Enum,Show)

type Bits = [B]

-- |
--
-- >>> toInt [T,F,T,F,T,F,T,F]
-- 170
-- >>> toInt [F,T,F,T,F,T,F,T]
-- 85
toInt :: Bits -> Int
toInt = foldl' (\x y -> x * 2 + y) 0 . map fromEnum

-- |
--
-- >>> toBits 170
-- [T,F,T,F,T,F,T,F]
-- >>> toBits 85
-- [F,T,F,T,F,T,F,T]
toBits :: Int -> Bits
toBits = toBits' [] 0

toBits' :: Bits -> Int -> Int -> Bits
toBits' bs !cnt 0
  | cnt == 8 = bs
  | otherwise = replicate (8 - cnt) F ++ bs -- FIXME: performance
toBits' bs !cnt x = toBits' (b:bs) (cnt + 1) q
  where
    q = x `div` 2
    r = x `mod` 2
    b = if r == 0 then F else T
<commit_msg>doc up.<commit_after>{-# LANGUAGE BangPatterns #-}

module Network.HPACK.Bit (
    B(..)
  , Bits
  , toInt
  , toBits
  ) where

import Data.List (foldl')

-- | Data type for Bit.
data B = F -- ^ Zero
       | T -- ^ One
       deriving (Eq,Ord,Enum,Show)

-- | Bit sequence.
type Bits = [B]

-- | From 'Bits' to 'Int'.
--
-- >>> toInt [T,F,T,F,T,F,T,F]
-- 170
-- >>> toInt [F,T,F,T,F,T,F,T]
-- 85
toInt :: Bits -> Int
toInt = foldl' (\x y -> x * 2 + y) 0 . map fromEnum

-- | From 'Int' to 'Bits'.
--
-- >>> toBits 170
-- [T,F,T,F,T,F,T,F]
-- >>> toBits 85
-- [F,T,F,T,F,T,F,T]
toBits :: Int -> Bits
toBits = toBits' [] 0

toBits' :: Bits -> Int -> Int -> Bits
toBits' bs !cnt 0
  | cnt == 8 = bs
  | otherwise = replicate (8 - cnt) F ++ bs -- FIXME: performance
toBits' bs !cnt x = toBits' (b:bs) (cnt + 1) q
  where
    q = x `div` 2
    r = x `mod` 2
    b = if r == 0 then F else T

{'fraction_non_alphanumeric': 0.22442839951865223, 'fraction_numerical': 0.024067388688327317, 'mean_word_length': 2.1919385796545106, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 39, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4782209', 'n_tokens_mistral': 806, 'n_tokens_neox': 762, 'n_words': 215}