Last active
May 8, 2020 13:27
-
-
Save Timo-Linde/4406efdb5012ce8de178c526ff5564dc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns mc.vint) | |
(def ^:private msb 2r10000000) | |
(defn read-more? | |
[b] | |
(-> (bit-and msb b) | |
(> 0))) | |
(defn clear-msb | |
[b] | |
(bit-and b 2r01111111)) | |
(defn combine-to-int | |
([left right] | |
(-> left | |
(bit-shift-left 7) | |
(bit-or (clear-msb right))))) | |
(defn read-vint | |
[byte-provider] | |
(loop [b (byte-provider) | |
byte-stack [b]] | |
(if (read-more? b) | |
(let [next-b (byte-provider)] | |
(recur next-b (conj byte-stack next-b))) | |
(->> byte-stack | |
(reverse) | |
(reduce combine-to-int))))) | |
(defn read-vint-is | |
[is] | |
(read-vint #(.read is))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns mc.vint_test | |
(:require [clojure.test :refer :all] | |
[mc.vint :refer :all])) | |
(deftest read-more-test | |
(testing "read-more" | |
(is (true? (read-more? 2r11110100))) | |
(is (true? (read-more? 2r10000001))) | |
(is (false? (read-more? 2r01110100))) | |
(is (false? (read-more? 2r00000001))) | |
(is (false? (read-more? 1))) | |
) | |
) | |
(deftest clear-msb-test | |
(testing "clear-msb-with-msb" | |
(is (= 2r01111111 (clear-msb 2r11111111))) | |
(is (= 2r01000001 (clear-msb 2r11000001))) | |
(is (= 2r01110100 (clear-msb 2r11110100))) | |
) | |
(testing "clear-msb-without-msb" | |
(is (= 2r01000001 (clear-msb 2r01000001))) | |
) | |
) | |
(deftest combine-to-int-test | |
(testing "combine-to-int" | |
(is (= 2r11101001000001 (combine-to-int 2r01110100 2r01000001))) | |
(is (= 2r100001011 (combine-to-int 2r10 2r100001011))) | |
(is (= 2r100001011 (combine-to-int 2 139))) | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment