repeatedly-into as a macro

This commit is contained in:
Max Penet 2013-06-15 21:37:57 +02:00 committed by Peter Taoussanis
parent 823f2c3c46
commit e4cde95d54
2 changed files with 25 additions and 17 deletions

View file

@ -209,13 +209,15 @@
(defn coll-thaw
"Thaws simple collection types."
[coll ^DataInputStream s]
(utils/repeatedly-into coll (.readInt s) #(thaw-from-stream s)))
(utils/repeatedly-into coll
(.readInt s)
(thaw-from-stream s)))
(defn coll-thaw-kvs
"Thaws key-value collection types."
[coll ^DataInputStream s]
(utils/repeatedly-into coll (/ (.readInt s) 2)
(fn [] [(thaw-from-stream s) (thaw-from-stream s)])))
[(thaw-from-stream s) (thaw-from-stream s)]))
(defn- thaw-from-stream
[^DataInputStream s]
@ -260,8 +262,9 @@
;;; DEPRECATED
id-old-reader (read-string (.readUTF s))
id-old-string (.readUTF s)
id-old-map (apply hash-map (utils/repeatedly-into [] (* 2 (.readInt s))
#(thaw-from-stream s)))
id-old-map (apply hash-map (utils/repeatedly-into []
(* 2 (.readInt s))
(thaw-from-stream s)))
id-old-keyword (keyword (.readUTF s))
(throw (Exception. (str "Failed to thaw unknown type ID: " type-id))))))
@ -416,4 +419,4 @@
(thaw ba {:read-eval? read-eval?
:compressor (when compressed? compression/default-snappy-compressor)
:password password
:legacy-mode true}))
:legacy-mode true}))

View file

@ -13,18 +13,23 @@
clauses)
~(when default default))))
(defn repeatedly-into
(defmacro repeatedly-into
"Like `repeatedly` but faster and `conj`s items into given collection."
[coll n f]
(if-not (instance? clojure.lang.IEditableCollection coll)
(loop [v coll idx 0]
(if (>= idx n)
v
(recur (conj v (f)) (inc idx))))
(loop [v (transient coll) idx 0]
(if (>= idx n)
(persistent! v)
(recur (conj! v (f)) (inc idx))))))
[coll n & body]
`(let [coll# ~coll
n# ~n]
(if (instance? clojure.lang.IEditableCollection coll#)
(loop [v# (transient coll#) idx# 0]
(if (>= idx# n#)
(persistent! v#)
(recur (conj! v# ~@body)
(inc idx#))))
(loop [v# coll#
idx# 0]
(if (>= idx# n#)
v#
(recur (conj v# ~@body)
(inc idx#)))))))
(defmacro time-ns "Returns number of nanoseconds it takes to execute body."
[& body] `(let [t0# (System/nanoTime)] ~@body (- (System/nanoTime) t0#)))
@ -87,4 +92,4 @@
(comment (String. (ba-concat (.getBytes "foo") (.getBytes "bar")))
(let [[x y] (ba-split (.getBytes "foobar") 5)]
[(String. x) (String. y)]))
[(String. x) (String. y)]))