Skip to content

Instantly share code, notes, and snippets.

@97jaz
Created August 5, 2019 18:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 97jaz/2884d660bb16d006a2c099639ec4b893 to your computer and use it in GitHub Desktop.
Save 97jaz/2884d660bb16d006a2c099639ec4b893 to your computer and use it in GitHub Desktop.
#lang racket/base
(define (signed-var-int val)
(cond
[(bitwise-bit-set? val 31)
(bitwise-ior val (bitwise-not #xffffffff))]
[else
val]))
(define (read-var-int in)
(let loop ([num-read 0] [result 0])
(define read (read-byte in))
(define value (bitwise-and read #b01111111))
(define new-result
(bitwise-ior result
(arithmetic-shift value (* 7 num-read))))
(define new-num-read (add1 num-read))
(when (> new-num-read 5)
(error "var-int is too big"))
(if (zero? (bitwise-and read #b10000000))
(signed-var-int new-result)
(loop new-num-read new-result))))
(define (write-var-int out value)
(let loop ([value (bitwise-and value #xffffffff)])
(define temp (bitwise-and value #b01111111))
(define new-value (arithmetic-shift value -7))
(cond
[(zero? new-value)
(write-byte temp out)]
[else
(write-byte (bitwise-ior temp #b10000000) out)
(loop new-value)])))
(define (read-var-int/bytes bstr)
(read-var-int (open-input-bytes bstr)))
(define (write-var-int/bytes value)
(define out (open-output-bytes))
(write-var-int out value)
(get-output-bytes out))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment