Skip to content

Instantly share code, notes, and snippets.

@mdallastella
Last active July 7, 2017 09:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdallastella/73dee0d73c441808d1dd121afdac502b to your computer and use it in GitHub Desktop.
Save mdallastella/73dee0d73c441808d1dd121afdac502b to your computer and use it in GitHub Desktop.
Write to a DataOutputStream whit a message specification
(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]])
(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