(defn do-alts
"returns derefable [val port] if immediate, nil if enqueued"
[fret ports opts]
(let [flag (alt-flag)
n (count ports)
^ints idxs (random-array n)
priority (:priority opts)
ret
(loop [i 0]
(when (< i n)
(let [idx (if priority i (aget idxs i))
port (nth ports idx)
wport (when (vector? port) (port 0))
vbox (if wport
(let [val (port 1)]
(impl/put! wport val (alt-handler flag #(fret [% wport]))))
(impl/take! port (alt-handler flag #(fret [% port]))))]
(if vbox
(channels/box [@vbox (or wport port)])
(recur (inc i))))))]
(or
ret
(when (contains? opts :default)
(.lock ^Lock flag)
(let [got (and (impl/active? flag) (impl/commit flag))]
(.unlock ^Lock flag)
(when got
(channels/box [(:default opts) :default])))))))