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 (defn coll-thaw
"Thaws simple collection types." "Thaws simple collection types."
[coll ^DataInputStream s] [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 (defn coll-thaw-kvs
"Thaws key-value collection types." "Thaws key-value collection types."
[coll ^DataInputStream s] [coll ^DataInputStream s]
(utils/repeatedly-into coll (/ (.readInt s) 2) (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 (defn- thaw-from-stream
[^DataInputStream s] [^DataInputStream s]
@ -260,8 +262,9 @@
;;; DEPRECATED ;;; DEPRECATED
id-old-reader (read-string (.readUTF s)) id-old-reader (read-string (.readUTF s))
id-old-string (.readUTF s) id-old-string (.readUTF s)
id-old-map (apply hash-map (utils/repeatedly-into [] (* 2 (.readInt s)) id-old-map (apply hash-map (utils/repeatedly-into []
#(thaw-from-stream s))) (* 2 (.readInt s))
(thaw-from-stream s)))
id-old-keyword (keyword (.readUTF s)) id-old-keyword (keyword (.readUTF s))
(throw (Exception. (str "Failed to thaw unknown type ID: " type-id)))))) (throw (Exception. (str "Failed to thaw unknown type ID: " type-id))))))

View file

@ -13,18 +13,23 @@
clauses) clauses)
~(when default default)))) ~(when default default))))
(defn repeatedly-into (defmacro repeatedly-into
"Like `repeatedly` but faster and `conj`s items into given collection." "Like `repeatedly` but faster and `conj`s items into given collection."
[coll n f] [coll n & body]
(if-not (instance? clojure.lang.IEditableCollection coll) `(let [coll# ~coll
(loop [v coll idx 0] n# ~n]
(if (>= idx n) (if (instance? clojure.lang.IEditableCollection coll#)
v (loop [v# (transient coll#) idx# 0]
(recur (conj v (f)) (inc idx)))) (if (>= idx# n#)
(loop [v (transient coll) idx 0] (persistent! v#)
(if (>= idx n) (recur (conj! v# ~@body)
(persistent! v) (inc idx#))))
(recur (conj! v (f)) (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." (defmacro time-ns "Returns number of nanoseconds it takes to execute body."
[& body] `(let [t0# (System/nanoTime)] ~@body (- (System/nanoTime) t0#))) [& body] `(let [t0# (System/nanoTime)] ~@body (- (System/nanoTime) t0#)))