Skip to content

Commit 7fdd2d0

Browse files
committed
with-open accepts multiple bindings, patch from Meikel Brandmeyer
1 parent ef94567 commit 7fdd2d0

File tree

1 file changed

+24
-19
lines changed

1 file changed

+24
-19
lines changed

src/clj/clojure/core.clj

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1817,18 +1817,34 @@
18171817
"Reads one object from the string s"
18181818
[s] (clojure.lang.RT/readString s))
18191819

1820+
(defn subvec
1821+
"Returns a persistent vector of the items in vector from
1822+
start (inclusive) to end (exclusive). If end is not supplied,
1823+
defaults to (count vector). This operation is O(1) and very fast, as
1824+
the resulting vector shares structure with the original and no
1825+
trimming is done."
1826+
([v start]
1827+
(subvec v start (count v)))
1828+
([v start end]
1829+
(. clojure.lang.RT (subvec v start end))))
1830+
18201831
(defmacro with-open
1821-
"bindings => name init
1832+
"bindings => [name init ...]
18221833
1823-
Evaluates body in a try expression with name bound to the value of
1824-
init, and a finally clause that calls (.close name)."
1834+
Evaluates body in a try expression with names bound to the values
1835+
of the inits, and a finally clause that calls (.close name) on each
1836+
name in reverse order."
18251837
[bindings & body]
18261838
(if (vector? bindings)
1827-
`(let ~bindings
1828-
(try
1829-
~@body
1830-
(finally
1831-
(.close ~(first bindings)))))
1839+
(cond
1840+
(= (count bindings) 0) `(do ~@body)
1841+
(symbol? (bindings 0)) `(let ~(subvec bindings 0 2)
1842+
(try
1843+
(with-open ~(subvec bindings 2) ~@body)
1844+
(finally
1845+
(. ~(bindings 0) close))))
1846+
:else (throw (IllegalArgumentException.
1847+
"with-open only allows Symbols in bindings")))
18321848
(throw (IllegalArgumentException.
18331849
"with-open now requires a vector for its binding"))))
18341850

@@ -2023,17 +2039,6 @@
20232039
[s key]
20242040
(. clojure.lang.PersistentStructMap (getAccessor s key)))
20252041

2026-
(defn subvec
2027-
"Returns a persistent vector of the items in vector from
2028-
start (inclusive) to end (exclusive). If end is not supplied,
2029-
defaults to (count vector). This operation is O(1) and very fast, as
2030-
the resulting vector shares structure with the original and no
2031-
trimming is done."
2032-
([v start]
2033-
(subvec v start (count v)))
2034-
([v start end]
2035-
(. clojure.lang.RT (subvec v start end))))
2036-
20372042
(defn load-reader
20382043
"Sequentially read and evaluate the set of forms contained in the
20392044
stream/file"

0 commit comments

Comments
 (0)