module Network.HPACK.Huffman.Bit (
B(..)
, Bits
, fromBits
, toBits
) where
import Data.List (foldl')
import Data.Word (Word8)
data B = F
| T
deriving (Eq,Ord,Show)
fromBit :: B -> Word8
fromBit F = 0
fromBit T = 1
toBit :: Word8 -> B
toBit 0 = F
toBit 1 = T
toBit _ = error "toBit"
type Bits = [B]
fromBits :: Bits -> Word8
fromBits = foldl' (\x y -> x * 2 + y) 0 . map fromBit
toBits :: Word8 -> Bits
toBits = toBits' [] 0
toBits' :: Bits -> Int -> Word8 -> Bits
toBits' bs !cnt 0
| cnt == 8 = bs
| otherwise = replicate (8 cnt) F ++ bs
toBits' bs !cnt x = toBits' (b:bs) (cnt + 1) q
where
q = x `div` 2
r = x `mod` 2
b = toBit r