Last active
July 7, 2017 09:27
-
-
Save mdallastella/73dee0d73c441808d1dd121afdac502b to your computer and use it in GitHub Desktop.
Write to a DataOutputStream whit a message specification
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
(import '[java.io DataOutputStream ByteArrayOutputStream]) | |
(defn write-int [out v] | |
(.writeInt out v)) | |
(defn write-string [out s] | |
(let [b (.getBytes s) | |
l (count s)] | |
(write-int out l) | |
(.write out b 0 l))) | |
(defn encode | |
[spec message] | |
(let [out (ByteArrayOutputStream.) | |
stream (DataOutputStream. out)] | |
(doall | |
(map | |
(fn [field] | |
(let [field-name (first field) | |
value (second field) | |
function (get spec field-name)] | |
(try | |
(apply function [stream value]) | |
(catch Exception e | |
(throw (Exception. (str (.getMessage e) " writing " field-name))))))) | |
message)) | |
(seq (.toByteArray out)))) | |
(def message-spec | |
{:id write-int | |
:first-name write-string | |
:last-name write-string | |
:age write-int}) | |
(encode | |
message-spec [[:id 1] | |
[:first-name "Marco"] | |
[:last-name "Dalla Stella"] | |
[:age 35]]) |
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
(import '[java.io DataOutputStream ByteArrayOutputStream]) | |
(defn write-int [out v] | |
(.writeInt out v)) | |
(defn write-string [out s] | |
(let [b (.getBytes s) | |
l (count s)] | |
(write-int out l) | |
(.write out b 0 l))) | |
(defn encode | |
[spec message] | |
(let [spec-order (:order (meta spec)) | |
out (ByteArrayOutputStream.) | |
stream (DataOutputStream. out)] | |
(doall | |
(map | |
(fn [field-name] | |
(let [value (get message field-name) | |
function (get spec field-name)] | |
(try | |
(apply function [stream value]) | |
(catch Exception e | |
(throw (Exception. (str (.getMessage e) " writing " field-name))))))) | |
spec-order)) | |
(seq (.toByteArray out)))) | |
(def message-spec | |
(with-meta | |
{:id write-int | |
:first-name write-string | |
:last-name write-string | |
:age write-int} | |
{:order [:id :first-name :last-name :age]})) | |
(encode | |
message-spec {:id 1 | |
:first-name "Marco" | |
:last-name "Dalla Stella" | |
:age 35}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment