module Octane.Type.CompressedWord (CompressedWord(..), fromCompressedWord) where
import Data.Aeson ((.=))
import Data.Function ((&))
import qualified Control.DeepSeq as DeepSeq
import qualified Data.Aeson as Aeson
import qualified Data.Binary.Bits as BinaryBit
import qualified Data.Binary.Bits.Get as BinaryBit
import qualified Data.Binary.Bits.Put as BinaryBit
import qualified Data.Bits as Bits
import qualified GHC.Generics as Generics
import qualified Octane.Type.Boolean as Boolean
data CompressedWord = CompressedWord
{ limit :: Word
, value :: Word
} deriving (Eq, Generics.Generic, Show)
instance BinaryBit.BinaryBit CompressedWord where
getBits n = do
let theLimit = fromIntegral n
theValue <- getStep theLimit (bitSize theLimit) 0 0
pure (CompressedWord theLimit theValue)
putBits _ compressedWord = do
let theLimit = fromIntegral (limit compressedWord)
let theValue = fromIntegral (value compressedWord)
let maxBits = bitSize theLimit
let upper = (2 ^ (maxBits 1)) 1
let lower = theLimit upper
let numBits = if lower > theValue || theValue > upper
then maxBits
else maxBits 1
BinaryBit.putWord64be numBits theValue
instance DeepSeq.NFData CompressedWord where
instance Aeson.ToJSON CompressedWord where
toJSON compressedWord = Aeson.object
[ "Limit" .= limit compressedWord
, "Value" .= value compressedWord
]
fromCompressedWord :: (Integral a) => CompressedWord -> a
fromCompressedWord compressedWord = compressedWord & value & fromIntegral
bitSize :: (Integral a, Integral b) => a -> b
bitSize x = x & fromIntegral & logBase (2 :: Double) & ceiling
getStep :: Word -> Word -> Word -> Word -> BinaryBit.BitGet Word
getStep theLimit maxBits position theValue = do
let x = Bits.shiftL 1 (fromIntegral position)
if position < maxBits && theValue + x <= theLimit
then do
bit <- BinaryBit.getBits 0
let newValue = if Boolean.unpack bit then theValue + x else theValue
getStep theLimit maxBits (position + 1) newValue
else pure theValue