Skip to content

Instantly share code, notes, and snippets.

@Gabrielll04
Last active January 21, 2024 00:27
Show Gist options
  • Save Gabrielll04/8ef29d88bad94e5a9c14b4a2d393b9ac to your computer and use it in GitHub Desktop.
Save Gabrielll04/8ef29d88bad94e5a9c14b4a2d393b9ac to your computer and use it in GitHub Desktop.
A readVarInt implementation using recursion.
import Data.Bits
import Data.Binary.Get
import Data.ByteString.Lazy (pack)
type VarInt = Integer
readVarInt :: Get VarInt
readVarInt = do
bs <- loop 0
return bs
where
loop acc = do
b <- getWord8
let currentByte = toInteger $ b .&. 0x7f
acc' = (acc `shiftL` 7) .|. currentByte
if (b .&. 0x80 /= 0)
then loop acc'
else return acc'
main :: IO ()
main = print $ runGet (readVarInt) (pack [0x7f]) -- this must return 127
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment