Created
October 15, 2012 19:15
-
-
Save lfranchi/3894513 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
(use 'gloss.io 'gloss.core) | |
;; Support | |
(def flags {:RAW 1 | |
:JSON 2 | |
:FRAGMENT 4 | |
:COMPRESSED 8 | |
:DBOP 16 | |
:PING 32 | |
:RESERVED 64 | |
:SETUP 128 | |
;; Magic fall-through | |
:ANY (bit-not 0)}) | |
(defn has-value | |
"Returns if the desired map has the given value, returning | |
the associated key." | |
[m v] | |
(some #(if (= (val %) v) (key %)) m)) | |
(defn flag-from-value | |
[value] | |
(has-value flags value)) | |
(defn test-flag | |
"Does a not-zero?-bit-and of the arguments" | |
[x y] | |
(not (zero? (bit-and x y)))) | |
(defn to-byte-array | |
[longs] | |
(byte-array (map #(byte %) longs))) | |
;; gloss | |
(def inner (compile-frame | |
[:ubyte (repeated :ubyte :prefix :none)] | |
(fn [[flag body]] (let [b (if (test-flag flag (flags :COMPRESSED)) | |
body | |
(.getBytes body))] | |
[flag b])) | |
(fn [[flag body]] (let [b (if (test-flag flag (flags :COMPRESSED)) | |
body | |
(String. (to-byte-array body) (java.nio.charset.Charset/forName "utf-8")))] | |
[flag b])))) | |
(def frame (finite-frame | |
(prefix | |
:int32 | |
inc | |
dec) | |
inner)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment